Search completed in 1.30 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.
...And 27 more matches
return - JavaScript
the re
turn statement ends function execution and specifies a value to be re
turned to the function caller.
... syntax re
turn [[expression]]; expression the expression whose value is to be re
turned.
... if omitted, undefined is re
turned instead.
...And 11 more matches
Error codes returned by Mozilla APIs
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.
...this error may be re
turned by various components that use files to indicate that necessary files are not in an expected format.
...And 6 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?
... unreachable code after a re
turn statement might occur in these situations: when using an expression after a re
turn statement, or when using a semicolon-less re
turn statement but including an expression directly after.
...And 5 more matches
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.
...And 5 more matches
Components.returnCode
components.re
turncode is a property which can hold an xpcom re
turn code additionally to the value re
turned by the re
turn statement.
... note that components.re
turncode is currently non-functional due to bug 287107.
... usage components.re
turncode is a property that can be used to indicate to an xpcom caller of the javascript method that the method is re
turning a specific nsresult code.
...And 4 more matches
Event.returnValue - Web APIs
the event property re
turnvalue indicates whether the default action for this event has been prevented or not.
... note: while re
turnvalue has been adopted into the dom standard, it is present primarily to support existing code.
... 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.
...And 4 more matches
HTMLDialogElement.returnValue - Web APIs
the re
turnvalue property of the htmldialogelement interface gets or sets the re
turn value for the <dialog>, usually to indicate which button the user pressed to close it.
... syntax dialoginstance.re
turnvalue = 'myre
turnvalue'; var myre
turnvalue = dialoginstance.re
turnvalue; value a domstring representing the re
turnvalue of the dialog.
...n> </select> </label></p> <menu> <button>cancel</button> <button>confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var dialog = document.getelementbyid('favdialog'); dialog.re
turnvalue = 'favanimal'; function opencheck(dialog) { if (dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } function handleuserinput(re
turnvalue) { if (re
turnvalue === 'cancel' || re
turnvalue == null) { // user canceled the dialog, do nothing } else if (re
turnvalue === 'confirm...
...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.
... a re
turn or yield statement is called outside of a function.
...And 3 more matches
JS_SetCallReturnValue2
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.
...And 2 more matches
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.
... learn more general knowledge
turn on wikipedia webrtc protocols technical reference specification specification update for ipv6 ...
Index - Web APIs
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.
... 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).
... 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.
...And 1675 more matches
Index
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.
... 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.
...And 178 more matches
Index
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.
... 28 components.re
turncode xpcom:language bindings, xpconnect no summary!
...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.
...And 114 more matches
sslfnc.html
re
turns the function re
turns one of these values: if successful, secsuccess.
... the policy flags for all cipher suites are
turned off by default, disallowing all cipher suites.
... re
turns the function re
turns one of these values: if successful, secsuccess.
...And 110 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).
... 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.
...And 110 more matches
IAccessibleTable
in this case iaccessible2.indexinparent() will re
turn the child index which then can be used when calling rowindex() and columnindex().
...this object attribute is obtained by parsing the attribute string re
turned by iaccessible2.attributes().
...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().
...And 80 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"...
...){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":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","sub...
...string","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,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.length,c=n...
...And 78 more matches
Document - Web APIs
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.
...And 77 more matches
Shell global objects
timesaccessed re
turns a number that indicates how many times this variable is accessed perfmeasurement see perfmeasurement.jsm.
...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.
...this is what debugger.source.prototype.elementattributename re
turns.
...And 73 more matches
Parser API
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.
...this string is not meaningful to the parsing process, but is produced as part of the source location information in the re
turned ast nodes.
...And 71 more matches
IAccessibleText
when a method doesn't implement this method it must re
turn s_false.
... re
turn value e_invalidarg if bad [in] passed.
...attributes() re
turns text() attributes.
...And 67 more matches
nsIDOMWindowUtils
imageanimationmode unsigned short re
turns the image animation mode of the window.
... imeisopen boolean re
turns the ime open state.
... imestatus unsigned long re
turns the current ime status.
...And 60 more matches
Window - Web APIs
staticrange read only re
turns a staticrange() constructor which creates a staticrange object.
... 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 56 more matches
Expressions and operators - JavaScript
(x = y) re
turn value and chaining like most expressions, assignments like x = y have a re
turn value.
...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.
...And 56 more matches
Debugger.Object - Firefox Developer Tools
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).
... 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.
...And 54 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.
... 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.
...And 52 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.
...And 50 more matches
Starting WebLock
ns_imethodimp weblock::observe(nsisupports *asubject, const char *atopic, const prunichar *adata) { re
turn ns_ok; } notification via the observer service is somewhat indirect.
...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.
... 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.
...And 49 more matches
Navigator - Web APIs
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.
...And 46 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
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.
...conditionistrue : conditionisfalse; for example, to retrieve an element, you would use: function getelement(aid){ re
turn (document.getelementbyid) ?
...the method re
turns an array in javascript, and can be called on the document element or other nodes to search only their subtree.
...And 45 more matches
Graceful asynchronous programming with Promises - Learn web development
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 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 45 more matches
tabbrowser - Archive of obsolete content
selectedbrowser type: browser element this read-only property re
turns the currently displayed browser element.
... tabcontainer type: tabs element re
turns the tabs element that contains the tabs.
...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.
...And 44 more matches
Debugger - Firefox Developer Tools
this function should re
turn a resumption value, which determines how the debuggee should continue.
...most handler functions can re
turn a resumption value indicating how the debuggee’s execution should proceed.
... this method’s re
turn value is ignored.
...And 43 more matches
JavaScript Daemons Management - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0.html |*| \*/ "use strict"; /**************************** * the daemon system * ****************************/ /* the global "daemon" constructor */ function daemon (oowner, ftask, nrate, nlen, finit, fonstart) { if (!(this && this instanceof daemon)) { re
turn; } if (arguments.length < 2) { throw new typeerror("daemon - not enough arguments"); } if (oowner) { this.owner = oowner }; this.task = ftask; if (isfinite(nrate) && nrate > 0) { this.rate = math.floor(nrate); } if (nlen > 0) { this.length = math.floor(nlen); } if (fonstart) { this.onstart = fonstart; } if (finit) { this.onstop = finit; finit.call(oowner, t...
...-1 : 1; var bbreak = odmn.task.call(odmn.owner, odmn.index, odmn.length, odmn.backw) === false, bend = odmn.isatend(), binvert = odmn.reversals > 0; if (bend && !binvert || bbreak) { odmn.pause(); re
turn false; } if (bend && binvert) { odmn.backw = !odmn.backw; odmn.reversals--; } re
turn true; }; /* system not required daemon global object methods */ /** * daemon global object optional methods (shortcuts).
... **/ daemon.construct = function (aargs) { var odmn = new this.blank(); this.apply(odmn, aargs); re
turn odmn; }; daemon.buildaround = function (octx, nrate, nlen) { if (!octx.perform) { throw new typeerror("you cannot create a daemon around an object devoid of a \"perform\" function"); } re
turn new this(octx, octx.perform, nrate || null, nlen || null, octx.create || null, octx.prepare || null); }; /* warning!
...And 42 more matches
Element - Web APIs
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.clientheight read only re
turns a number representing the inner height of the element.
...And 42 more matches
source-editor.jsm
re
turn value true if there are changes that can be redone, otherwise false.
... re
turn value true if there are changes that can be undone, otherwise false.
... 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.
...And 41 more matches
DevTools API - Firefox Developer Tools
re
turn value: a promise that is fulfilled with the toolbox instance once it has been initialized and the selected tool is loaded.
... re
turn value: toolbox object or undefined if there's no toolbox for the given target..
... re
turn value: a promise that is fulfilled once the toolbox has been destroyed.
...And 40 more matches
Index - Archive of obsolete content
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.
...in calling this method, the editor is created underneath and the event listeners are all prepa if (ns_failed(rv)) re
turn ns_error_failure; // we are not setup??!!
... 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.
...And 39 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 = ...
...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(); 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 co...
...lor; } 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.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { re
turn (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = func...
...And 38 more matches
Editor Embedding Guide - Archive of obsolete content
in calling this method, the editor is created underneath and the event listeners are all prepa if (ns_failed(rv)) re
turn ns_error_failure; // we are not setup??!!
... getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand.
... getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand.
...And 37 more matches
WebGL constants - Web APIs
the webgl api provides several constants that are passed into or re
turned by functions.
... 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.
...And 37 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 = ...
...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(); 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 co...
...lor; } 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.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { re
turn (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = func...
...And 37 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
you can also use the unary + operator to convert values to numbers: + '42'; // 42 + '010'; // 10 + '0x10'; // 16 a special value called nan (short for "not a number") is re
turned if the string is non-numeric: parseint('hello', 10); // nan nan is toxic: if you provide it as an operand to any mathematical operation, the result will also be nan: nan + 5; // nan you can test for nan using the built-in isnan() function: isnan(nan); // true javascript also has the special values infinity and -infinity: 1 / 0; // infinity -1 / 0; // -infinity you can test for inf...
...inity, -infinity and nan values using the built-in isfinite() function: isfinite(1 / 0); // false isfinite(-infinity); // false isfinite(nan); // false the parseint() and parsefloat() functions parse a string until they reach a character that isn't valid for the specified number format, then re
turn the number parsed up to that point.
... if you query a non-existent array index, you'll get a value of undefined in re
turn: typeof a[90]; // undefined if you take the above about [] and length into account, you can iterate over an array using the following for loop: for (var i = 0; i < a.length; i++) { // do something with a[i] } es2015 introduced the more concise for...of loop for iterable objects such as arrays: for (const currentvalue of a) { // do something with currentvalue } you could also iterate o...
...And 37 more matches
Node - Web APIs
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.
... node.baseuriread only re
turns a domstring representing the base url of the document containing the node.
... node.childnodesread only re
turns a live nodelist containing all the children of this node.
...And 36 more matches
StringView - Archive of obsolete content
the code stringview.js "use strict"; /*\ |*| |*| :: number.isinteger() polyfill :: |*| |*| /docs/web/javascript/reference/global_objects/number/isinteger |*| \*/ if (!number.isinteger) { number.isinteger = function isinteger (nval) { re
turn typeof nval === "number" && isfinite(nval) && nval > -9007199254740992 && nval < 9007199254740992 && math.floor(nval) === nval; }; } /*\ |*| |*| stringview mdndeveloper network |*| |*| revision #12, march 21st, 2017 |*| |*| https://developer.mozilla.org/add-ons/code_snippets/stringview |*| https://developer.mozilla.org/docs/user:fusionchess |*| https://github.com/madmurphy/stringview.js |...
... */ var nlen = achars.length, npart = achars[nidx]; re
turn npart > 251 && npart < 254 && nidx + 5 < nlen ?
...so...: */ (nchar / 1073741824); atarget[nidx++] = 0x80 /* 128 */ + ((nchar >>> 24) & 0x3f /* 63 */); atarget[nidx++] = 0x80 /* 128 */ + ((nchar >>> 18) & 0x3f /* 63 */); atarget[nidx++] = 0x80 /* 128 */ + ((nchar >>> 12) & 0x3f /* 63 */); atarget[nidx++] = 0x80 /* 128 */ + ((nchar >>> 6) & 0x3f /* 63 */); atarget[nidx++] = 0x80 /* 128 */ + (nchar & 0x3f /* 63 */); } re
turn nidx; }; stringview.getutf8charlength = function (nchar) { re
turn nchar < 0x80 ?
...And 35 more matches
Bytecode Descriptions
this is how we implement typeof step 2, making typeof nonexistingvariable re
turn "undefined" instead of throwing a referenceerror.
...(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.
...both operations call a js method which scripts can define however they want, so they check afterwards that the method re
turned an object.
...And 35 more matches
nsINavBookmarksService
for js or from other components, just please be very careful to close the batch, especially when encountering an error and re
turning early.
... re
turn value re
turns the id of the newly-inserted folder.
... re
turn value re
turns the id of the newly-inserted folder.
...And 35 more matches
Math - JavaScript
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.
...And 35 more matches
IAccessible2
nrelations ); hresult role([out] long role ); hresult scrollto([in] enum ia2scrolltype scrolltype ); hresult scrolltopoint([in] enum ia2coordinatetype coordinatetype, [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.
...extendedrole() re
turns the extended role.
...And 34 more matches
lang/type - Archive of obsolete content
globals functions isundefined(value) re
turns true if value is undefined, false otherwise.
... re
turns boolean : boolean indicating if value is undefined.
... isnull(value) re
turns true if value is null, false otherwise.
...And 33 more matches
JSAPI User Guide
rootedobject global(cx); global = js_newglobalobject(cx, &globalclass, nullptr, js::dontfireonnewglobalhook); if (!global) re
turn 1; // enter the new global object's compartment.
... if (!js_initstandardclasses(cx, global)) re
turn 1; // your application code here.
... re
turn 0; } int main(int argc, const char *argv[]) { // initialize the js engine.
...And 33 more matches
nsIHTMLEditor
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.
... 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.
...And 33 more matches
nsIXPConnect
void debugdumpobject(in nsisupports acomobj, in short depth); [noscript,notxpcom] prbool definedomquickstubs(in jscontextptr cx, in jsobjectptr proto, in pruint32 flags, in pruint32 interfacecount, [array, size_is(interfacecount)] in nsiidptr interfacearray); jsval evalinsandboxobject(in astring source, in jscontextptr cx, in nsixpconnectjsobjectholder sandbox, in prbool re
turnstringonly); native code only!
... re
turn value missing description exceptions thrown missing exception missing 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 descrip...
...tion 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 missing description asourcetext missing description exceptions thrown missing exception missing description debugdumpjsstack() void debugdumpjsstack( in prbool showargs, in prbool showlocals, in prbool showthisprops ); parameters showargs missing description showlocals missing description showthisprops ...
...And 33 more matches
Debugger.Object - Firefox Developer Tools
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).
... 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.
...And 33 more matches
lang/functional - Archive of obsolete content
globals functions method(lambda) takes a function and re
turns a method associated with an object.
... 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.
...And 32 more matches
Space Manager Detailed Design - Archive of obsolete content
*/ nsiframe* getframe() const { re
turn mframe; } /** * translate the current origin by the specified (dx, dy).
... */ void translate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * re
turns the current translation from local coordinate space to * world coordinate space.
... */ 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.
...And 32 more matches
Functions - JavaScript
a function in javascript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and re
turn an output where there is some obvious relationship between the input and the output.
... 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.
...And 32 more matches
Index - XPath
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.
...And 32 more matches
nsISessionStore
re
turn value an nsidomnode representing the new tab, the content of which is a duplicate of atab.
... 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.
...And 31 more matches
Date - JavaScript
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.
...2 to 7) and re
turns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored.
...And 31 more matches
nsIVariant
re
turn value the value is converted to an 8-bit string in the iso-8859-1 character set.
...(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.
...And 30 more matches
WebGLRenderingContext - Web APIs
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.
...And 30 more matches
JSAPI Cookbook
} 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; } ...
... */ 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::rootedobject x(cx, js_newarrayobject(cx, 0)); if (!x) re
turn false; creating an object // javascript var x = {}; // or "x = object()", or "x = new object" /* jsapi */ js::rootedobject x(cx, js_newplainobject(cx)); // or js_newobject(cx, js::nullptr(), js::nullptr(), js::nullptr()); if (!x) re
turn false; constructing an object with new // javascript var person = new person("dave", 24); it looks so simple in javascript, but a jsapi application has to do three things here: look up the constructor, person prepare the arguments ("dave", 24) call js_new to simulate the new keyword (if your constructor doesn't take any arguments, you can skip the second step and call js_...
...And 29 more matches
Places utilities for JavaScript
if the interface isn't available to that node, null is re
turned.
... anode - the bookmark aiid - the re
turn interface wanted.
... 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.
...And 29 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.
... 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.
...And 29 more matches
String - JavaScript
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.
...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.
...(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.
...And 29 more matches
listbox - Archive of obsolete content
currentitem type: listitem element re
turns the currently focused item in the list box, which is only useful in a multiple selection 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.
...And 28 more matches
richlistbox - Archive of obsolete content
currentitem type: listitem element re
turns the currently focused item in the list box, which is only useful in a multiple selection 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.
...And 28 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...
...(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); 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...
...And 28 more matches
JXON - Archive of obsolete content
_item> <catalog_item gender="women's"> <item_number>rrx9856</item_number> <discount_until>dec 25, 1995</discount_until> <price>42.50</price> <size description="medium"> <color_swatch image="black_cardigan.jpg">black</color_swatch> </size> </catalog_item> </product> <script type="text/javascript"><![cdata[function matchwo(a,b) { if (a < b && a < 0) { re
turn 1; } else { re
turn 0; } }]]></script> </catalog> first, create a dom tree like the previous example as described in the how to create a dom tree article.
...|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ function parsetext (svalue) { if (/^\s*$/.test(svalue)) { re
turn null; } if (/^(?:true|false)$/i.test(svalue)) { re
turn svalue.tolowercase() === "true"; } if (isfinite(svalue)) { re
turn parsefloat(svalue); } if (isfinite(date.parse(svalue))) { re
turn new date(svalue); } re
turn svalue; } function jxontree (oxmlparent) { var nattrlen = 0, nlength = 0, scollectedtxt = ""; if (oxmlparent.haschildnodes()) { for (var onode, sprop, vcontent, nitem = ...
... jxontree.prototype.valueof = function () { re
turn this.keyvalue; }; jxontree.prototype.tostring = function () { re
turn string(this.keyvalue); }; jxontree.prototype.getitem = function (nitem) { if (nlength === 0) { re
turn null; } var ncount = 0; for (var skey in this) { if (ncount === nitem) { re
turn this[skey]; } ncount++; } re
turn null; }; jxontree.prototype.getattribute = function (nattrid) { if (nattrlen === 0 || nattrid + 1 > nattr...
...And 27 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
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.
... 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.
... 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.
...And 27 more matches
Dict.jsm
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.
... keys iterator re
turns an iterator over all the keys in the dictionary.
...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
core/promise - Archive of obsolete content
instead of structuring our programs into logical black boxes: function blackbox(a, b) { var c = assemble(a); re
turn combine(b, c); } we're forced into 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.displayerr...
...or(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(question, function continuewith(result) { answers = result; 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.
...And 26 more matches
An Overview of XPCOM
implementation of nsisupports interface // initialize the 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 oriented programming.
...in xpcom, all interface methods should re
turn an nsresult error value (see the xpcom api reference for a listing of these error codes).
...And 26 more matches
nsIFile
prfiledescstar opennsprfiledesc(in long flags, in long mode); void renameto(in nsifile newparentdir, in astring newname); void remove(in boolean recursive); void reveal(); void setrelativedescriptor(in nsifile fromfile, in acstring relativedesc); attributes attribute type description directoryentries nsisimpleenumerator re
turns an enumeration of the elements in a directory.
... parent nsifile this attribute re
turns the parent nsifile for this nsifile.
... example, this could re
turn "/home/user/foo.txt" or "c:\images\my.jpeg" permissions unsigned long the value of this attribute is a unix-style file permission mask for this nsifile.
...And 26 more matches
HTMLMediaElement - Web APIs
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.controlslist read only re
turns a domtokenlist that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls.
... htmlmediaelement.currentsrc read only re
turns a domstring with the absolute url of the chosen media resource.
...And 26 more matches
Indexed collections - JavaScript
calling arr.length will re
turn arraylength, but the array doesn't contain any elements.
...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).
...And 26 more matches
Encrypt Decrypt_MAC_Using Token
*/ 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.
...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"); } 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.
...And 25 more matches
Proxy Auto-Configuration (PAC) file - HTTP
description re
turns a string describing the configuration.
... the format of this string is defined in re
turn value format below.
... re
turn value format the javascript function re
turns a single string if the string is null, no proxies should be used the string can contain any number of the following building blocks, separated by a semicolon: direct connections should be made directly, without any proxies proxy host:port the specified proxy should be used socks host:port the specified socks server should be used recent versions of firefox support as well: http host:port the specified proxy should be used https host:port the specified https proxy should be used socks4 host:port socks5 host:port the specified socks server (with the specified sock version) should be used if there are multiple semicolon-separated settings, the left-most setting will be used, until firefox fails to establish the conne...
...And 25 more matches
Array - JavaScript
rry') // add to the front // ["strawberry", "banana"] find the index 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"] copy an array let shallowcopy = fruits.slice() // this is how to make a copy // ["strawberry", "mango"] accessing array elements javascript arrays are zero-indexed.
... using an invalid index number re
turns undefined.
...And 25 more matches
Promise.prototype.then() - JavaScript
the then() method re
turns a promise.
...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.
...if it is not a function, it is internally replaced with an "identity" function (it re
turns the received argument).
...And 25 more matches
Modularization techniques - Archive of obsolete content
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.
...a successful queryinterface() will call addref() on the requested interface before re
turning.
...And 24 more matches
Making asynchronous programming easier with async and await - Learn web development
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.
... 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?
...And 24 more matches
IPDL Tutorial
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.
... 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.
...the message is sent, and the c++ method re
turns immediately.
...And 24 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.
... re
turn value the nsiaccessible for the given dom node.
... getaccessibleinshell() re
turn an nsiaccessible for a dom node in the given pres shell.
...And 24 more matches
nsITreeView
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.
... re
turn value true if a drop is allowed at the current location; otherwise false.
...to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always re
turn false from candropbeforeafter().
...And 24 more matches
Comparing Reflect and Object methods - JavaScript
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.
...And 24 more matches
CustomizableUI.jsm
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.
... parameters aproperties the specification for the widget re
turn value a wrapper around the created 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).
...And 23 more matches
nsIAccessibleTable
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).
... re
turn value an nsiaccessible object.
...And 23 more matches
nsIAnnotationService
re
turn value re
turns a page annotation.
... re
turn value re
turns an item annotation.
... re
turn value re
turns a string value page annotation.
...And 23 more matches
nsIWindowMediator
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.
...And 23 more matches
Using the CSS Typed Object Model - Web APIs
<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().
...each for (const [prop, val] of defaultcomputedstyles) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(prop)); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode(val)); styleslist.appendchild(cssvalue); } the computedstylemap() method re
turns a stylepropertymapreadonly object containing the size property, which indicates how many properties are in the map.
...onst cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode( allcomputedstyles.get(ofinterest[i]))); styleslist.appendchild(cssvalue); } we included border-left-color to demonstrate that, had we included all the properties, every value that defaults to currentcolor (including caret-color, outline-color, text-decoration-color, column-rule-color, etc.) would re
turn rgb(255, 0, 0).
...And 23 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...
...perty 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.
... 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.
...And 23 more matches
Introduction to using XPath in JavaScript - XPath
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.
... 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.
... resulttype: a constant that specifies the desired result type to be re
turned as a result of the evaluation.
...And 23 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)) { ...
... 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"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, uns...
...igned 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_digestfinal(ctx, mac, maclen, maxlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestfinal()\n"); } re
turn secsuccess; } /* * compute mac */ secstatus computemac(pk11context *ctxmac, unsigned char *ptext, unsigned int ptextlen, unsigned char *mac, unsigned int *maclen, unsigned int maxlen) { secstatus rv = macinit(ctxmac); if (rv !=...
...And 22 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)) { ...
... 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"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, uns...
...igned 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_digestfinal(ctx, mac, maclen, maxlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestfinal()\n"); } re
turn secsuccess; } /* * compute mac */ secstatus computemac(pk11context *ctxmac, unsigned char *ptext, unsigned int ptextlen, unsigned char *mac, unsigned int *maclen, unsigned int maxlen) { secstatus rv = macinit(ctxmac); if (rv !=...
...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
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)) { ...
... 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"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, uns...
...igned 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_digestfinal(ctx, mac, maclen, maxlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestfinal()\n"); } re
turn secsuccess; } /* * compute mac */ secstatus computemac(pk11context *ctxmac, unsigned char *ptext, unsigned int ptextlen, unsigned char *mac, unsigned int *maclen, unsigned int maxlen) { secstatus rv = macinit(ctxmac); if (rv !=...
...And 22 more matches
sample2
on earlier versions of nss that * don't support error tables, pr_errortostring will re
turn "unknown code".
...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
nsIPropertyBag2
t32 getpropertyasint32(in astring prop); print64 getpropertyasint64(in astring prop); void getpropertyasinterface(in astring 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.
...And 22 more matches
io/file - Archive of obsolete content
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.
...And 21 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...
...// this block also invokes a function to write registry keys (plid) and checks re
turn from key writing // this block invokes refreshplugins() to ensure that plugin and xpt are available for use immediately if (errblock1 == success) { // installation to the current browser was a success - this is the most important job of this script!
... * * @param empty param list **/ function createsecondaryinstall() { // use getfolder in such a way that it creates c:\winnt\system32\myplugin secondaryfolder = getfolder("win system", company_name); // if secondaryfolder is null, then there has been an error if(!secondaryfolder) re
turn nosecondaryinstall; else { // we have admin privileges to write to the win system directory // so we will set up dll and xpt in their new home errblock2 = addfile (plid, version, plugin_file, secondaryfolder, null); // something went wrong if errblock2 is not 0 if (errblock2!=0) { logcomment("could not add " + plugin_file + " to " + secondaryfolder + ":" + errblock2); re
turn...
...And 21 more matches
Old Proxy API - Archive of obsolete content
calltrap is a variable-argument function(args) { re
turn any; } that reifies “proxy(args)”.
... constructtrap is an optional variable-argument function(args) { re
turn any-object; } that reifies “new proxy(args)”.
... 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.
...And 21 more matches
Examples
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.
...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.
...And 21 more matches
Microdata DOM API - Web APIs
it re
turns a nodelist containing the items with the specified types, or all types if no argument is specified.
...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.
...when called, the method must re
turn a live nodelist object containing all the elements in the document, in tree order, that are each top-level microdata items whose types include all the types specified in the method's argument, having obtained the types by splitting the string on spaces.
...And 21 more matches
Promise - JavaScript
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.
... as the promise.prototype.then() and promise.prototype.catch() methods re
turn promises, they can be chained.
...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 ...
...And 21 more matches
Tree View Details - Archive of obsolete content
the view will need to re
turn 0 for the outermost rows and higher values for inner 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.
... 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.
...And 20 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) {...
... 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"); } 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(pk11con...
...text *ctx, unsigned char *mac, unsigned int *maclen, unsigned int maxlen) { secstatus rv = pk11_digestfinal(ctx, mac, maclen, maxlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestfinal()\n"); } re
turn secsuccess; } /* * compute mac */ secstatus computemac(pk11context *ctxmac, unsigned char *ptext, unsigned int ptextlen, unsigned char *mac, unsigned int *maclen, unsigned int maxlen) { secstatus rv = macinit(ctxmac); if (rv != secsuccess) re
turn rv; rv = macupdate(ctxmac, ptext, ptextlen); if (rv != secsuccess) re
turn rv; rv = macfinal(ctxmac, mac, maclen, maxlen); re
turn rv; } /* * writetoheaderfile */ secstatus writetoheaderfile(const char *buf, unsigned int len, headertype type, prfiledesc *outfile) { secstatus rv; char header[40]; char trailer[40]; char *ou...
...And 20 more matches
Creating the Component Code
once enabled, this "weblock" mode is password protected and persists until it is
turned off by the password holder.
...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.
...the key to this interface is that the re
turn type of getclassobject does not have to be an nsifactory.
...And 20 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.
...And 20 more matches
IAccessibleTableCell
g column, [out] long rowextents, [out] long columnextents, [out] boolean isselected ); [propget] hresult rowextent([out] long nrowsspanned ); [propget] hresult rowheadercells([out, size_is(, nrowheadercells,)] iunknown cellaccessibles, [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.
...[propget] hresult columnextent( [out] long ncolumnsspanned ); parameters ncolumnsspanned re
turns the 1 based column extent of the specified cell.
... re
turn value s_ok.
...And 20 more matches
this - JavaScript
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, bec...
...as a result, they incorrectly re
turned the window object.
... derived classes must not re
turn before calling super(), unless they re
turn an object or have no constructor at all.
...And 20 more matches
async function - JavaScript
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.
...the resolved value of the promise is treated as the re
turn value of the await expression.
... async functions always re
turn a promise.
...And 20 more matches
window/utils - Archive of obsolete content
the exception is the windows() function which re
turns an array of currently opened windows.
... re
turns nsidomwindow: the topmost browser window.
... getinnerid(window) re
turns the id of the specified window's current inner window.
...And 19 more matches
Index
it's important to note that nss requires strict cleanup for all handles re
turned by nss.
...the data will be processed and either re
turned directly or sent to a callback function registered in the context.
... * 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 h...
...And 19 more matches
HTMLElement - Web APIs
htmlelement.accesskeylabel read only re
turns a domstring containing the element's assigned access key.
... htmlelement.iscontenteditable read only re
turns a boolean that indicates whether or not the content of the element can be edited.
... htmlorforeignelement.dataset read only re
turns a domstringmap with which script can read and write the element's custom data attributes (data-*) .
...And 19 more matches
SVGPathElement - Web APIs
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.
... svgpathelement.getpointatlength() re
turns an svgpoint representing the x and y coordinates in user space utilizing the browser's distance-along-a-path algorithm.
... svgpathelement.getpathsegatlength() re
turns an unsigned long representing the index within the pathseglist utilizing the user agent's distance-along-a-path algorithm.
...And 19 more matches
Using Service Workers - Web APIs
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.
... 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.
... 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.
...And 19 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 19 more matches
BigInt64Array - JavaScript
static properties bigint64array.bytes_per_element re
turns a number value of the element size.
... bigint64array.name re
turns the string value of the constructor name.
... instance properties bigint64array.prototype.buffer re
turns the arraybuffer referenced by the bigint64array.
...And 19 more matches
BigUint64Array - JavaScript
static properties biguint64array.bytes_per_element re
turns a number value of the element size.
... biguint64array.name re
turns the string value of the constructor name.
... instance properties biguint64array.prototype.buffer re
turns the arraybuffer referenced by the biguint64array.
...And 19 more matches
Float32Array - JavaScript
static properties float32array.bytes_per_element re
turns a number value of the element size.
... float32array.name re
turns the string value of the constructor name.
... instance properties float32array.prototype.buffer re
turns the arraybuffer referenced by the float32array fixed at construction time and thus read only.
...And 19 more matches
Float64Array - JavaScript
static properties float64array.bytes_per_element re
turns a number value of the element size.
... float64array.name re
turns the string value of the constructor name.
... instance properties float64array.prototype.buffer re
turns the arraybuffer referenced by the float64array fixed at construction time and thus read only.
...And 19 more matches
Int16Array - JavaScript
static properties int16array.bytes_per_element re
turns a number value of the element size.
... int16array.name re
turns the string value of the constructor name.
... instance properties int16array.prototype.buffer re
turns the arraybuffer referenced by the int16array fixed at construction time and thus read only.
...And 19 more matches
Int32Array - JavaScript
static properties int32array.bytes_per_element re
turns a number value of the element size.
... int32array.name re
turns the string value of the constructor name.
... instance properties int32array.prototype.buffer re
turns the arraybuffer referenced by the int32array fixed at construction time and thus read only.
...And 19 more matches
Int8Array - JavaScript
static properties int8array.bytes_per_element re
turns a number value of the element size.
... int8array.name re
turns the string value of the constructor name.
... instance properties int8array.prototype.buffer re
turns the arraybuffer referenced by the int8array fixed at construction time and thus read only.
...And 19 more matches
Object - JavaScript
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.
...And 19 more matches
TypedArray - JavaScript
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").
... instance properties typedarray.prototype.buffer re
turns the arraybuffer referenced by the typed array.
...And 19 more matches
Uint16Array - JavaScript
static properties uint16array.bytes_per_element re
turns a number value of the element size.
... uint16array.name re
turns the string value of the constructor name.
... instance properties uint16array.prototype.buffer re
turns the arraybuffer referenced by the uint16array fixed at construction time and thus read only.
...And 19 more matches
Uint32Array - JavaScript
static properties uint32array.bytes_per_element re
turns a number value of the element size.
... uint32array.name re
turns the string value of the constructor name.
... instance properties uint32array.prototype.buffer re
turns the arraybuffer referenced by the uint32array fixed at construction time and thus read only.
...And 19 more matches
Uint8Array - JavaScript
static properties uint8array.bytes_per_element re
turns a number value of the element size.
... uint8array.name re
turns the string value of the constructor name.
... instance properties uint8array.prototype.buffer re
turns the arraybuffer referenced by the uint8array fixed at construction time and thus read only.
...And 19 more matches
Uint8ClampedArray - JavaScript
static properties uint8clampedarray.bytes_per_element re
turns a number value of the element size.
... uint8clampedarray.name re
turns the string value of the constructor name.
... instance properties uint8clampedarray.prototype.buffer re
turns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus read only.
...And 19 more matches
tabs/utils - Archive of obsolete content
re
turns tabbrowser : gettabcontainer(window) get the tabbrowser's tabcontainer property.
... 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.
...And 18 more matches
LiveConnect Overview - Archive of obsolete content
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.
...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.
...place the forname assignment statement in a try block to handle the exception, as follows: function getclass(javaclassname) { try { var theclass = java.lang.class.forname(javaclassname); } catch (e) { re
turn ("the java exception is " + e); } re
turn theclass; } in this example, if javaclassname evaluates to a legal class name, such as "java.lang.string", the assignment succeeds.
...And 18 more matches
inIDOMUtils
value state 1 :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.
... 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.
...And 18 more matches
nsIDOMMozNetworkStatsManager
to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method re
turns an array of interfaces.
... re
turn value an nsidomdomrequest object.
... invalidnetwork the network must be in the re
turn of getavailablenetworks.
...And 18 more matches
nsIDOMWindowInternal
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.
...And 18 more matches
nsIWindowsRegKey
ng(); void writebinaryvalue(in astring name, in acstring data); void writeint64value(in astring name, in unsigned long long data); void writeintvalue(in astring name, in unsigned long data); void writestringvalue(in astring name, in astring data); attributes attribute type description childcount unsigned long this attribute re
turns the number of child keys.
... valuecount unsigned long this attribute re
turns the number of values under this key.
...it is still possible to enumerate values that have other types (that is, getvaluetype() may re
turn a type not defined below).
...And 18 more matches
eval() - JavaScript
re
turn value the completion value of evaluating the given code.
... if the completion value is empty, undefined is re
turned.
... if the argument of eval() is not a string, eval() re
turns the argument unchanged.
...And 18 more matches
Understanding WebAssembly text format - WebAssembly
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).
... 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.
...And 18 more matches
Client-side form validation - Learn web development
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.
...And 17 more matches
Fetching data from the server - Learn web development
this isn't strictly necessary here — xhr re
turns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future.
... add this next: request.responsetype = 'text'; fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is re
turned from the network) before you can do anything with that response, otherwise, an error will be thrown.
... xhr allows you to handle this using its onload event handler — this is run when the load event fires (when the response has re
turned).
...And 17 more matches
NSS PKCS11 Functions
re
turns the function re
turns one of these values: if successful, a pointer to a secmodmodule.
...re
turns the function re
turns one of these values: if successful, secsuccess.
...re
turns the function re
turns one of these values: if successful, secsuccess).
...And 17 more matches
Using Objective-C from js-ctypes
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).
...the objc_getclass function receives the name of the class, looks up the definition, and re
turns it.
...sel_registername receives the name of the selector, and re
turns the selector.
...And 17 more matches
A first splash into JavaScript - Learn web development
see if you can guess it in 10
turns or fewer.
...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.
...And 16 more matches
Client-Server Overview - Learn web development
when an html page is re
turned it is rendered by the web browser.
... at the end of the message we see the body content — which contains the actual html re
turned by the request.
... static sites a static site is one that re
turns the same hard coded content from the server whenever a particular resource is requested.
...And 16 more matches
Sqlite.jsm
openconnection(options) re
turns a promise that resolves to an opened connection instance or is rejected if an error occurred while opening the database.
... this function re
turns a promise that will be resolved when the database has closed.
... await conn.close(); throw e; } clone(readonly) this function re
turns a clone of the current connection-promise.
...And 16 more matches
JS::CompileOptions
methods some methods of js::owningcompileoptions and js::compileoptions re
turn the instance itself to allow method chain.
... 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.
...And 16 more matches
nsIAccessibleText
defaulttextattributes nsipersistentproperties re
turn the text attributes that apply to the entire accessible.
...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.
...And 16 more matches
nsILoginManagerStorage
countlogins() implement this method to re
turn the number of logins matching the specified criteria.
...passing null should not match any logins, and should re
turn 0.
... re
turn value the number of logins that match the specified criteria.
...And 16 more matches
nsIPromptService
acheckstate contains the initial checked state of the checkbox when this method is called and the final checked state after this method re
turns.
... re
turn value true for ok, false for cancel see also the confirm_example.
... acheckstate contains the initial checked state of the checkbox when this method is called and the final checked state after this method re
turns.
...And 16 more matches
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.flipx() re
turns a new dommatrix created by flipping the source matrix around its x-axis.
... dommatrixreadonly.flipy() re
turns a new dommatrix created by flipping the source matrix around its y-axis.
... dommatrixreadonly.inverse() re
turns a new dommatrix created by inverting the source matrix.
...And 16 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
it re
turns an interval id which uniquely identifies the interval, so you can remove it later by calling clearinterval().
...the function is not passed any arguments, and no re
turn value is expected.
... 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.
...And 16 more matches
Numbers and dates - JavaScript
properties of number property 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 maxi...
...mum safe integer in javascript (+253 − 1, or +9007199254740991) methods of number method description number.parsefloat() parses a string argument and re
turns a floating point number.
... number.parseint() parses a string argument and re
turns an integer of the specified radix or base.
...And 16 more matches
Array.prototype.reduce() - JavaScript
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.
... 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).
...And 16 more matches
places/bookmarks - Archive of obsolete content
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.
... 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.
...And 15 more matches
Handling common accessibility problems - Learn web development
previous overview: cross browser testing next 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.
... as a test, you can
turn off a site's css and see how understandable it is without it.
... 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).
...And 15 more matches
Task.jsm
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 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.
...And 15 more matches
XPCOMUtils.jsm
if not // provided, the default factory is used, which re
turns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
... // will be automatically re
turned from queryinterface if that was // generated with the generateqi helper.
...neratensgetfactory(componentsarray); function generateci(classinfo); function generateqi(interfaces); void importrelative(that, path, scope); generator itersimpleenumerator(enumerator, interface); generator iterstringenumerator(enumerator); attributes attribute type description categorymanager nsicategorymanager re
turns a reference to nsicategorymanager.
...And 15 more matches
How to embed the JavaScript engine
*/ 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(cx, js_newglobalobject(cx, &global_class, nullptr)); if (!global) re
turn 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *filename = "noname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, rval.address()); if (!ok) re
turn 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); ...
...} js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); re
turn 0; } spidermonkey 31 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object.
...And 15 more matches
IAccessibleValue
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.
...[propget] hresult currentvalue( [out] variant currentvalue ); parameters currentvalue re
turns the current value represented by this object.
...And 15 more matches
nsILocalFile
getrelativedescriptor() re
turns a relative file path in an opaque, cross platform format.
... re
turn value an opaque string value with undefined character encoding.
... the result re
turned from this method may be used with setrelativedescriptor() to initialize a nsilocalfile instance.
...And 15 more matches
Getting Started Guide
a rule of xpcom is that any function that creates or re
turns an interface pointer will have already addrefed it.
... it
turns out that reference counting by hand is hard for programmers to get right.
...you still have to know which functions re
turn interface pointers that have already been addrefed and which don't.
...And 15 more matches
Using IndexedDB - Web APIs
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 method re
turns a transaction object containing the idbindex.objectstore method, which you can use to access your object store.
...And 15 more matches
Key Values - Web APIs
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.
... whitespace keys keyboardevent.key value description virtual keycode windows mac linux android "enter" the enter or ↵ key (sometimes labeled re
turn).
... vk_re
turn (0x0d) kvk_re
turn (0x24) kvk_ansi_keypadenter (0x4c) kvk_powerbook_keypadenter (0x34) gdk_key_re
turn (0xff0d) gdk_key_kp_enter (0xff8d) gdk_key_iso_enter (0xfe34) gdk_key_3270_enter (0xfd1e) qt::key_re
turn (0x01000004) qt::key_enter (0x01000005) keycode_enter (66) keycode_numpad_enter (160) keycode_dpad_center (23) "tab" the horizontal tab key, tab.
...And 15 more matches
KeyboardEvent - Web APIs
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 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").
...And 15 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
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 fragment shader re
turns the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects.
...it gets called as the handler for the promise re
turned by issessionsupported().
...And 15 more matches
Starting up and shutting down a WebXR session - Web APIs
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.
... 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.
...getxr(usepolyfill) { let tempxr; let temppoly; switch(usepolyfill) { case "if-needed": if (!navigator.xr) { webxrpolyfill = new webxrpolyfill(); } tempxr = navigator.xr; break; case "yes": webxrpolyfill = new webxrpolyfill(); tempxr = navigator.xr; break; case "no": default: tempxr = navigator.xr; break; } re
turn tempxr; } const xr = getxr("no"); // get the native xrsystem object const xr = getxr("yes"); // always re
turns an xrsystem from the polyfill const xr = getxr("if-needed"); // use the polyfill only if navigator.xr missing the re
turned xrsystem object can then be used according to the documentation provided here on mdn.
...And 15 more matches
Using the Web Speech API - Web APIs
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.
... speechrecognition.interimresults: defines whether the speech recognition system should re
turn interim results, or just final results.
... speechrecognition.maxalternatives: sets the number of alternative potential matches that should be re
turned per result.
...And 15 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.
...And 15 more matches
util/array - Archive of obsolete content
globals functions has(array, element) re
turns true if the given array contains the element or false otherwise.
... 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.
...And 14 more matches
Mozilla DOM Hacking Guide
similarly, then re
turn type of the c++ function will be wrapped by xpconnect so that javascript can use it safely.
...the re
turn value of getdocument() is a nsidomdocument.
... 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.
...And 14 more matches
imgIContainer
in the case of any error, zero is re
turned, and an exception will be thrown.
...in the case of any error, zero is re
turned, and an exception will be thrown.
... flag_sync_decode: forces synchronous/non-progressive decode of all available data before the call re
turns.
...And 14 more matches
nsIDocShell
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).
... isexecutingonloadhandler boolean re
turns true if the docshell is currently executing the onload handler.
...when setting this attribute, a ns_error_not_implemented error may be re
turned by implementations not supporting zoom.
...And 14 more matches
nsIEditorSpellCheck
re
turn value re
turns true if spell checking can be enabled.
... if there are no available dictionaries, the re
turn value is false.
...in spite of the name, this function checks the word you give it, re
turning true if the word is misspelled.
...And 14 more matches
nsIMsgDBView
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.
... re
turn values acount upon re
turn, the count variable may contain the number of messages loaded.
...And 14 more matches
nsISelectionPrivate
endplaceholdertransaction will give rise to reflow/refreshing view/scroll, and call times of nstextframe::getpointfromoffset whose re
turn value is to be cached.
... interlineposition boolean type short re
turns the type of the selection (see nsiselectioncontroller for available constants).
... native code only!getcachedframeoffset re
turns cached value for nstextframe::getpointfromoffset.
...And 14 more matches
UInt64
syntax creates and re
turns a new 64-bit unsigned integer.
... re
turn value a new object representing the specified value.
... re
turn value the re
turned value is -1 if a < b, 0 if a == b, and 1 if a > b.
...And 14 more matches
Range - Web APIs
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.
...And 14 more matches
TreeWalker - Web APIs
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.
... treewalker.filter read only re
turns a nodefilter used to select the relevant nodes.
...And 14 more matches
Inputs and input sources - Web APIs
the re
turned xrpose's transform is the transform corresponding to the target ray.
... 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.
...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.
...And 14 more matches
Background audio processing using AudioWorklet - Web APIs
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().
...so each input is, in
turn, an array of channels.
...utputlist[inputnum]; let channelcount = math.min(input.length, output.length); for (let channelnum = 0; channelnum < channelcount; channelnum++) { let samplecount = input[channelnum].length; for (let i = 0; i < samplecount; i++) { let sample = input[channelnum][i]; /* manipulate the sample */ output[channelnum][i] = sample; } } }; re
turn true; } note that when determining the number of sources to process and send through to the corresponding outputs, we use math.min() to ensure that we only process as many channels as we have room for in the output list.
...And 14 more matches
WorkerNavigator - Web APIs
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.
...And 14 more matches
platform/xpcom - Archive of obsolete content
var { class } = require('sdk/core/heritage'); var { unknown, factory } = require('sdk/platform/xpcom'); var { cc, ci } = require('chrome'); var contractid = '@me.org/helloworld'; // define a component var helloworld = class({ extends: unknown, get wrappedjsobject() this, hello: function() {re
turn 'hello world';} }); // create and register the factory var factory = factory({ contract: contractid, component: helloworld }); // xpcom clients can retrieve and use this new // component in the normal way var wrapper = cc[contractid].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); using class id you can specify a class id for the ...
...here's the example above, rewritten to use class id instead of contract id for lookup: var { class } = require('sdk/core/heritage'); var { unknown, factory } = require('sdk/platform/xpcom'); var { cc, ci, components } = require('chrome'); // define a component var helloworld = class({ extends: unknown, get wrappedjsobject() this, hello: function() {re
turn 'hello world';} }); // create and register the factory var factory = factory({ component: helloworld }); var id = factory.id; // retrieve the factory by class id var wrapper = components.classesbyid[id].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); replacing factories if the factory you create has the same contract id as an exist...
...this will typically re
turn a descendant of unknown, although it may re
turn a custom object that satisfies the nsisupports interface.
...And 13 more matches
Making decisions in your code — conditionals - Learn web development
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.
... this code is pretty human-readable — it is saying "if the condition re
turns true, run code a, else run code b" you should note that you don't have to include the else and the second curly brace block — the following is also perfectly legal code: if (condition) { code to run if condition is true } run some other code however, you need to be careful here — in this case, the second block of code is not controlled by the conditional statement, so it always runs, regardless of whether the condition re
turns true or false.
...And 13 more matches
JS::CallArgs
(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.
... 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.
...And 13 more matches
nsIMsgHeaderParser
moveduplicateaddresses(in string addrs, in string other_addrs, in prbool removealiasestome, out string newaddress); string unquotephraseoraddr(in string line, in boolean preserveintegrity); wstring unquotephraseoraddrwstring(in wstring line, in 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.
... 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.
...And 13 more matches
nsIURI
to create an nsiuri object, you should use nsiioservice.newuri(), like this: function makeuri(aurl, aorigincharset, abaseuri) { var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); re
turn ioservice.newuri(aurl, aorigincharset, abaseuri); } components of a uri prepath path scheme userpass host port ref ftp :// username@password @ hostname : portnumber /pathname?query=value #ref method overview nsiuri clone(); nsiuri cloneignoringref(); boolean equals(in n...
... hasref boolean re
turns if there is a reference portion (the part after the "#") of the uri.
...about:blank) prepath autf8string the prepath re
turns the string before the path (such as "scheme://user:password@host:port").
...And 13 more matches
Reference Manual
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.
...the pointer re
turned cannot be addrefed, released, or deleted.
...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).
...And 13 more matches
Add to iPhoto
this.cfstringcreatewithcharacters = this.lib.declare("cfstringcreatewithcharacters", ctypes.default_abi, this.cfstringref, // re
turns a new cfstringref 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 in...
...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.
... 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.
...And 13 more matches
SubtleCrypto.wrapKey() - Web APIs
re
turn value result is a promise that fulfills with an arraybuffer containing the encrypted exported key.
...*/ 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.
...And 13 more matches
Iteration protocols - JavaScript
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.
... this function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is re
turned.
...And 13 more matches
menulist - Archive of obsolete content
editable type: boolean re
turns true if the element is editable.
... autocomplete fields are editable so this property always re
turns true for those.
... selectedindex type: integer re
turns the index of the currently selected item.
...And 12 more matches
Index - Learn web development
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.
...it won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't
turn out right, especially in the earlier stages of your learning journey.
... 89 javascript building blocks article, assessment, beginner, codingscripting, conditionals, functions, guide, introduction, javascript, landing, loops, module, events, l10n:priority in this module, we continue our coverage of all javascript's key fundamental features,
turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.
...And 12 more matches
Third-party APIs - Learn web development
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.
... 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.
...And 12 more matches
Componentizing our React app - Learn web development
in this code, we define the function and export it on the same line: export default function todo() { re
turn ( ); } this is ok so far, but our component has to re
turn something!
... go back to src/app.js, copy the first <li> from inside the unordered list, and paste it into todo.js so that it reads like this: export default function todo() { re
turn ( <li classname="todo stack-small"> <div classname="c-cb"> <input id="todo-0" type="checkbox" defaultchecked={true} /> <label classname="todo-label" htmlfor="todo-0"> eat </label> </div> <div classname="btn-group"> <button type="button" classname="btn"> edit <span classname="visually-hidden">eat</span> </button> <button type="button" classname="btn btn__danger"> delete <span classname="visually-hidden">eat</span> </button> </div> </li> ); } note: components must always re
turn something.
... if at any point in the future you try to render a component that does not re
turn anything, react will display an error in your browser.
...And 12 more matches
Handling common JavaScript problems - Learn web development
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.
... in the search packages text field, type "jslint" and press enter/re
turn to search for linting-related packages.
...And 12 more matches
Gecko info for Windows accessibility vendors
if there is no msaa node for a dom node, or vice-versa, queryservice() will re
turn null.
...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.
...the results are always re
turned via vt_dispatch.
...And 12 more matches
How to implement a custom autocomplete search component
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.
...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.
...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 12 more matches
JNI.jsm
re
turn value blah blah loadclass() blah blah cdata loadclass( ajenv, afullyqualifiedname, [optional] object adeclares ); parameters ajenv the re
turn value of getforthread().
... re
turn value blah blah newstring() blah blah cdata newstring( ajenv, astr ); parameters ajenv the re
turn value of getforthread().
... re
turn value blah blah readstring() blah blah string readstring( ajenv, ajavastring ); parameters ajenv the re
turn value of getforthread().
...And 12 more matches
XPCOM array guide
// re
turn it to the caller *aresult = array; ns_addref(*aresult); } javascript example function getlist() { var array = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); // append some elements ...
... // re
turn it to the caller re
turn array; } access to elements since nsiarray is a regular xpcom object, its interfaces follows the standard conventions of ownership.
...the method enumerate() re
turns a nsisimpleenumerator which accesses all the elements in the array.
...And 12 more matches
Using XPCOM Utilities to Make Things Easier
// 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.
...must be called in class's constructor ns_get_iid re
turns the iid given the name of an interface.
... // 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.
...And 12 more matches
IAccessibleHyperlink
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.
...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.
... re
turn value e_invalidarg if bad [in] passed, [out] value is null.
...And 12 more matches
nsIIOService
lags,in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsiuri newfileuri(in nsifile afile); nsiuri newuri(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description offline boolean re
turns true if networking is in "offline" mode.
... re
turn value true if the port is allowed, false otherwise.
... re
turn value a string corresponding to the scheme.
...And 12 more matches
nsIMsgDBHdr
inherits from: nsisupports this interface is usually given to you in re
turn to a query from the message database.
... there are utility functions that also re
turn it though.
... for instance, msghdrforcurrentmessage() will re
turn the currently selected message's header.
...And 12 more matches
nsIMsgIncomingServer
inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void clearallvalues(); void cleartemporaryre
turnreceiptsfilter(); void closecachedconnections(); void configuretemporaryfilters(in nsimsgfilterlist filterlist); void configuretemporaryre
turnreceiptsfilter(in nsimsgfilterlist filterlist); obsolete since gecko 1.8 void displayofflinemsg(in nsimsgwindow awindow); boolean equals(in nsimsgincomingserver server); void forgetpassword(); void forgetsessionpassword(); astring generateprettynameformigration(); boolean getboolattribute(in string name); boolean getboolvalue(in str...
... 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.
...And 12 more matches
nsITextInputProcessor
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.
...("foo-".length, tip.attr_converted_clause); tip.appendclausetopendingcomposition("bar".length, tip.attr_selected_clause); tip.appendclausetopendingcomposition("-buzz".length, tip.attr_converted_clause); // then, sets the caret if you need tip.setcaretinpendingcomposition("foo-bar".length); // finally, flush the pending composition on the focused editor if (!tip.flushpendingcomposition()) { re
turn; // composition is not started } if there is no composition, flushpendingcomposition() starts composition with dispatching compositionstart event automatically.
... however, if the event is consumed by web content, it re
turns false.
...And 12 more matches
nsIZipReader
findentries() re
turns a string enumerator containing the matching entry names.
... pat~pat2 re
turns matches to the pattern 'pat' which do not also match the pattern 'pat2'.
... re
turn value the nsiutf8stringenumerator containing the matching entry names.
...And 12 more matches
Streams - Plugins
once the plug-in re
turns from this method, the browser deletes the npstream object.
... 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.
...And 12 more matches
Attr - Web APIs
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.
... as that doesn't hold true in cases like attr objects being re
turned by document.evaluate, the dom living standard reintroduced the property.
... specified read only this property always re
turns true.
...And 12 more matches
Cache - Web APIs
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.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.
...And 12 more matches
DOMMatrix - Web APIs
constructor dommatrix() creates and re
turns a new dommatrix object.
...if the matrix can't be inverted, its components are all set to nan, and is2d re
turns false.
...re
turns itself.
...And 12 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
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).
... * * @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.
...And 12 more matches
Using Web Workers - Web APIs
thus, using the window shortcut to get the current global scope (instead of self) within a worker will re
turn an error.
... 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.
...And 12 more matches
Window.open() - Web APIs
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.
...And 12 more matches
Arrow function expressions - JavaScript
syntax basic syntax (param1, param2, …, paramn) => { statements } (param1, 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.
... () => { statements } advanced syntax // parenthesize the body of a function to re
turn an object literal expression: params => ({foo: bar}) // rest parameters and default parameters are supported (param1, param2, ...rest) => { statements } (param1 = defaultvalue1, param2, …, paramn = defaultvaluen) => { statements } // destructuring within the parameter list is also supported 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.
... shorter functions var elements = [ 'hydrogen', 'helium', 'lithium', 'beryllium' ]; // this statement re
turns the array: [8, 6, 7, 9] elements.map(function(element) { re
turn element.length; }); // the regular function above can be written as the arrow function below elements.map((element) => { re
turn element.length; }); // [8, 6, 7, 9] // when there is only one parameter, we can remove the surrounding parentheses elements.map(element => { re
turn element.length; }); // [8, 6, 7, 9] // when the only statement in an arrow function is `re
turn`, we can remove `re
turn` and remove // the surrounding curly brackets elements.map(element => element.length)...
...And 12 more matches
Date.parse() - JavaScript
the date.parse() method parses a string representation of a date, and re
turns the number of milliseconds since january 1, 1970, 00:00:00 utc or nan if the string is unrecognized or, in some cases, contains illegal date values (e.g.
...(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.
...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.
... 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.
...And 11 more matches
Reading from Files - Archive of obsolete content
this method will open the file and re
turn a stream.
...the readstring method re
turns the string read from the stream.
...this doesn't trigger an error, and the string will just be re
turned containing as many characters as are available.
...And 11 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
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.
...://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="re
turn myfunction(event);"/> </window> oninput type: script code this event is sent when a user enters text in a textbox.
...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.
...And 11 more matches
Basic math in JavaScript — numbers and operators - Learn web development
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.
...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.
... 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.
...And 11 more matches
Promise
a reference to an existing promise may be received by different means, for example as the re
turn value of a call into an asynchronous api.
...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.
... 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.
...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.
...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.
...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.
...And 11 more matches
NSS API Guidelines
when something goes wrong, the call stack unwinds, with routines re
turning an error indication.
...likewise, the external references to errors are made in the prototypes files, with the functions which can re
turn them.
...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.
...And 11 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; } ...
... } 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 truelen = 0; int digit1, digit2; outbuf->data = ishexdata ?
... port_alloc(outlen) : port_alloc(len); if (!outbuf->data) { re
turn -1; } if (ishexdata) { while (*instring) { if ((*instring == '\n') || (*instring == ':')) { instring++; continue; } digit1 = getdigit(*instring++); digit2 = getdigit(*instring++); if ((digit1 == -1) || (digit2 == -1)) { port_free(outbuf->data); outbuf->data = null; re
turn -1; } outbuf->data[truelen++] = digit1 << 4 | digit2; } } else { while (*instring) { if (*instring == '\n') { instring++; continue; } outbuf->data[truelen++] = *ins...
...And 11 more matches
pkfnc.html
re
turns the function re
turns one of these values: if successful, a pointer to a certificate structure.
...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.
...And 11 more matches
sslcrt.html
re
turns the function re
turns one of these values: if successful, secsuccess.
... 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.
... 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.
...And 11 more matches
Mozilla internal string guide
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.
...(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.
...And 11 more matches
NS_ConvertUTF16toUTF8
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
NS_LossyConvertUTF16toASCII
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsAdoptingCString
nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple operator const char* char* operator const char*() const - source operator[] char operator[](print32) const - source parameters print32 i char operator[](pruint32) const - source parameters pruint32 i get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsCAutoString
source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells u...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string ...
...And 11 more matches
nsCString
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsDependentCString
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsFixedCString
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsPromiseFlatCString
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsXPIDLCString
ng_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - 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 caseles...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount rfindchar print32 rfindchar(prunichar, print32, print32) const - source parameters prunichar achar print32 aoffset print32 acount findcharinset print32 findcharinset(const char*, print32) const - source this method searches this string for the first character found in the given string.
...And 11 more matches
nsIEffectiveTLDService
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.
... method overview acstring getbasedomain(in nsiuri auri, [optional] in pruint32 aadditionalparts); acstring getbasedomainfromhost(in autf8string ahost, [optional] in pruint32 aadditionalparts); acstring getpublicsuffix(in nsiuri auri); acstring getpublicsuffixfromhost(in autf8string ahost); methods getbasedomain() re
turns the base domain of a uri; that is, the public suffix with a given number of additional domain name parts.
... aadditionalparts the number of domain name parts to be re
turned in addition to the public suffix.
...And 11 more matches
nsIFaviconService
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.
... re
turn value a data url containing the data for the favicon.
...And 11 more matches
nsIMessenger
boolean canundo(); re
turn value boolean representing whether undo is available.
... boolean canredo(); re
turn value boolean representing whether redo is available.
... unsigned long getundotransactiontype(); re
turn value a long representing the type of the transaction.
...And 11 more matches
nsIScriptableIO
re
turn value re
turns an nsifile object referencing the specified file location.
... getfilewithpath() re
turns a file reference using an absolute file path to locate the file.
... re
turn value re
turns an nsifile object referencing the specified file location.
...And 11 more matches
nsIXPCScriptable
for example, callers must guarantee that they set the *_retval of the various methods that re
turn a boolean to pr_true before making the call.
... implementations may skip writing to *_retval unless they want to re
turn pr_false.
...no implementor of this interface should ever re
turn flags with this bit set.
...And 11 more matches
nsIMsgCloudFileProvider
if this value is not known, re
turns -1.
...if this value is not known, re
turns -1.
...if this value is not known, re
turns -1.
...And 11 more matches
Int64
syntax creates and re
turns a new 64-bit signed integer.
... re
turn value a new object representing the specified value.
... re
turn value the re
turned value is: -1 if a < b, 0 if a == b, and 1 if a > b.
...And 11 more matches
Element.classList - Web APIs
the element.classlist is a read-only property that re
turns a live domtokenlist collection of the class attributes of the element.
... syntax const elementclasses = elementnodereference.classlist; re
turns a domtokenlist representing the contents of the element's class attribute.
... if the class attribute is not set or empty, it re
turns an empty domtokenlist, i.e.
...And 11 more matches
IDBObjectStore - Web APIs
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.
... idbobjectstore.clear() creates and immediately re
turns an idbrequest object, and clears this object store in a separate thread.
... 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.
...And 11 more matches
USBDevice - Web APIs
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.
...And 11 more matches
WebGL2RenderingContext - Web APIs
state information webgl2renderingcontext.getindexedparameter() re
turns the indexed value for the given target.
... renderbuffers webgl2renderingcontext.getinternalformatparameter() re
turns information about implementation-dependent support for internal formats.
... programs and shaders webgl2renderingcontext.getfragdatalocation() re
turns the binding of color numbers to user-defined varying out variables.
...And 11 more matches
HTTP Index - HTTP
when this happens, the user needs to
turn cors back on in their browser.
... 74 content-location http, reference, header the content-location header indicates an alternate location for the re
turned data.
...when this policy is enabled, the promise re
turned by mediadevices.getusermedia() will reject with a notallowederror.
...And 11 more matches
Closures - JavaScript
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.
... 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.
...And 11 more matches
Details of the object model - JavaScript
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.
...if it does, that value is re
turned.
...And 11 more matches
Iterators and generators - JavaScript
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.
...if value is present alongside done, it is the iterator's re
turn value.
...And 11 more matches
Functions - JavaScript
values can be passed to a function, and the function will re
turn a value.
... 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.
...And 11 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.
... see also the find() method, which re
turns the value of an array element, instead of its index.
...And 11 more matches
Array.prototype.map() - JavaScript
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.
... re
turn value a new array with each element being the result of the callback function.
...And 11 more matches
Array.prototype.sort() - JavaScript
the sort() method sorts the elements of an array in place and re
turns the sorted array.
... re
turn value the sorted array.
... if comparefunction is supplied, all non-undefined array elements are sorted according to the re
turn value of the compare function (all undefined elements are sorted to the end of the array, with no call to comparefunction).
...And 11 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 match or matches are replaced with newsubstr or the value re
turned by the specified function.
... re
turn value a new string, with some or all matches of a pattern replaced by a replacement.
...And 11 more matches
Symbol - JavaScript
the symbol() function re
turns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class, but is incomplete as a constructor because it does not support the syntax "new symbol()".
... every symbol value re
turned from symbol() is unique.
... 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.
...And 11 more matches
url - Archive of obsolete content
an exception is raised if the url can't be converted; otherwise, the native file path is re
turned as a string.
... re
turns string : the converted native file path as a string.
... re
turns string : the converted url as a string.
...And 10 more matches
Using microformats - Archive of obsolete content
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.
... re
turn value a string that describes the contents of the specified microformat object.
...And 10 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... 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).
... 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.
...And 10 more matches
Introducing asynchronous JavaScript - Learn web development
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.
...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.
...when you fetch an image from a server, you can't re
turn the result immediately.
...And 10 more matches
Extending a Protocol
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: navigator.echo("hi!"); that will re
turn a pending promise that never settles.
...And 10 more matches
Following the Android Toasts Tutorial from a JNI Perspective
re as follows: java type signature boolean z byte b char c class/object lclass name in slash notation here; double d float f int i long j short s void v array of type [sig here method format (sig of type of each argument here)sig of the re
turn type here declaring a class/object is done in a special way.
...the arguments are within the parenthesis, and the re
turn type is immediately following.
...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.
...And 10 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; } ...
... } 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; int digit1, digit2; outbuf->data = ishexdata ?
... port_alloc(outlen) : port_alloc(len); if (!outbuf->data) { re
turn -1; } if (ishexdata) { while (*instring) { if ((*instring == '\n') || (*instring == ':')) { instring++; continue; } digit1 = getdigit(*instring++); digit2 = getdigit(*instring++); if ((digit1 == -1) || (digit2 == -1)) { port_free(outbuf->data); outbuf->data = null; re
turn -1; } outbuf->data[truelen++] = digit1 << 4 | digit2; } } else { while (*instring) { if (*instring == '\n') { instring++; continue; } outbuf->data[truelen++] = *ins...
...And 10 more matches
Python binding for NSS
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.
... error codes are never re
turned from methods/functions.
...most people will probablby just print the string representation of the re
turned certverifylog object.
...And 10 more matches
Introduction to the JavaScript shell
build() re
turns the date and time at which the javascript shell was built.
... 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.
...And 10 more matches
Places Developer Guide
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 getfol...
...deridforitem(aitemid) - re
turns the id of the folder containing the given item.
... string getitemguid(aitemid) obsolete since gecko 14.0 - re
turns a globally unique identifier for the item.
...And 10 more matches
Avoiding leaks in JavaScript XPCOM components
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).
... 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.
...And 10 more matches
Introduction to XPCOM for the DOM
the memory is never re
turned because we keep the object around even if we don't need it.
... a getter is a function defined in global scope or in class scope that will "re
turn" a pointer to the required interface.
... please note that all getter functions have to addref the re
turned pointer.
...And 10 more matches
IAccessibleHypertext
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.
...And 10 more matches
mozIStorageStatement
ned long aparamindex, [array,const,size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); mozistoragependingstatement executeasync(mozistoragestatementcallback acallback); boolean executestep(); boolean step(); void execute(); attributes attribute type description columncount unsigned long number of columns re
turned.
... mozistoragestatement clone(); re
turn value a mozistoragestatement that is a copy of the current statement.
... re
turn value an autf8string representing the parameter name for the specified index.
...And 10 more matches
nsIDOMNSHTMLDocument
void releaseevents(in long eventflags); void routeevent(in nsidomevent evt); void write(); obsolete since gecko 2.0 void writeln(); obsolete since gecko 2.0 attributes attribute type description alinkcolor domstring same as body.alink bgcolor domstring same as body.bgcolor compatmode domstring re
turns "backcompat" if the document is in quirks mode or "css1compat" if the document is in full standards or almost standards mode.
... 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.
... re
turn value true if the command was recognized, false otherwise.
...And 10 more matches
nsIHttpChannel
setter is case insensitive; getter re
turns an uppercase string.
... requestsucceeded boolean re
turns true if the http response code indicates success.
... note: this re
turns the raw (possibly 8-bit) text from the server.
...And 10 more matches
nsIInputStream
if a stream is at end-of-file, but not closed, then this method re
turns 0 bytes available.
... re
turn value number of bytes currently available in the stream, or pr_uint32_max if the size of the stream exceeds pr_uint32_max.
...this method causes subsequent calls to read() and readsegments() to re
turn 0 bytes read to indicate end-of-file.
...And 10 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.
... 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 getfilesize() read only.
...And 10 more matches
Component; nsIPrefBranch
re
turn value the value of the requested boolean preference.
... re
turn value re
turns string - the value of the requested string preference.
... re
turn value re
turns utf8tring - the value of the requested string preference.
...And 10 more matches
AudioWorkletProcessor.process - Web APIs
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.
... 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 10 more matches
Using the CSS Painting API - Web APIs
if set to false, all colours used on the canvas will be fully opaque */ static get contextoptions() { re
turn { alpha: true }; } /* ctx is the 2d drawing context a subset of the html5 canvas api.
... */ paint(ctx) { ctx.fillstyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillrect(0, 15, 200, 20); /* order: x, y, w, h */ } }); in this class example we have defined a single context option with the contextoptions() function: we re
turned a simple object stating alpha transparency is allowed.
... the code to do this looks like so: registerpaint('headerhighlight', class { static get contextoptions() { re
turn { alpha: true }; } /* ctx is the 2d drawing context size is the paintsize, the dimensions (height and width) of the box being painted */ paint(ctx, size) { ctx.fillstyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillrect( 0, size.height / 3, size.width * 0.4, size.height * 0.6 ); } }); this code example has two differences from our first example: we've i...
...And 10 more matches
Selection - Web APIs
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.
...And 10 more matches
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
the webglrenderingcontext.getrenderbufferparameter() method of the webgl api re
turns information about the renderbuffer.
...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.
...And 10 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 10 more matches
Meta programming - JavaScript
for example, getting a property on an object: let handler = { get: function(target, name) { re
turn name in target?
...here, an object that is proxied will not re
turn undefined when getting undefined properties, but will instead re
turn the number 42.
... handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof getprototypeof method must re
turn an object or null.
...And 10 more matches
Text formatting - JavaScript
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.
...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.
...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.
...And 10 more matches
Using Promises - JavaScript
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.
... here's some code that uses createaudiofileasync(): function successcallback(result) { console.log("audio file ready at url: " + result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions re
turn a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to re
turn a promise, using it could be as simple as this: createaudiofileasync(audiosettings).then(successcallback, failurecallback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function c...
...And 10 more matches
Atomics - JavaScript
re
turns the old value at that index.
...re
turns the old value at that index.
...re
turns the old value.
...And 10 more matches
JSON.parse() - JavaScript
an optional reviver function can be provided to perform a transformation on the resulting object before it is re
turned.
... 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.
...And 10 more matches
Map - JavaScript
description a map object iterates its elements in insertion order — a for...of loop re
turns an array of [key, value] for each iteration.
...thus, when iterating over it, a map object re
turns keys in order of insertion.
... instance properties map.prototype.size re
turns the number of key/value pairs in the map object.
...And 10 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.
... re
turn value an already resolved promise if the iterable passed is empty.
...And 10 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.
... re
turn value an already resolved promise if the iterable passed is empty.
...And 10 more matches
Proxy - JavaScript
y1 = new proxy(target, handler1); because the handler is empty, this proxy behaves just like the original target: console.log(proxy1.message1); // hello console.log(proxy1.message2); // everyone to customise the proxy, we define functions on the handler object: const target = { message1: "hello", message2: "everyone" }; const handler2 = { get: function(target, prop, receiver) { re
turn "world"; } }; const proxy2 = new proxy(target, handler2); here we've provided an implementation of the get() handler, which intercepts attempts to access properties in the target.
...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.
... 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.
...And 10 more matches
delete operator - JavaScript
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.
...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.
...And 10 more matches
core/heritage - Archive of obsolete content
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.
...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.
...And 9 more matches
Promises - Archive of obsolete content
nse.messages) { try { yield publish({ username: user, messages: response.messages }); } catch (e) { self.reporterror("publication failed", e); } } }); can be converted to a pure promise-based equivalent as such: request("login", { username: user, password: password }) .then(response => { if (response.messages) re
turn publish({ username: user, messages: response.messages }); }) .then(null, (e) => { self.reporterror("publication failed", e); }); file io file io in add-ons should be done via the os.file api, which provides a simple, but powerful, interface for reading, writing, and manipulating both text and binary files.
... 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.
... addonmanager var aom = { __proto__: addonmanager, addon: function addon(addon) { if (!(addon && "getdatadirectory" in addon)) re
turn addon; re
turn { __proto__: addon, getdatadirectory: function getdatadirectory() { re
turn new promise((accept, reject) => { re
turn addon.getdatadirectory((directory, error) => { if (error) reject(error); else accept(directory)...
...And 9 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.
... 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.
...And 9 more matches
prefwindow - Archive of obsolete content
re
turning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527).
...if the handler re
turns true, the dialog will indeed go away, but if it re
turns false it will not.
...if the routine re
turns true, the dialog will indeed go away, but if it re
turns false it will not.
...And 9 more matches
tabs - Archive of obsolete content
selectedindex type: integer re
turns the index of the currently selected item.
...re
turns -1 if no items are selected selecteditem type: element holds the currently selected item.
... tabbox type: tabbox element re
turns the tabbox element that contains the tabs.
...And 9 more matches
Mobile accessibility - Learn web development
to
turn it on, look up what phone model and android version you have, and then look up where the talkback menu is.
... when you've found the talkback menu, press the slider switch to
turn talkback on.
... when talkback is
turned on, your android device's basic controls will be a bit different.
...And 9 more matches
Client-side storage - Learn web development
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.
...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.
... 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.
...And 9 more matches
Getting started with React - Learn web development
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.
...because react
turns the jsx we write into react.createelement(), all react components must import the react module.
... 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.
...And 9 more matches
Mozilla accessibility architecture
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.
...if there is no msaa node for a dom node, paccessible->queryinterface(iid_iaccessible) will re
turn null.
...the first request for an accessible is usually the accessible for document in one of the open windows, and the code in widget/src/gtk2 or widget/src/windows must re
turn this doc accessible.
...And 9 more matches
OS.File for the main thread
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.
...it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typically because the computer is
turned off, the battery runs out, or the application is stopped.) let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp"}); // buffer "file.txt.tm...
... re
turn promise.resolve(true); // loop end.
...And 9 more matches
JSAutoByteString
char *encodelatin1(jscontext *cx, jsstring *str) call js_encodestring and take ownership of the re
turned string, and re
turn the string.
... char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take ownership of the re
turned string, and re
turn the string.
... char *ptr() const re
turn a pointer to the owned string.
...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", ...
... &previous); if (previous) nsmemory::free(previous); rv = catman->addcategoryentry("content-policy", "weblock", weblock_contractid, pr_true, pr_true, &previous); if (previous) nsmemory::free(previous); re
turn rv; } this code adds a new category entry under the topic "content-policy," and it calls addcategoryentry in the same way we did in registering for notifications.
...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.
...And 9 more matches
NS_ConvertASCIItoUTF16
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
NS_ConvertUTF8toUTF16
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsAdoptingString
nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple operator const prunichar* prunichar* operator const prunichar*() const - source operator[] prunichar operator[](print32) const - source parameters print32 i prunichar operator[](pruint32) const - source parameters pruint32 i get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsAutoString
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsDependentString
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsFixedString
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsPromiseFlatString
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsString
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
nsXPIDLString
tor=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source re
turns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount print32 find(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acoun...
...@re
turn offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 rfind(const char*, prbool, print32, print32) const - source parameters char* acstring prbool aignorecase print32 aoffset print32 acount print32 rfind(const nsaflatstring&, print32, print32) const - source parameters nsaflatstring& astring print32 aoffset print32 aco...
...And 9 more matches
IAccessibleRelation
[out] bstr localizedrelationtype ); [propget] hresult ntargets([out] long ntargets ); [propget] hresult relationtype([out] bstr relationtype ); [propget] hresult 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.
...And 9 more matches
mozIStorageConnection
transactioninprogress boolean re
turns true if there is a transaction in progress on the database.
... otherwise re
turns false.
... mozistorageconnection clone( in boolean areadonly optional ); parameters areadonly if true, the re
turned database connection is in read only mode.
...And 9 more matches
nsIAccessible
groupposition this method re
turns grouping information.
... 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.
...And 9 more matches
nsIAccessibleHyperLink
the re
turned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink.
... selected boolean determines whether the element currently has the focus, for example after re
turning from the destination page.
...the re
turned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink.
...And 9 more matches
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.
...re
turn value true if an image is selected, false otherwise.
... cancopyimagelocation() re
turns whether we can copy an image location.
...And 9 more matches
nsILoginManager
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.
... re
turn value the number of logins matching the parameters passed.
... re
turn value true if the form was successfully filled out; otherwise false.
...And 9 more matches
nsIMicrosummaryService
re
turn value re
turns an nsimicrosummary for the given page and generator uris.
...re
turn value re
turns an nsisimpleenumerator enumeration of bookmark ids.
... getgenerator() re
turn a microsummary generator for the given uri.
...And 9 more matches
nsINavHistoryService
re
turn value re
turns the original title of the page.
... re
turn value re
turns true if this uri would be added to the history, otherwise re
turns false.
... re
turn value re
turns the id of the created visit.
...And 9 more matches
nsITransactionList
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 9 more matches
nsITransactionListener
aresult the nsresult re
turned after beginning a batch.
...adoresult the nsresult re
turned after executing the transaction.
...aresult the nsresult re
turned after ending a batch.
...And 9 more matches
nsITransactionManager
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.
... endbatch()
turns off the transaction manager's batch mode.
...getredolist() re
turns the list of nsitransaction on the redo stack.
...And 9 more matches
nsIXULTemplateQueryProcessor
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.
... re
turn value -1 if aleft < aright 0 if aleft == aright 1 if aleft > aright compilequery() compile a query from a node.
...if null is re
turned, the query will be ignored.
...And 9 more matches
nsIAbCard/Thunderbird3
methods getproperty() re
turns a property for the given name.
... defaultvalue the value to re
turn if the property does not exist.
... re
turn value the value of the attribute asked for.
...And 9 more matches
XPIDL
methods define a re
turn type and a series of in and out parameters.
...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.
...if a method is declared notxpcom, the mangling of the re
turn type is prevented, so it is called mostly as it looks.
...And 9 more matches
Address Book examples
this function will re
turn the first match that it finds in the collection or null.
...again, this function re
turns the first match that it finds in the collection, or null.
...card = components.classes["@mozilla.org/addressbook/cardproperty;1"] .createinstance(components.interfaces.nsiabcard); card.setproperty("firstname", "john"); card.setproperty("lastname", "smith"); card.primaryemail = "john@invalid.com"; now add the card to an address book via its nsiabdirectory interface: let newcard = addressbook.addcard(card); the addcard function re
turns a new nsiabcard object that may have had nsiabdirectory specific data added to it, e.g.
...And 9 more matches
Debugger.Frame - Firefox Developer Tools
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.
... 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.
...each property is a read-only accessor property whose getter re
turns the current value of the corresponding parameter.
...And 9 more matches
Debugger.Script - Firefox Developer Tools
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.
... 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.
...And 9 more matches
HTMLFormElement - Web APIs
a form with an input named action will have its action property re
turn that input instead of the form's action html attribute).
... 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.
... reportvalidity() re
turns true if the element's child controls satisfy their validation constraints.
...And 9 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.
... modifier keys on gecko when getmodifierstate() re
turns true on gecko?
...And 9 more matches
MediaDevices.getUserMedia() - Web APIs
it re
turns a promise that resolves to a mediastream object.
... 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.
...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.
...And 9 more matches
MediaStreamTrack - Web APIs
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.
... 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.
...And 9 more matches
Resource Timing API - Web APIs
high-resolution timestamps several of the resource timing properties re
turn high-resolution timestamps.
...the first property in the processing model is starttime which re
turns the timestamp immediately before the resource loading process begins.
... when cors is in effect, many of these values are re
turned as zero unless the server's access policy permits these values to be shared.
...And 9 more matches
SVGTextContentElement - Web APIs
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.
...And 9 more matches
SubtleCrypto.unwrapKey() - Web APIs
it decrypts the key and then imports it, re
turning a cryptokey object that can be used in the web crypto api.
... 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.
...*/ function bytestoarraybuffer(bytes) { const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); re
turn bytesasarraybuffer; } /* get some key material to use as input to the derivekey method.
...And 9 more matches
SubtleCrypto - Web APIs
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 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.
... 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.
... var encoder = new textencoder; function encodeintoatposition(string, u8array, position) { re
turn encoder.encodeinto(string, position ?
...And 9 more matches
TextRange - Web APIs
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.
...And 9 more matches
Touch - Web APIs
basic properties touch.identifier read only re
turns a unique identifier for this touch object.
... 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.
...And 9 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.
...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.
...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
Array.prototype.every() - JavaScript
it re
turns a boolean value.
... re
turn value true if the callback function re
turns a truthy value for every array element.
... 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.
...And 9 more matches
Array.prototype.find() - JavaScript
the find() method re
turns the value of the first element in the provided array that satisfies the provided testing function.
... re
turn value the value of the first element in the array that satisfies the provided testing function.
... otherwise, undefined is re
turned.
...And 9 more matches
Array.prototype.indexOf() - JavaScript
the indexof() method re
turns the first index at which a given element can be found in the array, or -1 if it is not present.
...if the index is greater than or equal to the array's length, -1 is re
turned, which means the array will not be searched.
... re
turn value the first index of the element in the array; -1 if not found.
...And 9 more matches
JSON.stringify() - JavaScript
re
turn value a json string representing the given value.
...json.stringify() can re
turn undefined when passing in "pure" values like json.stringify(function(){}) or json.stringify(undefined).
... the instances of date implement the tojson() function by re
turning a string (the same as date.toisostring()).
...And 9 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.
... re
turn value the object that was passed to the function.
...the re
turn value will be used as the value of the property.
...And 9 more matches
Set - JavaScript
instance properties set.prototype.size re
turns the number of values in the set object.
...re
turns 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.
...And 9 more matches
String.prototype.charCodeAt() - JavaScript
the charcodeat() method re
turns an integer between 0 and 65535 representing the utf-16 code unit at the given index.
...if the unicode code point cannot be represented in 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.
... re
turn value a number representing the utf-16 code unit value of the character at the given index.
...And 9 more matches
yield - JavaScript
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.
... 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.
...And 9 more matches
context-menu - Archive of obsolete content
predicatecontext(predicatefunction) predicatefunction is called when the menu is invoked, and the context occurs when the function re
turns a true value.
...if you register a listener function for this event and it re
turns true, the menu item associated with the listener's content script is shown in the menu.
... for example, this item appears whenever the context menu is invoked on a page that contains at least one image: require("sdk/context-menu").item({ label: "this page has images", contentscript: 'self.on("context", function (node) {' + ' re
turn !!document.queryselector("img");' + '});' }); note that the listener function has a parameter called node.
...And 8 more matches
radiogroup - Archive of obsolete content
selectedindex type: integer re
turns the index of the currently selected item.
...re
turns -1 if no items are selected selecteditem type: element holds the currently selected item.
...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.
...And 8 more matches
textbox - Archive of obsolete content
for number boxes, the default is 0 or the minimum value re
turned by the min property, whichever is higher.
...otherwise it re
turns the value of the associated label element, if applicable.
... otherwise it re
turns the placeholder or emptytext property.
...And 8 more matches
JavaScript basics - Learn web development
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..
...And 8 more matches
Useful string methods - Learn web development
try entering the following lines: let browsertype = 'mozilla'; browsertype.length; this should re
turn the number 7, because "mozilla" is 7 characters long.
... 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!
...And 8 more matches
Introduction to the server side - Learn web development
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).
... 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).
...And 8 more matches
Package management basics - Learn web development
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.
...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.
...And 8 more matches
HTML parser threading
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.
...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).
...And 8 more matches
WebRequest.jsm
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 tells the browser to wait for your event listener to re
turn before continuing with the request.
... next, re
turn an object from the listener that contains instructions for what the browser should do with this request.
...And 8 more matches
AsyncTestUtils extended framework
sometimes in your tests you need to wait for an operation to complete that does not occur synchronously (that is, it is not done when the function call you made to initiate the operation re
turns control to you).
...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.
...re
turning false tells the asynchronous driver that it should yield control up to the top-level.
...And 8 more matches
NSS Sample Code Sample1
s = pk11_setprivatekeynickname(prvkey, mservername); if (s != secsuccess) { rv = 1; goto done; } done: if (slot) pk11_freeslot(slot); if (pubkey) seckey_destroypublickey(pubkey); if (prvkey) seckey_destroyprivatekey(prvkey); re
turn rv; } int server::generatekeys() { int rv = 0; seckeypublickey *pubkey = 0; pk11slotinfo *slot = 0; // choose a slot to use slot = pk11_getinternalkeyslot(); if (!slot) { rv = 1; goto done; } // get our own public key to use for wrapping rv = getpublickey(&pubkey); if (rv) goto done; // do the encryption (aes) key if (!mwrappedenckey) { pk11symkey *key = 0; //...
... 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 8 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 8 more matches
NS ConvertASCIItoUTF16 external
prunichar* aptr nsastring& operator=(prunichar) - source parameters prunichar achar adopt void adopt(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
NS ConvertUTF16toUTF8 external
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
NS ConvertUTF8toUTF16 external
prunichar* aptr nsastring& operator=(prunichar) - source parameters prunichar achar adopt void adopt(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
NS LossyConvertUTF16toASCII external
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
PromiseFlatCString (External)
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
PromiseFlatString (External)
prunichar* aptr nsastring& operator=(prunichar) - source parameters prunichar achar adopt void adopt(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsACString (External)
methods beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsAString (External)
methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsAutoString (External)
prunichar* aptr nsastring& operator=(prunichar) - source parameters prunichar achar adopt void adopt(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsCAutoString (External)
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsCStringContainer (External)
methods beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring astr print32* c find(const nsacstring&, pruint32, print32 (*) print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsCString external
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsDependentCString external
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsDependentCSubstring external
onst nsacstring&, pruint32, pruint32) - source parameters nsacstring& astr pruint32 astartpos pruint32 alength rebind void rebind(const char*, pruint32) - source parameters char* astart pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsDependentString external
prunichar* aptr nsastring& operator=(prunichar) - source parameters prunichar achar adopt void adopt(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsDependentSubstring external
pruint32, pruint32) - source parameters nsastring astr pruint32 astartpos pruint32 alength rebind void rebind(const prunichar*, pruint32) - source parameters prunichar astart pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring astr print32* c find(const nsastring&, pruint32, print32 (*) print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsLiteralCString (External)
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsLiteralString (External)
source parameters char* aptr nsacstring& operator=(char) - source parameters char achar adopt void adopt(const char*, pruint32) - source parameters char* adata pruint32 alength beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsacstring& astr print32 (*)(char*, char*, pruint32) c print32 find(const nsacstring&, pruint32, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsStringContainer (External)
methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsString external
prunichar* aptr nsastring& operator=(prunichar) - source parameters prunichar achar adopt void adopt(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation.
...@re
turn the new length of the string, or 0 if resizing failed.
... @re
turn the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string, beginning at aoffset.
...And 8 more matches
nsIDOMElement
domstring getattribute( in domstring name ); parameters name attribute name re
turn value a domstring containing the attribute value.
...nsidomattr getattributenode( in domstring name ); parameters name attribute name re
turn value a nsidomattr corresponding to the attribute.
...nsidomattr getattributenodens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname attribute name re
turn value a nsidomattr corresponding to the attribute.
...And 8 more matches
nsIOutputStream
this exception may only be thrown if isnonblocking() re
turns true.
...this exception may only be thrown if isnonblocking() re
turns true.
... re
turn value true if stream is non-blocking.
...And 8 more matches
nsIPlacesView
methods getdragableselection() re
turns an array of selected nsinavhistoryresultnode objects that can be dragged from the view.
... 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.
...And 8 more matches
nsIPrincipal
if there isn't one, this will re
turn null.
... hashvalue unsigned long re
turns a hash value for the principal.
... 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.
...And 8 more matches
nsITransferable
flavorstransferablecanexport() re
turns a list of flavors (mime types as nsisupportscstring) that the transferable can export, either through intrinsic knowledge or output data converters.
... 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.
... 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 8 more matches
nsIURL
if a file extension does not exist, the empty string is re
turned.
...if there isn't one, an empty string is re
turned.
...if there isn't one, an empty string is re
turned.
...And 8 more matches
Working with data
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.
... 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 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.
...And 8 more matches
CacheStorage - Web APIs
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.
...And 8 more matches
DocumentOrShadowRoot - Web APIs
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.
...And 8 more matches
File - Web APIs
file objects are generally retrieved 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.
...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).
...And 8 more matches
SVGMatrix - Web APIs
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.
...And 8 more matches
ServiceWorkerRegistration - Web APIs
serviceworkerregistration.scope read only re
turns a unique identifier for a service worker registration.
... serviceworkerregistration.installing read only re
turns a service worker whose state is installing.
... serviceworkerregistration.waiting read only re
turns a service worker whose state is installed.
...And 8 more matches
Using readable streams - Web APIs
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)); let’s look in detail at how read() is used.
... in the pump() function seen above we first invoke read(), which re
turns a promise containing a results object — this has the results of our read in it, in the form { done, value }: re
turn reader.read().then(({ done, value }) => { the results can be one of three different types: if a chunk is available to read, the promise will be fulfilled with an object of the form { value: thechunk, done: false }.
...And 8 more matches
VTTCue - Web APIs
constructor vttcue(starttime, endtime, text) re
turns a newly created vttcue object that covers the given time range and has the given text.
... vttcue.vertical re
turns an enum representing the cue writing direction.
... vttcue.snaptolines re
turns true if the vttcue.line attribute is an integer number of lines or a percentage of the video size.
...And 8 more matches
WebGL2RenderingContext.getSamplerParameter() - Web APIs
the webgl2renderingcontext.getsamplerparameter() method of the webgl 2 api re
turns parameter information of 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.
...And 8 more matches
WebGLRenderingContext.getProgramParameter() - Web APIs
the webglrenderingcontext.getprogramparameter() method of the webgl api re
turns information about the given program.
...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.
...And 8 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.
... the re
turned style is a live cssstyledeclaration object, which updates automatically when the element's styles are changed.
...ns-serif; text-align: center; background: purple; color: white; } 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.
...And 8 more matches
WorkerGlobalScope - Web APIs
the self property re
turns the specialized scope for each context.
... standard properties workerglobalscope.navigator read only re
turns the workernavigator associated with the worker.
... workerglobalscope.self read only re
turns a reference to the workerglobalscope itself.
...And 8 more matches
WritableStream.WritableStream() - Web APIs
if this process is to be done asynchronously, it can re
turn a promise to signal success or failure.
...it can re
turn a promise to signal success or failure of the write operation.
...if this process is asynchronous, it can re
turn a promise to signal success or failure.
...And 8 more matches
XMLHttpRequest - Web APIs
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.
...And 8 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
will re
turn object of type role_window.
...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.
...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.
...And 8 more matches
Intl.Locale - JavaScript
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.
...And 8 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.
...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.
...And 8 more matches
String.prototype.match() - JavaScript
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.
...And 8 more matches
String.prototype.split() - JavaScript
the split() method divides a string into an ordered list of substrings, puts these substrings into an array, and re
turns the array.
... if separator is omitted or does not occur in str, the re
turned array contains one element consisting of the entire string.
...zero length) string, which appears at the first (or last) position of the re
turned array.
...And 8 more matches
parseInt() - JavaScript
the parseint() function parses a string argument and re
turns an integer of the specified radix (the base in mathematical numeral systems).
... re
turn value an integer parsed from the given string.
... description the parseint function converts its first argument to a string, parses that string, then re
turns an integer or nan.
...And 8 more matches
Strict mode - JavaScript
function strict() { // function-level strict mode syntax 'use strict'; function nested() { re
turn 'and so am i!'; } re
turn "hi!
... " + 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.
...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...
...And 8 more matches
Navigation and resource timings - Web Performance
if no such connection is requested, it re
turns 0.
...if there is no redirect, or if one of the redirects is not of the same origin, the value re
turned is 0.
...if there is no redirect, or if one of the redirects is not of the same origin, the value re
turned is 0.
...And 8 more matches
XPCOM Objects - Archive of obsolete content
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.
...And 7 more matches
Commands - Archive of obsolete content
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.
... iscommandenabled (command) this method should re
turn true if the command is enabled, or false if it is disabled.
...And 7 more matches
menu - Archive of obsolete content
control type: menu element re
turns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu.
... parentcontainer type: menu element read only property that re
turns the containing menu element, or null if there isn't a containing menu.
... 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.
...And 7 more matches
NPN_GetValue - Archive of obsolete content
values for npnvariable: npnvxdisplay =1: unix only: re
turns the current display npnvxtappcontext: unix only: re
turns the application's xtappcontext npnvnetscapewindow: ms windows and unix/x11 only: ms windows: gets the native window on which plug-in drawing occurs; re
turns hwnd unix/x11: gets the browser toplevel window in which the plug-in is displayed; re
turns window npnvjavascriptenabledbool: tells whether javascript i...
...s enabled; true=javascript enabled, false=not enabled npnvasdenabledbool: tells whether smartupdate (former name: asd) is enabled; true=smartupdate enabled, false=not enabled npnvisofflinebool: tells whether offline mode is enabled; true=offline mode enabled, false=not enabled npnvtoolkit: npnvsupportsxembedbool: npnvwindownpobject: re
turns the npobject * pointer for the dom window object; see getting the page url in npapi plugin for a rough example npnvpluginelementnpobject: npnvsupportswindowless: tells whether the browser supports windowless plugins.
... the value parameter should point to a npbool, which will be set appropriately if the function re
turns nperr_no_error.
...And 7 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
if (document.all) { // internet explorer 4+ document.write('<link rel="stylesheet" type="text/css" src="style-ie.css">'); } else if (document.layers) { // navigator 4 document.write('<link rel="stylesheet" type="text/css" src="style-nn.css">'); } note how the above example only provided stylesheets for internet explorer and navigator 4 and even then only if the visitor has javascript support
turned on in their browser.
... </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.
...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.
...And 7 more matches
XForms Custom Controls - Archive of obsolete content
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.
... */ string getcurrentvalue(); } notes: getcurrentvalue() should re
turn the current value of the control as seen by a user.
...currently interface is: interface nsixformsaccessors : nsisupports { /** * re
turn value of instance node.
...And 7 more matches
Arrays - Learn web development
we'll re
turn to this example later on in the article.
... 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!
...And 7 more matches
Routing in Ember - Learn web development
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.
...And 7 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
we'll use array.prototype.map() instead of array.prototype.filter() because we want to re
turn a new array with some changes, instead of deleting something from the array.
... add the edittask() function inside your app component, in the same place as the other functions: function edittask(id, newname) { const editedtasklist = tasks.map(task => { // if this task has the same id as the edited task if (id === task.id) { // re
turn {...task, name: newname} } re
turn task; }); settasks(editedtasklist); } pass edittask into our <todo /> components as a prop in the same way we did with deletetask: const tasklist = tasks.map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggletaskcompleted={toggletaskcompleted} deletetask={deletetask} edittask={edittask} /> )); now open todo.js.
... copy this block of code into the todo() function, beneath your usestate() hook but above the re
turn statement: const editingtemplate = ( <form classname="stack-small"> <div classname="form-group"> <label classname="todo-label" htmlfor={props.id}> new name for {props.name} </label> <input id={props.id} classname="todo-text" type="text" /> </div> <div classname="btn-group"> <button type="button" classname="btn todo-cancel"> cancel <sp...
...And 7 more matches
Introduction to automated testing - Learn web development
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.
...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.
... 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.
...And 7 more matches
nss tech note5
ck_mechanism_type ciphermech = ckm_des_cbc_pad <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(ciphermech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* alwys re
turns internal slot, may not be optimal */ prepare the key if using a raw key /*
turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key bytes */ keyitem.len = /* length of the array of key bytes */ /*
turn the secitem into a key object */ pk11symkey* symkey = pk11_importsymkey(slot, ciphermech, ...
... ck_mechanism_type digestmech = ckm_md5 <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(digestmech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* always re
turns int slot, may not be optimal */ prepare the key if using a raw key /*
turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key bytes */ keyitem.len = /* length of the array of key bytes */ /*
turn the secitem into a key object */ pk11symkey* symkey = pk11_importsymkey(slot, digestmech, pk11_...
... can find a list of hmac mechanisms in security/nss/lib/softoken/pkcs11.c - grep for ckf_sn_vr, and choose the mechanisms that contain hmac in the name ck_mechanism_type hmacmech = ckm_md5_hmac; <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(hmacmech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* always re
turns int slot, may not be optimal */ prepare the key if using a raw key /*
turn the raw key into a secitem */ secitem keyitem; keyitem.type = sibuffer; keyitem.data = /* ptr to an array of key bytes */ keyitem.len = /* length of the array of key bytes */ /*
turn the secitem into a key object */ pk11symkey* symkey = pk11_imp...
...And 7 more matches
PKCS #11 Module Specs
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).
... librarydescription override the default librarydescription value for the module re
turned in the ck_info structure with an internationalize string (utf8).
... cryptotokendescription override the default label value for the internal crypto token re
turned in the ck_token_info structure with an internationalize string (utf8).
...And 7 more matches
JIT Optimization Strategies
in particular, arguments cannot be re
turned from the function, or passed as an argument into calls (except for the apply case above).
...in particular, arguments cannot be re
turned from the function, or passed as an argument into calls (except for the apply example listed above).
...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.
...And 7 more matches
JS::AutoVectorRooter
syntax js::autovectorrooter(jscontext* cx); methods method description size_t length() const re
turns the length of the array.
... t popcopy() pops an element from the array and re
turns it.
... js::mutablehandle<t> operator[](size_t i) re
turns to the i-th element as js::mutablehandle<t>.
...And 7 more matches
JSFastNative
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.
...(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.
...And 7 more matches
IAccessibleComponent
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.
...And 7 more matches
mozIStorageValueArray
methods gettypeofindex() re
turns the type of the value at the given column index.
... 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.
... re
turn value the int32 for the specified entry.
...And 7 more matches
mozIThirdPartyUtil
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.
...if so, re
turn.
...And 7 more matches
nsIBinaryInputStream
re
turn value an 8-bit integer read from the stream.
... re
turn value a 16-bit integer read from the stream.
... re
turn value a 32-bit integer read from the stream.
...And 7 more matches
nsIComponentRegistrar
cidtocontractid() this method re
turns the contractid corresponding to a given classid.
... 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.
...And 7 more matches
nsIContentViewer
can re
turn null.
...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.
...And 7 more matches
nsIControllers
exceptions thrown ns_error_out_of_memory getcontrollerat() re
turns the controller instance at the given position.
... re
turn value the controller at the given position.
... getcontrollerbyid() re
turns a controller given by its order, rather than position, of insertion.
...And 7 more matches
nsIINIParser
nsiutf8stringenumerator getkeys(in autf8string asection); nsiutf8stringenumerator 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.
... 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.
...And 7 more matches
nsIJSON
deprecated since gecko 2.0 methods decode() obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) decodes a json string, re
turning the javascript object it represents.
... re
turn value the original javascript object, reconstructed from the json string.
... re
turn value the original javascript object, reconstructed from the json string.
...And 7 more matches
nsIMsgMessageService
amsgwindow nsimsgwindow for progress and status feedback re
turn values aurl the new nsiuri of the message.
... aurllistener an nsiurllistener amsgwindow nsimsgwindow for progress and status feedback re
turn values aurl the new nsiuri of the message.
... re
turn values aurl the new nsiuri of the message.
...And 7 more matches
nsISelection
n domstring alter, in domstring direction, in domstring granularity); void removeallranges(); void removerange(in nsidomrange range); void selectallchildren(in nsidomnode parentnode); void selectionlanguagechange(in boolean langrtl); domstring tostring(); attributes attribute type description anchornode nsidomnode re
turns the node in which the selection begins.
... focusnode nsidomnode re
turns the node in which the selection ends.
... rangecount long re
turns the number of ranges in the selection.
...And 7 more matches
Declaring and Using Callbacks
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.
...And 7 more matches
CData
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.
... 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.
...And 7 more matches
The JavaScript input interpreter - Firefox Developer Tools
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).
... when you find the expression you want, press enter (re
turn) to execute the statement.
...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 7 more matches
BluetoothCharacteristicProperties - Web APIs
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.
...And 7 more matches
CSSCounterStyleRule - Web APIs
if the descriptor was not specified in the associated rule, the attribute re
turns an empty string.
...if the descriptor was not specified in the associated rule, the attribute re
turns an empty string.
...if the descriptor was not specified in the associated rule, the attribute re
turns an empty string.
...And 7 more matches
FetchEvent.respondWith() - Web APIs
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".
... 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".
...And 7 more matches
Using Fetch - Web APIs
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.
...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).
...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
In depth: Microtasks and the JavaScript runtime environment - Web APIs
ent.getelementbyid("output"); let userlanguages = { "mike": "en", "teresa": "es" }; function greetuser(user) { function localgreeting(user) { let greeting; let language = userlanguages[user]; switch(language) { case "es": greeting = `¡hola, ${user}!`; break; case "en": default: greeting = `hello, ${user}!`; break; } re
turn greeting; } outputelem.innerhtml += localgreeting(user) + "<br>\r"; } greetuser("mike"); greetuser("teresa"); greetuser("veronica"); this short program contains three execution contexts, some of which are created and destroyed several times over the course of the program's execution.
...when this function re
turns, the context for localgreeting() is removed from the execution stack and destroyed.
... the greetuser() function re
turns and its context is removed from the stack and destroyed.
...And 7 more matches
IDBObjectStoreSync - Web APIs
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.
... createindex() creates and re
turns a new index with the given name in the connected database.
... re
turns idbindexsync an object to access the newly created index.
...And 7 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.
... 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..
...And 7 more matches
PerformanceEntry.duration - Web APIs
the duration property re
turns a timestamp that is the duration of the performance entry.
... 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).
...And 7 more matches
Using the Resource Timing API - Web APIs
function calculate_load_times() { // check performance 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...
...the transfersize property re
turns the size (in octets) of the fetched resource including the response header fields plus the response payload body.
... the encodedbodysize property re
turns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings.
...And 7 more matches
SVGSVGElement - Web APIs
svgsvgelement.unsuspendredraw() cancels a specified suspendredraw() by providing a unique suspend handle id that was re
turned by a previous suspendredraw() call.
... 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.
...And 7 more matches
Using the Screen Capture API - Web APIs
capturing screen contents capturing screen contents as a live mediastream is initiated by calling navigator.mediadevices.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.
... 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.
...And 7 more matches
SubtleCrypto.importKey() - Web APIs
re
turn value result is a promise that fulfills with the imported key as a cryptokey object.
...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.
...And 7 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.
...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 point is not very useful, but there are other types of matrices that can perform helpful operations on points.
...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...
...And 7 more matches
Signaling and video calling - Web APIs
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.
...that would be weird."); re
turn; } targetusername = clickedusername; createpeerconnection(); navigator.mediadevices.getusermedia(mediaconstraints) .then(function(localstream) { document.getelementbyid("local_video").srcobject = localstream; localstream.gettracks().foreach(track => mypeerconnection.addtrack(track, localstream)); }) .catch(handlegetusermediaerror); } } this begins with...
...when this succeeds, fulfilling the re
turned promise, our then handler is executed.
...And 7 more matches
Web Authentication API - Web APIs
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.
...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.
...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.
...And 7 more matches
Index - HTTP
26 content-location http, reference, header the content-location header indicates an alternate location for the re
turned data.
...when this policy is enabled and there were no user gestures, the promise re
turned by htmlmediaelement.play() will reject with a domexception.
...when this policy is enabled, the promise re
turned by mediadevices.getusermedia() will reject with a notallowederror.
...And 7 more matches
Control flow and error handling - JavaScript
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.
...And 7 more matches
Array.prototype.filter() - JavaScript
re
turn true to keep the element, false otherwise.
... 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.
...And 7 more matches
Array.prototype.some() - JavaScript
it re
turns a boolean value.
... re
turn value true if the callback function re
turns a truthy value for at least one element in the array.
... 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).
...And 7 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.
... re
turn value the number of leading zero bits in the 32-bit binary representation of the given number.
... if the converted 32-bit unsigned integer is 0, then re
turn 32, because all bits are 0.
...And 7 more matches
Number - JavaScript
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.
...re
turned on overflow.
...And 7 more matches
Reflect - JavaScript
re
turns a boolean that is true if the property was successfully defined.
... reflect.get(target, propertykey[, receiver]) re
turns the value of the property.
...re
turns a property descriptor of the given property if it exists on the object, undefined otherwise.
...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.
... so, for example: 'undefined'.indexof() will re
turn 0, as undefined is found at position 0 in the string undefined.
...And 7 more matches
String.prototype.substring() - JavaScript
the substring() method re
turns the part of the string between the start and end indexes, or to the end of the string.
... 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.
...And 7 more matches
in operator - JavaScript
the in operator re
turns true if the specified property is in the specified object or its prototype chain.
... // arrays let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'] 0 in trees // re
turns true 3 in trees // re
turns true 6 in trees // re
turns false 'bay' in trees // re
turns false (you must specify the index number, not the value at that index) 'length' in trees // re
turns true (length is an array property) symbol.iterator in trees // re
turns true (arrays are iterable, works only in es2015+) // predefined objects 'pi' in math // re
turns true // custom ob...
...jects let mycar = {make: 'honda', model: 'accord', year: 1998} 'make' in mycar // re
turns true 'model' in mycar // re
turns true you must specify an object on the right side of the in operator.
...And 7 more matches
function* - JavaScript
the function* declaration (function keyword followed by an asterisk) defines a generator function, which re
turns a generator object.
... 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.
...And 7 more matches
Canvas code snippets - Archive of obsolete content
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.
... function getpixelamount(canvas, r, g, b) { var 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.
... function getpixelcolour(canvas, x, y) { var cx = canvas.getcontext('2d'); var pixel = cx.getimagedata(x, y, 1, 1); re
turn { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2], a: pixel.data[3] }; } chaining methods this class provides jquery-style chained access to 2d context methods and properties.
...And 6 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
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.
... if (array.isarray(elemnameorarray)) { var frag = doc.createdocumentfragment(); array.foreach(arguments, function(thiselem) { frag.appendchild(tag.apply(null, thiselem)); }); re
turn frag; } // single element?
...tag.apply(null, childelem) : doc.createtextnode(childelem)); } }); re
turn elem; } re
turn tag.apply(null, jsontemplate); } in the above, the namespaces object defines the namespace prefixes which can be used in the given dom tree.
...And 6 more matches
XBL Example - Archive of obsolete content
<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 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.
...And 6 more matches
wizard - Archive of obsolete content
currentpage type: wizardpage element this property re
turns the wizardpage element that is currently displayed.
... pageindex type: integer this property re
turns the index of the currently selected page.
... 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.
...And 6 more matches
NPClass - Archive of obsolete content
allocate re
turns a pointer to a newly allocated npobject.
...this function is expected to allocate and re
turn enough storage to hold the npobject that is being created.
...re
turns true if the method exists, otherwise re
turns false.
...And 6 more matches
Working with JSON - Learn web development
this allows you to construct a data hierarchy, like so: { "squadname": "super hero squad", "hometown": "metro city", "formed": 2016, "secretbase": "super tower", "active": true, "members": [ { "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" ] }, { "name": "eternal flame", "age": 1000000, "secretidentity": "unknown", "powers": [ "immortali...
...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.
... 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.
...And 6 more matches
React interactivity: Events and state - Learn web development
it re
turns two things: the state, and a function that can be used to update the state later.
... usestate() re
turns these two things, so we are using array destructuring to capture them both in separate variables.
... // 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.
...And 6 more matches
TypeScript support in Svelte - Learn web development
just run npm run validate to check for unused css, and re
turn a11y hints and typescript compile errors.
...the partial utility re
turns a new type based on the type t, where every property of t is optional.
... like this: // actions.ts export function selectonfocus(node: htmlinputelement) { if (node && typeof node.select === 'function' ) { // make sure node is defined and has a select() method const onfocus = () => node.select() // event handler node.addeventlistener('focus', onfocus) // when node gets focus call onfocus() re
turn { destroy: () => node.removeeventlistener('focus', onfocus) // this will be executed when the node is removed from the dom } } } now update todo.svelte and newtodo.svelte where we import the actions file.
...And 6 more matches
AsyncShutdown.jsm
// 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.
...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().
...And 6 more matches
NetUtil.jsm
void asyncfetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attribute type description ioservice nsiioservice re
turns a reference to nsiioservice.
... re
turn value re
turns the nsiasyncstreamcopier object that is handling the copy.
... if (!components.issuccesscode(aresult)) { // handle error re
turn; } // consume the input stream.
...And 6 more matches
NSS_3.12_release_notes.html
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.
...ts in der_asciitotime bug 422866: vfychain -pp command crashes in nss_shutdown bug 345779: useless assignment statements in ec_gf2m_pt_mul_mont bug 349011: please stop exporting these crmf_ symbols bug 397178: crash when entering chrome://pippki/content/resetpassword.xul in url bar bug 403822: pkix_pl_ocsprequest_create can leave some members uninitialized bug 403910: cert_findusercertbyusage() re
turns wrong certificate if multiple certs with same subject available bug 404919: memory leak in sftkdb_readsecmoddb() (sftkmod.c) bug 406120: allow application to specify ocsp timeout bug 361025: support for camellia cipher suites to tls rfc4132 bug 376417: pk11_generatekeypair needs to get the key usage from the caller.
...bug 401610: shared db fails on iopr tests bug 388120: build error due to sec_begin_protos / sec_end_protos are undefined bug 415264: make security use of new nspr rotate macros bug 317052: lib/base/whatnspr.c is obsolete bug 317323: set nspr31_lib_prefix to empty explicitly for win95 and wince builds bug 320336: secitem_allocitem re
turns a non-null pointer if the allocation of its 'data' buffer fails bug 327529: can't pass 0 as an unnamed null pointer argument to cert_createrdn bug 334683: extraneous semicolons cause empty declaration compiler warnings bug 335275: compile with the gcc flag -werror-implicit-function-declaration bug 354565: fipstest sha_test needs to detect sha tests that are incorrectly configured for bit oriente...
...And 6 more matches
NSS Tools ssltap
-h
turn on hex/ascii printing.
... -f
turn on fancy printing.
... -s
turn on ssl parsing and decoding.
...And 6 more matches
GC Rooting Guide
if (!waserror) *valueout = resultvalue; re
turn waserror; } void otherfunction(jscontext *cx) { js::value value; bool success = maybegetvalue(cx, &value); // ...
... 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!
...And 6 more matches
Hacking Tips
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 ...
... $ 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.
... │ auto funcptr = js_data_to_func_ptr(exportfuncptr, codebase() + func.entryoffset()); │ if (!call_generated_2(funcptr, exportargs.begin(), &tlsdata_)) │ re
turn false; after it's set, x/64i funcptr will show you the trampoline code.
...And 6 more matches
Tracing JIT
when the fragment is destroyed, it re
turns its pages to the fragmento for reuse.
...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.
...And 6 more matches
Querying Places
the defaults for these objects will result in a query that re
turns all of your browser history in a flat list: chromeutils.definemodulegetter(this, "placesutils", "resource://gre/modules/placesutils.jsm"); // no query options set will get all history, sorted in database order, // which is nsinavhistoryqueryoptions.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.
... 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.
...And 6 more matches
nsIApplicationCacheService
re
turn value the nsiapplicationcache best able to serve the resource indicated by the key parameter.
... re
turn value the newly-created nsiapplicationcache.
... getactivecache() re
turns the currently active cache object for a cache group.
...And 6 more matches
nsIBrowserSearchService
re
turns the first visible engine if the default engine is hidden.
...this differs from the "defaultengine" attribute in that it always re
turns a given build's default engine, regardless of whether it is hidden.
... getdefaultengines() re
turns an array of all default search engines.
...And 6 more matches
nsICommandLine
methods findflag() finds a command-line flag, re
turning its position on the command line.
... 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.
... re
turn value the value of the specified argument.
...And 6 more matches
nsIEventListenerService
er(in nsidomeventtarget target, in domstring type, in nsidomeventlistener listener, in boolean usecapture); 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.
... 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.
...note: some events, especially 'load', may actually have a shorter event target chain than what this methods re
turns.
...And 6 more matches
nsILocaleService
this method re
turns something similar to getsystemlocale.
...re
turn value the user's os setting for preferred locale.
...this method re
turns the same as getsystemlocale.getcategory("nsilocale_messages").
...And 6 more matches
nsINavHistoryQueryOptions
note that this has no effect on folder links, which are place: uris re
turned by nsinavbookmarkservice's getfolderuri method.
...the query is exeucted, the results are sorted, and then the top maxresults results are taken and re
turned.
... results_as_date_query 3 re
turns nsinavhistoryqueryresultnode nodes for each predefined date range where we had visits.
...And 6 more matches
nsIProtocolProxyService
proxy auto config (pac) may perform a synchronous dns query, which may not re
turn immediately.
...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.
...And 6 more matches
nsISHEntry
(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.
... re
turn value clearchildshells() clear the child shell list.
...re
turn value native code only!create additional ways to create an entry.
...And 6 more matches
nsISecurityCheckedComponent
the two special re
turn values of '"allaccess" or "noaccess" unconditionally allow or deny access to the operation.
...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.
... re
turn value the capability required to call this method.
...And 6 more matches
nsISelection2
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).
... methods getrangesforinterval() re
turn array of ranges intersecting with the given dom interval.
... allowadjacent specifies whether the re
turned ranges are allowed to touch the input range rather than merely overlapping it.
...And 6 more matches
nsIWindowWatcher
rnotification(in nsiobserver aobserver); void setwindowcreator(in nsiwindowcreator creator); void unregisternotification(in nsiobserver aobserver); attributes attribute type description activewindow nsidomwindow the watcher serves as a global storage facility for the current active (front most non-floating-palette-type) window, storing and re
turning it on demand.
... re
turn value an nsiwebbrowserchrome object for the corresponding chrome window getnewauthprompter() re
turn a newly created nsiauthprompt implementation.
... re
turn value a new nsiauthprompt object.
...And 6 more matches
nsIXmlRpcClient
qiresult result); void asynccall (in nsixmlrpcclientlistener 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.
... result readonly nsisupports the most recent xml-rpc call result re
turned from this server.
...And 6 more matches
Using COM from js-ctypes
cocreateinstance(clsid_spvoice, null, clsctx_all, iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->speak(l"hello, firefox!", spf_default, null); pvoice->release(); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); re
turn 0; } to run the code, save it as test.cpp, and run following command in the directory (needs visual studio).
...id_spvoice, null, clsctx_all, &iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->lpvtbl->speak(pvoice, l"hello, firefox!", 0, null); pvoice->lpvtbl->release(pvoice); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); re
turn 0; } to run the code, save it as test.c, and run following command in the directory.
... &iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->lpvtbl->speak(pvoice, l"hello, firefox!", spf_default, null); pvoice->lpvtbl->release(pvoice); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); re
turn 0; } converting c code to js-ctypes code now we have working c code.
...And 6 more matches
Using js-ctypes
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: this example will not work on 64bit os x, see below for core foundation for 64bit os x /* build a str255 ("pascal style") string from the passed-in string */ function 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 */ ...
..., /* alert param */ ctypes.int16_t); /* item hit */ var hit = 0; var msgerr = makestr("carbon says..."); var msgexp = makestr("we just called the standardalert carbon function from javascript!"); var err = stdalert(1, msgerr, msgexp, 0, hit); carbon.close(); the makestr() function is a utility routine that takes as input a standard javascript string and re
turns a carbon-style "pascal" string, which is a length byte followed by the characters of the string itself.
...And 6 more matches
BluetoothRemoteGATTCharacteristic - Web APIs
l bluetoothdescriptoruuid descriptor); promise<dataview> readvalue(); promise<void> writevalue(buffersource value); 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.
...And 6 more matches
DOMTokenList - Web APIs
such a set is re
turned by element.classlist, htmllinkelement.rellist, htmlanchorelement.rellist, htmlareaelement.rellist, htmliframeelement.sandbox, or htmloutputelement.htmlfor.
... 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.
...And 6 more matches
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.
... re
turn value the string value of the specified attribute.
...And 6 more matches
Element.getBoundingClientRect() - Web APIs
the element.getboundingclientrect() method re
turns the size of an element and its position relative to the viewport.
... 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.
...if all the element's border-boxes are empty, then a rectangle is re
turned with a width and height of zero and where the top and left are the top-left of the border-box for the first css box (in content order) for the element.
...And 6 more matches
Fullscreen API - Web APIs
methods the fullscreen api adds methods to the document and element interfaces to allow
turning off and on full-screen mode.
...re
turns a promise which is resolved once full-screen mode has been completely shut off.
...re
turns a promise which is resolved once full-screen mode has been activated.
...And 6 more matches
HTMLVideoElement - Web APIs
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.
... 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.
...And 6 more matches
IDBIndex - Web APIs
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.
... 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.
... idbindex.get() 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 an idbkeyrange.
...And 6 more matches
MediaStream - Web APIs
constructor mediastream() creates and re
turns a new mediastream object.
... mediastream.active read only a boolean value that re
turns true if the mediastream is active, or false otherwise.
... mediastream.clone() re
turns a clone of the mediastream object.
...And 6 more matches
MutationRecord - Web APIs
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.
... mutationrecord.addednodes nodelist re
turn the nodes added.
...And 6 more matches
NavigatorID - Web APIs
navigatorid.appcodename read only always re
turns "mozilla", in any browser.
... navigatorid.appname read only always re
turns "netscape", in any browser.
... navigatorid.appversion read only re
turns either "4.0" or a string representing version information about the browser.
...And 6 more matches
PerformanceEntry.startTime - Web APIs
the starttime property re
turns the first recorded timestamp of the performance entry.
... 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().
...And 6 more matches
RTCIceServers.urls - Web APIs
these are typically stun and/or
turn servers.
... syntax var iceserver = { urls = iceserverurl | [ url1, ..., urln ], username: "webrtc", // optional credential: "
turnpassword" // optional }; iceservers.push(iceserver); the value of this property may be specified as a single url or as an array of multiple urls.
... a single ice server with authentication the second example creates a new rtcpeerconnection which will use a
turn server at
turnserver.example.org to negotiate connections.
...And 6 more matches
RTCIceTransport - Web APIs
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.
... 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.
... getlocalparameters() re
turns a rtciceparameters object describing the ice parameters established by a call to the rtcpeerconnection.setlocaldescription() method.
...And 6 more matches
Request - Web APIs
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.
... request.destination read only re
turns a string from the requestdestination enum describing the request's destination.
... request implements body, so it also has the following methods available to it: body.arraybuffer() re
turns a promise that resolves with an arraybuffer representation of the request body.
...And 6 more matches
Response - Web APIs
you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being re
turned as the result of another api operation—for example, a service worker fetchevent.respondwith, or a simple windoworworkerglobalscope.fetch().
... response.error() re
turns a new response object associated with a network error.
...it re
turns a promise that resolves with an arraybuffer.
...And 6 more matches
Screen - Web APIs
screen.availleft re
turns the first available pixel available from the left side of the screen.
... 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.
...And 6 more matches
ShadowRoot - Web APIs
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.
...And 6 more matches
UIEvent - Web APIs
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.
...And 6 more matches
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.
...And 6 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
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.
...ax: |*| var timeoutid = window.settimeout(func, delay[, arg1, arg2, ...]); |*| var timeoutid = window.settimeout(code, delay); |*| var intervalid = window.setinterval(func, delay[, arg1, arg2, ...]); |*| var intervalid = 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.
... */ ) { var aargs = array.prototype.slice.call(arguments, 2); re
turn __nativest__(vcallback instanceof function ?
...And 6 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.
...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.
...And 6 more matches
XRView - Web APIs
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.
...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 && !transversedistance && !verticaldistance) { re
turn refspace; } // compute the quaternion used to rotate the image based // on the pitch and yaw.
...And 6 more matches
Feature-Policy - HTTP
when this policy is disabled and there were no user gestures, the promise re
turned by htmlmediaelement.play() will reject with a domexception.
...when this policy is disabled, the promise re
turned by navigator.getbattery() will reject with a notallowederror domexception.
...when this policy is disabled, the promise re
turned by getusermedia() will reject with a notallowederror domexception.
...And 6 more matches
Loops and iteration - JavaScript
control re
turns to step 2.
... <option>new age</option> <option>classical</option> <option>opera</option> </select> </p> <p><input id="btn" type="button" value="how many are selected?" /></p> </form> <script> function howmany(selectobject) { let numberselected = 0; for (let i = 0; i < selectobject.options.length; i++) { if (selectobject.options[i].selected) { numberselected++; } } re
turn numberselected; } let btn = document.getelementbyid('btn'); btn.addeventlistener('click', function() { alert('number of options selected: ' + howmany(document.selectform.musictypes)); }); </script> do...while statement the do...while statement repeats until a specified condition evaluates to false.
...if the condition re
turns true, statement is executed and the condition is tested again.
...And 6 more matches
Regular expressions - JavaScript
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 re
turns an array of information or null on a mismatch.
...it re
turns true or false.
...And 6 more matches
Working with objects - JavaScript
lowing function displays the properties of the object when you pass the object 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 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.
...And 6 more matches
Default parameters - JavaScript
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.
... function multiply(a, b) { re
turn a * b } multiply(5, 2) // 10 multiply(5) // nan !
... 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.
...And 6 more matches
Array.from() - JavaScript
re
turn value a new array instance.
...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)); }; 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 ?
...And 6 more matches
Function.prototype.bind() - JavaScript
re
turn value a copy of the given function with the specified this value, and initial arguments (if provided).
....slice; function.prototype.bind = function() { var thatfunc = this, thatarg = arguments[0]; var args = slice.call(arguments, 1); if (typeof thatfunc !== 'function') { // closest thing possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - ' + 'what is trying to be bound is not callable'); } re
turn function(){ var funcargs = args.concat(slice.call(arguments)) re
turn thatfunc.apply(thatarg, funcargs); }; }; })(); you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.
...rototype.bind - what is trying to be bound is not callable'); } var baseargs= arrayprototypeslice.call(arguments, 1), baseargslength = baseargs.length, ftobind = this, fnop = function() {}, fbound = function() { baseargs.length = baseargslength; // reset to default base arguments baseargs.push.apply(baseargs, arguments); re
turn ftobind.apply( fnop.prototype.isprototypeof(this) ?
...And 6 more matches
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.
...And 6 more matches
String.fromCharCode() - JavaScript
the static string.fromcharcode() method re
turns a string created from the specified sequence of utf-16 code units.
... 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.
...And 6 more matches
TypedArray.prototype.find() - JavaScript
the find() method re
turns a value in the typed array, if an element satisfies the provided testing function.
... otherwise undefined is re
turned.
... see also the findindex() method, which re
turns the index of a found element in the typed array instead of its value.
...And 6 more matches
TypedArray.prototype.findIndex() - JavaScript
the findindex() method re
turns an index in the typed array, if an element in the typed array satisfies the provided testing function.
... otherwise -1 is re
turned.
... see also the find() method, which re
turns the value of a found element in the typed array instead of its index.
...And 6 more matches
typeof - JavaScript
the typeof operator re
turns a string indicating the type of the unevaluated operand.
... 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.
...And 6 more matches
Web Components
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.
... window.customelements re
turns a reference to the customelementregistry object.
... the element.shadowroot property re
turns the shadow root attached to the specified element, or null if there is no shadow root attached.
...And 6 more matches
Using the WebAssembly JavaScript API - WebAssembly
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.
... 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.
... 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.
...And 6 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
$ 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.
... 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.
...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.
...And 6 more matches
Modules - Archive of obsolete content
to prevent scripts from interfering with each other, loadscript should evaluate each script to be loaded in the scope of their own global object, and then re
turn the global object as its result.
...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.
...=> 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
Private Properties - Archive of obsolete content
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.
... 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.
...before explaining how weakmaps work, the following looks at how ordinary objects can be used as hash maps, by creating a simple image cache: let images = {}; function getimage(name) { let image = images[name]; if (!image) { image = loadimage(name); images[name] = image; } re
turn image; } now suppose there's a need to associate a thumbnail with each image.
...And 5 more matches
content/mod - Archive of obsolete content
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.
...And 5 more matches
Finding window handles - Archive of obsolete content
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.
... 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.
... .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!
...And 5 more matches
Miscellaneous - Archive of obsolete content
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.
... var osstring = services.appinfo.os; detecting the host application and version // get the name of the application running us services.appinfo.name; // re
turns "firefox" for firefox services.appinfo.version; // re
turns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous callback function that might not be called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see aroun...
...it also collapses consecutive whitespaces into a single whitespace, and re
turns at most 150 characters, making it ideal to display text in context menus.
...And 5 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
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).
... another option is to send a re
turn event from the extension to the web page.
... { 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 ?
...And 5 more matches
Adding windows and dialogs - Archive of obsolete content
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 the simplest way to have the dialog re
turn something to its opener.
...And 5 more matches
Using Dependent Libraries In Extension Components - Archive of obsolete content
// assume that we're in <extensiondir>/components, and we want to find // <extensiondir>/libraries 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...
... } 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.
... // assume that we're in <extensiondir>/components, and we want to find // <extensiondir>/libraries 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")); nscstring path; // loop through and load dependent libraries for (char const *const *dependent = kdependentlibraries; *dependent; ++dependent) { library->...
...And 5 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
n", 5); /* 3) define here (because if set after "4)" below it doesn't work!) processldapvalues which is eventually called by getldapattributes() just below, check getldapattributes() code from $mozilla_home/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processldapvalues */ function processldapvalues(values) { if(values) { // set the global var with the values re
turned from the ldap query ldap_values = values; var uid = getldapvalue(values, "uid"); var cn = getldapvalue(values, "cn"); var mail = getldapvalue(values, "mail"); var url = getldapvalue(values, "labeleduri"); // those ldap variables are only available in this processldapvalues context!
..."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 .
...es which is eventually called by getldapattributes() just below, // check getldapattributes() code from $mozilla_home/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processldapvalues /* commented all this section about ldap calls, not supported in ff5 packages :-( function processldapvalues (values) { if(values) { // set the global var with the values re
turned from the ldap query ldap_values = values; var uid = getldapvalue ( values ,"uid" ); var cn = getldapvalue ( values ,"cn" ); var mail = getldapvalue ( values ,"mail" ); var url = getldapvalue ( values ,"labeleduri" ); //debug with popup error messages doesn't work anymore :-( !!
...And 5 more matches
Exception logging in JavaScript - Archive of obsolete content
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.
... the ns_nointerface error is never reported when re
turned by a javascript object's queryinterface() method on the nsisupports interface.
...And 5 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...
... if (typeof(crypto.version) != "undefined") { crmfobject = crypto.generatecrmfrequest( "cn=" + form.name.value, form.password.value, authenticator, keytransportcert, "setcrmfrequest();", 1024, null, "rsa-dual-use"); } re
turn false; } function setcrmfrequest() { form.cert_request.value = crmfobject.request; form.submit(); } form.onsubmit = validate; </script> on completion of the request, the ca may submit a page that looks something like this: <!doctype html> <h2>certificate request successful</h2> <p>hit 'load' to load your certificate</p> <form name="reqform"> <p><input type=submit name="load" value="submi...
...t"></p> </form> <script> /* the following values could be filled in by the server cgi */ var nickname= "mycertnickname"; var cert = "mkjflakdjfiwjflaksufklasf ..."; var forcebackup = false; function loadcertificate() { window.crypto.importusercertificates(nickname, cert, forcebackup); re
turn false; } document.forms[0].onsubmit = loadcertificate; </script> signing text domstring signtext(domstring stringtosign, domstring caoption /* ...
...And 5 more matches
Menu - Archive of obsolete content
item(target) re
turns an item in the menu.
... re
turn value a menuitem object, or null if no such target exists.
...it must re
turn a non-function menuitem.
...And 5 more matches
Methods - Archive of obsolete content
dirgetparent re
turns an object representing the parent directory.
... 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.
...And 5 more matches
Index - Archive of obsolete content
this will re
turn a table of result records which are then used to generate output.
...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.
... 995 xul questions and answers re
turn to mozilla-dev-tech-xul summaries 996 xul reference xul, xul reference no summary!
...And 5 more matches
Box Objects - Archive of obsolete content
all values re
turned are in pixels.
...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.
... note that retrieving these values will re
turn the size only if it was explicitly specified.
...And 5 more matches
Tree Box Objects - Archive of obsolete content
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.
...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.
...And 5 more matches
notificationbox - Archive of obsolete content
node, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appendnotification( label , value , image , priority , buttons, eventcallback ) re
turn type: element create a new notification and display it.
... if the re
turn value from this function is not true, then the notification is closed.
... getnotificationwithvalue( value ) re
turn type: notification element retrieve the notification with a particular value.
...And 5 more matches
NPAPI plugin reference - Archive of obsolete content
np_getmimedescription np_getmimedescription re
turns a supported mime type list for your plugin.
... npn_getintidentifier re
turns an opaque identifier for the integer that is passed in.
... npn_getstringidentifier re
turns an opaque identifier for the string that is passed in.
...And 5 more matches
Implementing controls using the Gamepad API - Game development
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.
...it works independently, so it could be
turned on even if the gamepad is not connected.
...it will launch the game in the super turbo mode and you'll be able to control the fridge with the keyboard: a and d for
turning the turret left and right, w for shooting and arrow keys for movement.
...And 5 more matches
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
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 | 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.
... 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.
...And 5 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
settimeout() re
turns an identifier value that can be used to refer to the timeout later, such as when you want to stop it.
...function once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); just like settimeout(), setinterval() re
turns an identifying value you can use later when you need to clear the interval.
...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!
...And 5 more matches
Storing the information you need — Variables - Learn web development
when you enter the variable names, you should get a value of undefined re
turned.
...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.
...And 5 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
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.
... try saving and refreshing again, and your console.log() statement should re
turn the <p> element we want.
... there's definitely a problem in the game logic somewhere — the game is not re
turning an error; it just isn't playing right.
...And 5 more matches
Commenting IDL for better documentation
we will take your comments and notes and
turn them into beautiful, easy to search and read documentation.
...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.
... @re
turns description if the method re
turns something then this should be included.
...And 5 more matches
Download
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.
... 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.
...And 5 more matches
Promise.jsm
a reference to an existing promise may be received by different means, for example as the re
turn value of a call into an asynchronous api.
...the method re
turns a new promise that, in
turn, is fulfilled or rejected depending on the state of the original promise and on the behavior of the callbacks.
... 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.
...And 5 more matches
gettext
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.
...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.
...And 5 more matches
Introduction to NSPR
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.
...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.
...at this time, the only safe solutions are to
turn off preemption (a runtime decision) or to preempt global threads only.
...And 5 more matches
NSS tools : ssltab
-h
turn on hex/ascii printing.
...-f
turn on fancy printing.
...-s
turn on ssl parsing and decoding.
...And 5 more matches
NSS tools : ssltap
-h
turn on hex/ascii printing.
...-f
turn on fancy printing.
...-s
turn on ssl parsing and decoding.
...And 5 more matches
sslerr.html
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.
... -12278 (unused) ssl_error_wrong_certificate -12277 "client authentication failed: private key in key database does not correspond to public key in certificate database." ssl_error_bad_cert_domain -12276 "unable to communicate securely with peer: requested domain name does not match the server's certificate." this error code should be re
turned by the certificate authentication callback function when it detects that the common name in the remote server's certificate does not match the hostname sought by the local client, according to the matching rules specified for cert_verifycertname.
...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.
...And 5 more matches
NSS tools : ssltap
-h
turn on hex/ascii printing.
... -f
turn on fancy printing.
... -s
turn on ssl parsing and decoding.
...And 5 more matches
Rhino Debugger
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 resume but control will re
turn to the debugger at the next line in the current function or top-level script.
...And 5 more matches
JS::IdentifyStandardInstance
if so, re
turn the associated jsprotokey.
... if not, re
turn jsproto_null.
...if so, re
turn the associated jsprotokey.
...And 5 more matches
JS::Value
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.
...(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 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.isobjectornull() re
turns true if the value is either an object or undefined.
...And 5 more matches
JS_GetFunctionId
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.
...And 5 more matches
IAccessibleApplication
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.
... re
turn value s_false if there is nothing to re
turn, [out] value is null.
...appversion() re
turns the application version.
...And 5 more matches
nsIAccessibleDocument
when accessibility is
turned on in gecko, there is an nsiaccessibledocument for each document whether it is xul, html or whatever.
... 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 5 more matches
nsIAccessibleTableCell
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.
... columnheadercells nsiarray re
turn an array of column header cells for this cell.
... columnindex long re
turn column index of this cell.
...And 5 more matches
nsICookieManager2
cookieexists() re
turns whether or not a matching cookie already exists.
... 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.
...And 5 more matches
nsIEnvironment
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.
...note: * for unix/linux platforms we follow the unix definition: an environment variable exists when getenv() re
turns a non-null value.
...And 5 more matches
nsIFocusManager
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.
...And 5 more matches
nsILivemarkService
re
turn value the id of the folder for the livemark.
... re
turn value re
turns the id of the folder for the livemark.
... re
turn value a nsiuri representing the uri of the feed; if the livemark container doesn't have a valid feed uri, null will be re
turned or the nsiuri object re
turned will be the empty string.
...And 5 more matches
nsIMsgFolder
will re
turn nsmsgkey_none if there was no last message loaded.
... 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.
...And 5 more matches
nsINavHistoryResultTreeViewer
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.
...And 5 more matches
nsITreeColumns
nsitreecolumn getcolumnat( in long index ); parameters index index of the column re
turn value a nsitreecolumn for this index.
...nsitreecolumn getcolumnfor( in nsidomelement element ); parameters element a dom element re
turn value a nsitreecolumn for this element.
...re
turn value the first nsitreecolumn.
...And 5 more matches
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.
...And 5 more matches
Working with Multiple Versions of Interfaces
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 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 5 more matches
Working with windows in chrome code
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.
...the re
turn value of window.open (and similar methods) is a window object (usually chromewindow) – the same type as the window variable.
... note however, that the open() call re
turns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail.
...And 5 more matches
ArrayType
arraytype represents c arrays syntax re
turns a new ctype representing an array data type.
... re
turn value a ctype represents the newly declared array type.
... ptr ctype re
turns a ctype representing the data type "pointer to this type".
...And 5 more matches
CType
ptr ctype re
turns a ctype representing the data type "pointer to this type".
... 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.
... re
turn value a ctype representing the data type "array of this type".
...And 5 more matches
FunctionType
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.
...And 5 more matches
ctypes
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.
... for example, ctypes.char.array(30)(str) converts the string str to utf-8 and re
turns a new cdata object of array type.
...this can only be used as a re
turn value type.
...And 5 more matches
Drawing and Event Handling - Plugins
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.
... unix and ms windows the queried information is re
turned in the variable parameter.
...the value parameter re
turns the name of the plug-in.
...And 5 more matches
CSS Typed Object Model API - Web APIs
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.
... cssunparsedvalue.entries() method re
turning 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).
...And 5 more matches
CharacterData - Web APIs
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.
...And 5 more matches
DOMParser - Web APIs
note: xmlhttprequest can parse xml and html directly from a url-addressable resource, re
turning a document in its response property.
... 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.
...this string determines a class of the the method's re
turn value.
...And 5 more matches
DirectoryEntrySync - Web APIs
example the getfile() method re
turns a fileentrysync, which represents a file in the file system.
... var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method re
turns a directoryentrysync, which represents a file in the file system.
... directoryreadersync createreader ( ) raises (fileexception); re
turns directoryreadersync represents a directory in a file system.
...And 5 more matches
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.
... 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.
...And 5 more matches
Element.getClientRects() - Web APIs
the getclientrects() method of the element interface re
turns a collection of domrect objects that indicate the bounding rectangles for each css border box in a client.
... syntax let rectcollection = object.getclientrects(); re
turn value the re
turned value is a collection of domrect objects, one for each css border box associated with the element.
... originally, microsoft intended this method to re
turn a textrectangle object for each line of text.
...And 5 more matches
HTMLMediaElement.play() - Web APIs
it re
turns a promise which is resolved when playback has been successfully started.
... 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().
...And 5 more matches
HTMLObjectElement - Web APIs
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.
...And 5 more matches
HTMLSelectElement - Web APIs
if the element is not associated with of a <form> element, then it re
turns null.
...when multiple is true, it re
turns "select-multiple"; otherwise, it re
turns "select-one".
...re
turns the value property of the first selected option element if there is one, otherwise the empty string.
...And 5 more matches
IDBCursor - Web APIs
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.
...And 5 more matches
IDBIndexSync - Web APIs
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.
... re
turns any the retrieved value from the index.
... getobject() retrieves and re
turns the value from this index's referenced object store that corresponds to the given key.
...And 5 more matches
IDBRequest - Web APIs
all asynchronous operations immediately re
turn an idbrequest instance.
...when the state is set to done, every request re
turns a result and an error, and an event is fired on the request.
... in plain words, all asynchronous methods re
turn a request object.
...And 5 more matches
Recording a media element - Web APIs
while the article using the mediastream recording api demonstrates using the mediarecorder interface to capture a mediastream generated by a hardware device, as re
turned by navigator.mediadevices.getusermedia(), you can also use an html media element (namely <audio> or <video>) as the source of the mediastream to be recorded.
... 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.
... recorder.ondataavailable = event => data.push(event.data); recorder.start(); log(recorder.state + " for " + (lengthinms/1000) + " seconds..."); let stopped = new promise((resolve, reject) => { recorder.onstop = resolve; recorder.onerror = event => reject(event.name); }); let recorded = wait(lengthinms).then( () => recorder.state == "recording" && recorder.stop() ); re
turn promise.all([ stopped, recorded ]) .then(() => data); } startrecording() takes two input parameters: a mediastream to record from and the length in milliseconds of the recording to make.
...And 5 more matches
Capabilities, constraints, and settings - Web APIs
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.
... the track's getconstraints() method re
turns the set of constraints passed into the most recent call to applyconstraints().
...if the width, height, framerate, or facingmode constraints can't be met, the promise re
turned by applyconstraints() will be rejected.
...And 5 more matches
MouseEvent - Web APIs
mouseevent derives from uievent, which in
turn derives from event.
... mouseevent.altkey read only re
turns true if the alt key was down when the mouse event was fired.
... mouseevent.ctrlkey read only re
turns true if the control key was down when the mouse event was fired.
...And 5 more matches
NodeIterator - Web APIs
the nodes will be re
turned in document order.
... 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.
...And 5 more matches
PaymentRequest.show() - Web APIs
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.
... re
turn value a promise that eventually resolves with a paymentresponse.
... exceptions aborterror the re
turned promise rejects with an aborterror if the user agent is already showing a payment panel.
...And 5 more matches
PaymentRequestEvent - Web APIs
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.
... modifiersread only re
turns an array of objects containing changes to payment details.
...And 5 more matches
Using the Payment Request API - Web APIs
so for example, you could create a new paymentrequest instance like so: var request = new paymentrequest(buildsupportedpaymentmethoddata(), buildshoppingcartdetails()); the functions invoked 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', display...
...this re
turns a promise that fulfills with a paymentresponse object if the payment is successful: request.show().then(function(paymentresponse) { // here we would process the payment.
...it re
turns a promise that fulfills with a boolean indicating whether it is or not, for example: // dummy payment request to check whether payment can be made new paymentrequest(buildsupportedpaymentmethoddata(), {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(result) { if(result) { // real payment request va...
...And 5 more matches
PerformanceTiming - Web APIs
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.
...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.
...if there is no redirect, or if one of the redirects is not of the same origin, the value re
turned is 0.
...And 5 more matches
Request.cache - Web APIs
if there is a match and it is fresh, it will be re
turned from the cache.
...if the server indicates that the resource has not changed, it will be re
turned from the cache.
...if the server indicates that the resource has not changed, it will be re
turned from the cache.
...And 5 more matches
SpeechRecognition - Web APIs
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.
... speechrecognition.continuous controls whether continuous results are re
turned for each recognition, or only a single result.
...And 5 more matches
SpeechRecognitionEvent - Web APIs
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.
...And 5 more matches
TextEncoder - Web APIs
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.
... textencoder.prototype.encodingread only always re
turns "utf-8".
... textencoder.prototype.encode() takes a usvstring as input, and re
turns a uint8array containing utf-8 encoded text.
...And 5 more matches
URL - Web APIs
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.
... 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.
...And 5 more matches
URLSearchParams - Web APIs
constructor urlsearchparams() re
turns a urlsearchparams object instance.
... urlsearchparams.entries() re
turns an iterator allowing iteration through all key/value pairs contained in this object.
... urlsearchparams.get() re
turns the first value associated with the given search parameter.
...And 5 more matches
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
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.
...And 5 more matches
WebGL2RenderingContext.getActiveUniforms() - Web APIs
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.
...And 5 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.
... re
turn value depends on the parameter.
...And 5 more matches
A basic 2D WebGL animation example - Web APIs
its role is to re
turn the color of each pixel in the shape being rendered.
... the shader set is passed into the function buildshaderprogram(), which re
turns the compiled and linked shader program.
... 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.
...And 5 more matches
Adding 2D content to a WebGL context - Web APIs
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 color is then re
turned to the webgl layer by storing it in the special variable gl_fragcolor.
... in this case, we're simply re
turning white every time, since we're just drawing a white square, with no lighting in use.
...And 5 more matches
WebGL model view projection - Web APIs
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.
... the obvious question is "why the extra dimension?" it
turns out that this addition allows for lots of nice techniques for manipulating 3d data.
... 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.
...And 5 more matches
Using XMLHttpRequest - Web APIs
"\r\n" : "&")); } } } function processstatus (odata) { if (odata.status > 0) { re
turn; } /* the form is now totally serialized!
...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 ?
.../* enctype is multipart/form-data */ "content-disposition: form-data; name=\"" + ofield.name + "\"\r\n\r\n" + ofield.value + "\r\n" : /* enctype is application/x-www-form-urlencoded or text/plain or method is get */ ffilter(ofield.name) + "=" + ffilter(ofield.value) ); } } processstatus(this); } re
turn function (oformelement) { if (!oformelement.action) { re
turn; } new submitrequest(oformelement); }; })(); </script> </head> <body> <h1>sending forms with pure ajax</h1> <h2>using the get method</h2> <form action="register.php" method="get" onsubmit="ajaxsubmit(this); re
turn false;"> <fieldset> <legend>registration example</legend> <p> first name: <input type="text" ...
...And 5 more matches
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
the static method xrwebgllayer.getnativeframebufferscalefactor() re
turns a floating-point scaling factor by which one can multiply the specified xrsession's resolution to get the native resolution of the webxr device's frame buffer.
... 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.
...And 5 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
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.
...the text must not include carriage re
turns or line feeds.
... 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.
...And 5 more matches
Grammar and types - JavaScript
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.
... /** * example 1 */ console.log(x === undefined); // true var x = 3; /** * example 2 */ // will re
turn a value of undefined var myvar = 'my value'; (function() { console.log(myvar); // undefined var myvar = 'local value'; })(); the above examples will be interpreted the same as: /** * example 1 */ var x; console.log(x === undefined); // true x = 3; /** * example 2 */ var myvar = 'my value'; (function() { var myvar; console.log(myvar); // undefined myvar = 'local value'; })(); because of hoisting, all var statements in a function should be placed as near to the top of the function as possible.
...And 5 more matches
Public class fields - JavaScript
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.
... class classwithstaticfield { static basestaticfield = 'base static field' static anotherbasestaticfield = this.basestaticfield static basestaticmethod() { re
turn 'base static method output' } } class subclasswithstaticfield extends classwithstaticfield { static substaticfield = super.basestaticmethod() } console.log(classwithstaticfield.anotherbasestaticfield) // expected output: "base static field" console.log(subclasswithstaticfield.substaticfield) // expected output: "base static method output" public instance fields public instance fields exis...
... 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.
...And 5 more matches
arguments.callee - JavaScript
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) ?
...to get around this arguments.callee was added so you could do [1, 2, 3, 4, 5].map(function(n) { re
turn !(n > 1) ?
...And 5 more matches
getter - JavaScript
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.
... 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.
...And 5 more matches
Array.prototype.slice() - JavaScript
the slice() method re
turns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.
... if start is greater than the index range of the sequence, an empty array is re
turned.
... re
turn value a new array containing the extracted elements.
...And 5 more matches
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
re
turn value an array of objects containing the formatted date in parts.
...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".
...And 5 more matches
String.prototype.codePointAt() - JavaScript
the codepointat() method re
turns a non-negative integer that is the unicode code point value.
... 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.
...And 5 more matches
Logical AND (&&) - JavaScript
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.
... syntax expr1 && expr2 description if expr1 can be converted to true, re
turns expr2; else, re
turns expr1.
...And 5 more matches
Logical OR (||) - JavaScript
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.
... syntax expr1 || expr2 description if expr1 can be converted to true, re
turns expr1; else, re
turns expr2.
...And 5 more matches
Nullish coalescing operator (??) - JavaScript
the nullish coalescing operator (??) is a logical operator that re
turns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise re
turns its left-hand side operand.
... contrary to the logical or (||) operator, the left operand is re
turned if it is a falsy value which is not null or undefined.
...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.
...And 5 more matches
void operator - JavaScript
the void operator evaluates the given expression and then re
turns undefined.
... 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.
... 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.
...And 5 more matches
Using custom elements - Web Components
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.
... // create a shadow root this.attachshadow({mode: 'open'}); // sets and re
turns 'this.shadowroot' // create (nested) span elements const wrapper = document.createelement('span'); wrapper.setattribute('class','wrapper'); const icon = wrapper.appendchild(document.createelement('span')); icon.setattribute('class','icon'); icon.setattribute('tabindex', 0); // insert icon from defined attribute or default icon const img = icon.appendchild(document.createelement('img')); img.src...
...this
turns any unordered list into an expanding/collapsing menu.
...And 5 more matches
Caching compiled WebAssembly modules - WebAssembly
in our wasm-utils.js library script, you'll find instantiatecachedurl() — this function fetches the wasm module at url with a version of dbversion, instantiates it with the given importobject, and re
turns a promise resolving to the finished wasm instance.
...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 (db.objectstorenames.contains(storename)) { console.log(`clearing out version ${event.oldversion} wasm cache`); db.deleteobjectstore(storename); } console.log(`creating version ${event.newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for looki...
...And 5 more matches
Classes and Inheritance - Archive of obsolete content
as it
turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code.
...moreover, if the constructor does not re
turn a value, the result of the call defaults to the value of this.
...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.
...And 4 more matches
passwords - Archive of obsolete content
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.
... because the search function is expected to re
turn a list of matching credentials, its oncomplete option is mandatory.
...And 4 more matches
Dialogs and Prompts - Archive of obsolete content
<?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.
... passing parameter to a dialog and getting re
turn values from it.
...And 4 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
it's available in the global for a window, but in jsm you'll need to fetch it from an interface: const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest"); here's how to load a file using it: function loadfile(url,type,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 ...
...here are some functions to handle this: function getgenericpref(branch,prefname) { switch (branch.getpreftype(prefname)) { default: case 0: re
turn undefined; // pref_invalid case 32: re
turn getucharpref(prefname,branch); // pref_string case 64: re
turn branch.getintpref(prefname); // pref_int case 128: re
turn branch.getboolpref(prefname); // pref_bool } } function setgenericpref(branch,prefname,prefvalue) { switch (typeof prefvalue) { case "string": setucharpref...
...(prefname,prefvalue,branch); re
turn; case "number": branch.setintpref(prefname,prefvalue); re
turn; case "boolean": branch.setboolpref(prefname,prefvalue); re
turn; } } function setdefaultpref(prefname,prefvalue) { var defaultbranch = services.prefs.getdefaultbranch(null); setgenericpref(defaultbranch,prefname,prefvalue); } function getucharpref(prefname,branch) // unicode getcharpref { branch = branch ?
...And 4 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
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 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.
...And 4 more matches
Tabbed browser - Archive of obsolete content
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.
... var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var recentwindow = wm.getmostrecentwindow("navigator:browser"); re
turn recentwindow ?
...in those cases, the following code re
turns null.
...And 4 more matches
MMgc - Archive of obsolete content
see below.) class myobject : public mmgc::gcobject { ~myobject() { assert(!"this will never be hit (unless we also descend from gcfinalizedobject)"); } }; gcobject::getweakref gcweakref *getweakref() const; the getweakref method re
turns a weak reference to the object.
...it has a get method which re
turns the pointer to the original object, or null if that object has already been destroyed.
...// 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.
...And 4 more matches
Autodial for Windows NT - Archive of obsolete content
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.
...to them it looks like mozilla is broken because windows doesn't try to dial when the feature is
turned on in control panel | internet options | connections when they are using mozilla but it does when they are using internet explorer.
...we try to mimic the autodial system service if it is not running and the user has the autodial feature
turned on in control panel | internet options | connections.
...And 4 more matches
JavaScript Client API - Archive of obsolete content
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.
... getallids() must re
turn an iterable list containing the guids of every item being stored on the local system.
...And 4 more matches
Supporting private browsing mode - Archive of obsolete content
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.
...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.
...ts.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var oldprivatemode = pbs.privatebrowsingmode; pbs.privatebrowsingenabled = true; /* this is all private */ pbs.privatebrowsingenabled = oldprivatemode; in this example, we save the current state of the private browsing mode setting in the oldprivatemode variable, then
turn on private browsing by setting its value to true.
...And 4 more matches
Creating a Wizard - Archive of obsolete content
set it to a script which performs whatever task you want and then re
turns true.
...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.
...And 4 more matches
Document Object Model - Archive of obsolete content
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.
... 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.
...And 4 more matches
Open and Save Dialogs - Archive of obsolete content
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 4 more matches
menupopup - Archive of obsolete content
re
turning false from this event handler prevents the popup from appearing.
...nsertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() re
turn type: no re
turn value closes the popup immediately.
... moveto( x, y ) re
turn type: no re
turn value moves the popup to a new location defined by screen coordinates (and not client coordinates).
...And 4 more matches
tooltip - Archive of obsolete content
re
turning false from this event handler prevents the popup from appearing.
...insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() re
turn type: no re
turn value closes the popup immediately.
... moveto( x, y ) re
turn type: no re
turn value moves the popup to a new location defined by screen coordinates (and not client coordinates).
...And 4 more matches
nsIContentPolicy - Archive of obsolete content
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).
... 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).
...And 4 more matches
Table Reflow Internals - Archive of obsolete content
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).
...a text run) user defined - currently only used for fixed positioned frames kinds of reflows incremental reflow (continued) reflower not allowed to change available size of reflowee reflow commands get coalesced to streamline processing style change a target changed stylistic if there is a target, otherwise every frame may need to respond parent of target usually
turns it into an incremental reflow with a style changed command type table frames nstableouter frame ↙ ↘ nstable frame nstablecaption frame ↙ ↘ ↓ nstablecol groupframe nstablerow groupframe nsblockframe ↓ ↓ nstablecol frame nstablerow frame ↓ nstablecell frame ↓ ...
...table reflow example <table width=300> <tr> <td>foo</td> <td>bar zap</td> </tr> </table> key: r = reflow reason, 0 (initial), 2 (resize) a = avail w, h c = computed w, h d = desired w, h me = max elem w debugging frame reflow gives instructions for
turning this on: tblo 030176cc r=0 a=8940,uc c=0,0 cnt=429 tbl 030178c4 r=0 a=8940,uc c=4470,uc cnt=430 rowg 03017a7c r=0 a=uc,uc c=uc,uc cnt=431 row 03017c08 r=0 a=uc,uc c=uc,uc cnt=432 cell 03017da8 r=0 a=uc,uc c=uc,uc cnt=433 block 03017e08 r=0 a=uc,uc c=uc,uc cnt=434 block 03017e08 d=870,300 me=480 cell 03017da8 d=930,360 me=540 cell 0301a8cc r=0 a=uc,u...
...And 4 more matches
E4X for templating - Archive of obsolete content
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, '"'...
... createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.call(arguments, 1); re
turn strs.formatstringfromname(msg,args,args.length); } re
turn strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined condition for e4x re
turn h(cond); } else if (_else) { re
turn _else(cond); } re
turn ''; // empty string al...
...lows conditions in attribute as well as element content } for example: {_if(elems.length(), function () <description>{elems[0]}</description>, function _else () <label>no data</label> )} note that the simple xmllist() constructor (<></>) may be useful to still be able to use an expression closure (i.e., without needing re
turn statements and braces): {_if(elems.length(), function () <> <markup/> <markup/> </>)} note that, while it is convenient to store such e4x in separate file templates (to be eval()d at a later time, taking into account security considerations, such as escaping with the above), e4x content using such functions can also be easily serialized inline (and then perhaps converted to the dom) as needed: var list = <>{_if(elems.length(), function () <> ...
...And 4 more matches
Iterator - Archive of obsolete content
the iterator function re
turns an object which implements legacy iterator protocol and iterates over enumerable properties of an object.
... keyonly if keyonly is truthy value, iterator.prototype.next re
turns property_name only.
... description re
turns iterator instance that iterates over object.
...And 4 more matches
JavaArray - Archive of obsolete content
created by any java method which re
turns an array.
... 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.
...for example: var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); bytearray[0] // re
turns 72 bytearray[1] // re
turns 101 any java data brought into javascript is converted to javascript data types.
...And 4 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
the present document describes the steps of what should be done to the plugin code to
turn it scriptable again.
...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.
... 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 4 more matches
Desktop gamepad controls - Game development
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.
...r || {}; var pressed = []; if(c.buttons) { for(var b=0,t=c.buttons.length; b<t; b++) { if(c.buttons[b].pressed) { pressed.push(gamepadapi.buttons.layout[b]); } } } var axes = []; if(c.axes) { for(var a=0,x=c.axes.length; a<x; a++) { axes.push(c.axes[a].tofixed(2)); } } gamepadapi.axes.status = 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.
...And 4 more matches
How to build custom form controls - Learn web development
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.
...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 object re
turned by the queryselectorall() function is a nodelist rather than an array.
...And 4 more matches
Images in HTML - Learn web development
users have
turned off images to reduce data transfer volume and distractions.
...if you put an image inside <a> tags, to
turn an image into a link, you still must provide accessible link text.
...try
turning off images in your browser and see how things look.
...And 4 more matches
Choosing the right approach - Learn web development
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.
... 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 ...
... it is better to use the chaining power of promises to go with a flatter, easier to parse structure: remotedb.alldocs(...).then(function (resultofalldocs) { re
turn localdb.put(...); }).then(function (resultofput) { re
turn localdb.get(...); }).then(function (resultofget) { re
turn localdb.put(...); }).catch(function (err) { console.log(err); }); or even: remotedb.alldocs(...) .then(resultofalldocs => { re
turn localdb.put(...); }) .then(resultofput => { re
turn localdb.get(...); }) .then(resultofget => { re
turn localdb.put(...); }) .catch(err => c...
...And 4 more matches
Functions — reusable blocks of code - Learn web development
every time we manipulated a text string, for example: let mytext = 'i am a string'; let newstring = mytext.replace('string', 'sausage'); console.log(newstring); // the replace() string function takes a source string, // and a target string and replaces the source string, // with the target string, and re
turns the newly formed string or every time we manipulated an array: let myarray = ['i', '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!
...the above function for example calls the random() function three times, which is defined by the following code: function random(number) { re
turn math.floor(math.random()*number); } we needed this function because the browser's built-in math.random() function only generates a random decimal number between 0 and 1.
...And 4 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
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.
...And 4 more matches
Creating Sandboxed HTTP Connections
since this is a stream, it could be called multiple times (depending on the size of the re
turned data, networking conditions, etc).
...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) ...
...aiid) { if (aiid.equals(components.interfaces.nsisupports) || aiid.equals(components.interfaces.nsiinterfacerequestor) || aiid.equals(components.interfaces.nsichanneleventsink) || aiid.equals(components.interfaces.nsiprogresseventsink) || aiid.equals(components.interfaces.nsihttpeventsink) || aiid.equals(components.interfaces.nsistreamlistener)) re
turn this; throw components.results.ns_nointerface; } }; quick note: storing the channel in a global (especially in an extension) isn't a good idea, but was done to make the code easier to read.
...And 4 more matches
HTTP Cache
currently we have 3 types of storages, all the access methods re
turn an nsicachestorage object: memory-only (memorycachestorage): stores data only in a memory cache, data in this storage are never put to disk disk (diskcachestorage): stores data on disk, but for existing entries also looks into the memory-only storage; when instructed via a special argument also primarily looks into application caches application cache (appcache...
...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...
... these callbacks are ensured to be invoked when asyncopenuri re
turns ns_ok.
...And 4 more matches
Implementing QueryInterface
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...
...orts*, ns_static_cast(nsix*, this)); // i (may) have multiple |nsisupports| in me, // 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 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.
...And 4 more matches
Add-on Repository
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.
... methods getrecommendedurl() re
turns the url that can be visited to see recommended add-ons.
... re
turn value an url indicating the repository's page of recommended add-ons.
...And 4 more matches
L20n Javascript API
ctx.registerlocalenegotiator(function(available, requested, deflocale) { re
turn intl.prioritizelocales(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 negotiator...
... 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.linkresource(function(locale) { re
turn '../locales/' + locale + '/strings.l20n'; }); the resource is added to all registered locales.
...And 4 more matches
PRThreadState
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.
... pr_joinable_thread joinable thread references remain valid after they have re
turned from their root function until pr_jointhread is called.
... the lifetime of a thread extends from the time it is created to the time it re
turns from its root function.
...And 4 more matches
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.
... 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.
...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, ...
... "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, p1)) { break; } pr_fprin...
...try again.\n"); } /* clear out the duplicate password string */ if (p1) { port_memset(p1, 0, port_strlen(p1)); port_free(p1); } fclose(input); fclose(output); re
turn p0; } /* * changepw */ secstatus changepw(pk11slotinfo *slot, char *oldpass, char *newpass, char *oldpwfile, char *newpwfile) { secstatus rv; secupwdata pwdata; secupwdata newpwdata; char *oldpw = null; char *newpw = null; if (oldpass) { pwdata.source = pw_plaintext; pwdata.data = oldpass; } else if (oldpwfile) { pwdata.source = pw_fromfile; pwdata.data = oldpwfile; } else { pwdata.source = pw_none; pwdata.data = null; } if (newpass) { n...
...And 4 more matches
JSDeletePropertyOp
if a jsdeletepropertyop does nothing and re
turns true, then property delete is unaffected.
... this callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then re
turning false.
...otherwise the callback must re
turn true, and the property operation proceeds.
...And 4 more matches
JS_DecompileScript
re
turn the source code of the script or the function.
... description js_decompilescript re
turns the source code of script.
...otherwise, it re
turns the original source code of the script.
...And 4 more matches
Split object
inner objects implement the jsextendedclass.outerobject hook, which re
turns a pointer to the corresponding outer object.
...the script in a might have opened tb by calling window.open, which re
turns a direct reference to tb's window.
...the outer window object is the object re
turned by window.open.
...And 4 more matches
Redis Tips
in standard node fashion, first re
turn value is error or null; second re
turn value is result of redis 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.
... they re
turn the post-increment value of your key.
...And 4 more matches
Using the Places history service
when isvisited re
turns true, the link gets the "visited" style.
...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.
...And 4 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.
...And 4 more matches
IAccessibleEditableText
re
turn value e_invalidarg if bad [in] passed.
... re
turn value e_invalidarg if bad [in] passed.
... re
turn value e_invalidarg if bad [in] passed.
...And 4 more matches
IAccessibleImage
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.
... re
turn value s_false if there is nothing to re
turn, [out] value is null.
...imageposition() re
turns the coordinates of the image.
...And 4 more matches
mozIStorageAggregateFunction
an aggregate function is a function that re
turns one value from a series of values.
... 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.
...And 4 more matches
mozIStorageService
the actual backup file is re
turned, and the resulting filename can be obtained from that.
... re
turn value an nsifile object representing the newly-created backup file.
...note: the connection object re
turned by this function is not threadsafe.
...And 4 more matches
mozITXTToHTMLConv
re
turn value the html version of the specified string.
... 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.
...And 4 more matches
nsIAccessibleSelectable
getselectedchildren() re
turns an nsiarray of the selected nsiaccessible children.
...re
turn value an nsiarray.
... re
turn value true if the child is selected, false if not.
...And 4 more matches
nsIAuthPrompt2
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.
...calling nsicancelable.cancel() on the re
turned object should close the dialog and must call nsiauthpromptcallback.onauthcancelled() on the provided callback.
...the implementation should fill in this object with the information entered by the user before re
turning.
...And 4 more matches
nsICategoryManager
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.
... re
turn value a simple enumerator, each result qis to nsisupportscstring.
...And 4 more matches
nsIClassInfo
no implementor of this interface should ever re
turn flags with this bit set.
...it has no meaning when re
turned from the flags attribute of a nsiclassinfo implementation.
... 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.
...And 4 more matches
nsICollection
count() re
turns the number of items in the collection.
...re
turn value number of items in the list.
... enumerate() re
turns an nsienumerator that lets you iterate over the items in the collection.
...And 4 more matches
nsIComponentManager
unlike getservice, this re
turns a new instance each time it is called.
... aiid the interface type to be re
turned.
... aiid the interface type to be re
turned.
...And 4 more matches
nsIContentPrefService
getpref() re
turns the value of a preference saved for a particular site.
... re
turn value the preference's value is re
turned; this value may be a string, integer, boolean, or any other value.
... re
turn value the result is an nsipropertybag2 containing the preferences and their values.
...And 4 more matches
nsIContentPrefService2
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.
... re
turn value the preference, or null if no such preference is known to exist.
...And 4 more matches
nsICryptoHash
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.
...And 4 more matches
nsIDispatchSupport
gethostingflags() re
turn the activex security and hosting flags.
...unsigned long gethostingflags( in string acontext ); parameters acontext re
turn value isclassmarkedsafeforscripting() test if the specified class is marked safe for scripting.
...classexists re
turns containing pr_false if the class is not registered.
...And 4 more matches
nsIDownloadManager
defaultdownloadsdirectory nsilocalfile re
turns the platform default downloads directory.
...obsolete since gecko 1.8 userdownloadsdirectory nsilocalfile re
turns the user configured downloads directory.
...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.
...And 4 more matches
nsIDroppedLinkHandler
re
turn value true if the link being dragged can be dropped.
...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.
...And 4 more matches
nsIExternalProtocolService
re
turn value true if we have a handler and false otherwise.
... re
turn value this code makes little sense and needs to be cleaned up.
...if neither the application nor the os knows about a handler for the protocol, the object this method re
turns will represent a default handler for unknown content.
...And 4 more matches
nsIHttpServer
an example : https://github.com/laurentj/slimerjs/blob/master/src/modules/webserver.jsm var exported_symbols = ["create"]; components.utils.import("resource://gre/modules/services.jsm"); function create() { var server = components.classes["@mozilla.org/server/jshttp;1"] .createinstance(components.interfaces.nsihttpserver); re
turn { get objectname () { re
turn "webserver"; }, /** * @param integer|string port port or "host:port" * @param object opt optional options.
... 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...
... file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(directorypath); re
turn server.registerdirectory(path, file); }, registerpathhandler: function(path, handlercallback) { server.registerpathhandler(path, function (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handlercallback(req, resp); }); }, registerprefixhandler: function(prefix, handlercallback) { server.registerprefixhandler(prefix, function (request, response) { var req = createhttprequest(request); ...
...And 4 more matches
nsIIDNService
dnservice); method overview autf8string convertacetoutf8(in acstring input); autf8string converttodisplayidn(in autf8string input, out boolean isascii); acstring convertutf8toace(in autf8string input); boolean isace(in acstring input); autf8string normalize(in autf8string input); methods convertacetoutf8() converts an ace (ascii compatible encoding) hostname into unicode format, re
turning a utf-8 format string.
... re
turn value the utf-8 encoded equivalent of the hostname.
...isascii on re
turn, this is set to true if the result is ascii or ace encoded; otherwise it's false.
...And 4 more matches
nsIInstallLocation
re
turn value the id for an item that might live at the location specified.
... re
turn value a file object at the requested location.
... re
turn value the location of the item.
...And 4 more matches
nsIMemory
ns_getmemorymanager re
turns the global nsimemory instance.
... 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.
...And 4 more matches
nsINavHistoryContainerResultNode
methods findnodebydetails() re
turns a node matching specified details.
... re
turn value an nsinavhistoryresultnode of a node matching the specified details or null if no match is found.
... getchild() re
turns the child node at the specified index.
...And 4 more matches
nsIPluginHost
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.
... (corresponds to npn_posturl and npn_posturlnotify.) re
turns the proxy info for a given url.
... 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.
...And 4 more matches
nsISelectionController
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.
... re
turn value true if visible, false if not.
...And 4 more matches
nsIServiceManager
nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result); void getservicebycontractid(in string acontractid, in 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.
... aiid the interface type to be re
turned.
...And 4 more matches
nsISocketTransport
securityinfo nsisupports security info object re
turned from the secure socket provider.
... methods native code only!getpeeraddr re
turns the ip address of the socket connection peer.
...re
turn value an prnetaddr containing the resolved ip address.
...And 4 more matches
nsIStringBundle
long aid, [array, size_is(length)] in wstring params, in unsigned long length); wstring formatstringfromname(in wstring aname, [array, size_is(length)] in wstring params, in unsigned long length); nsisimpleenumerator getsimpleenumeration(); wstring getstringfromid(in long aid); wstring getstringfromname(in wstring aname); methods formatstringfromid() re
turns a formatted string with the given id from the string bundle, where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
... 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.
...And 4 more matches
nsIURIFixup
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.
... re
turn value the converted, exposable uri, as an nsiuri.
...re
turns a well formed uri or nsnull if it cannot.
...And 4 more matches
Xray vision
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.
...for example, if content code creates a new date object, it will usually be created as a property of a dom object, and then it will be filtered out by the dom xray: // content code // redefine date.getfullyear() date.prototype.getfullyear = function() {re
turn 1000}; var date = new date(); // chrome code // contentwindow is an xray, and date is an expando on contentwindow // so date is filtered out gbrowser.contentwindow.date.getfullyear() // -> typeerror: gbrowser.contentwindow.date is undefined the chrome code will only even see date if it waives xrays, and then, because waiving is transitive, it should expect to be vulnerable to redefinition: //...
...And 4 more matches
StructType
syntax re
turns a ctype object describing a new structure data type.
... re
turn value a ctype object describing the newly created struct data type.
... ptr ctype re
turns a ctype representing the data type "pointer to this type".
...And 4 more matches
Version, UI, and Status Information - Plugins
this function re
turns a string that contains the user_agent field of 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.
...And 4 more matches
Accessibility Inspector - Firefox Developer Tools
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.
...for this reason, you should keep it
turned off when you aren't specifically using it.
...And 4 more matches
All keyboard shortcuts - Firefox Developer Tools
enter re
turn enter step forward through the attributes of a node tab tab tab step backward through the attributes 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 breadcrumbs bar these shortcuts work when the breadcrumbs bar is focused.
... the search box is focused, and content has been entered) esc esc esc step forward through properties and values tab tab tab step backward through properties and values shift + tab shift + tab shift + tab start editing property or value (rules view only, when a property or value is selected, but not already being edited) enter or space re
turn or space enter or space cycle up and down through auto-complete suggestions (rules view only, when a property or value is being edited) up arrow , down arrow up arrow , down arrow up arrow , down arrow choose current auto-complete suggestion (rules view only, when a property or value is being edited) enter or tab re
turn or tab enter or tab increment...
...And 4 more matches
Web Console Helpers - Firefox Developer Tools
$(selector, element) looks up a css selector string selector , re
turning the first node descended from element that matches.
... $$(selector, element) looks up a css selector string selector, re
turning an array of dom nodes descended from element that match.
...this is like for document.queryselectorall(), but re
turns an array instead of a nodelist.
...And 4 more matches
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.
...And 4 more matches
BaseAudioContext - Web APIs
0" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="231" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">baseaudiocontext</text></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.
... baseaudiocontext.destination read only re
turns an audiodestinationnode representing the final destination of all audio in the context.
...And 4 more matches
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.
... 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.
...And 4 more matches
Blob - Web APIs
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 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.
...And 4 more matches
Bluetooth - Web APIs
the bluetooth interface of the web bluetooth api re
turns a promise to a bluetoothdevice object with the specified options.
... bluetooth.referringdevice read only re
turns a reference to the device, if any, from which the user opened the current page.
... methods bluetooth.getavailability() re
turns a promise that resolved to a boolean indicating whether the user-agent has the ability to support bluetooth.
...And 4 more matches
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.
...And 4 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 4 more matches
Pixel manipulation with canvas - Web APIs
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).
...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...
...d = 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 object, you should use the createimagedata() method.
...And 4 more matches
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.
...And 4 more matches
Constraint validation API - Web APIs
aint validation api extends the interfaces for the form-associated elements listed below with a number of new properties and methods (elements that can have 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.
...And 4 more matches
DOMImplementation - Web APIs
such an object is re
turned by the document.implementation property.
... domimplementation.createdocument() creates and re
turns an xmldocument.
... domimplementation.createdocumenttype() creates and re
turns a documenttype.
...And 4 more matches
DOMLocator - Web APIs
re
turned by domerror.location.
... properties domlocator.linenumber read only re
turns a positive integer or -1.
... domlocator.columnnumber read only re
turns a positive integer or -1.
...And 4 more matches
Document.querySelector() - Web APIs
the document method queryselector() re
turns the first element within the document that matches the specified selector, or group of selectors.
... if no matches are found, null is re
turned.
... 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.
...And 4 more matches
EventTarget.addEventListener() - Web APIs
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.
... 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.
...And 4 more matches
FileSystemEntrySync - Web APIs
[ 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.
... re
turns filesystementrysync an object that represents an entry in the file system.
... re
turns filesystementrysync an object that represents an entry in the file system.
...And 4 more matches
GeolocationCoordinates - Web APIs
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.
...And 4 more matches
HTMLCollection - Web APIs
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.
...And 4 more matches
HTMLImageElement - Web APIs
65" width="160" height="50" fill="#f4f7f8" stroke="#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">htmlimageelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor image() the image() constructor creates and re
turns a new htmlimageelement object representing an html <img> element which is not attached to any dom tree.
... htmlimageelement.complete read only re
turns a boolean that is true if the browser has finished fetching the image, whether successful or not.
... htmlimageelement.currentsrc read only re
turns a usvstring representing the url from which the currently displayed image was loaded.
...And 4 more matches
Drag Operations - Web APIs
the drag data's types property re
turns a list of mime-type like domstrings, such as text/plain or image/jpeg.
...you can do this either by re
turning false from attribute-defined event listeners, or by calling the event's preventdefault() method.
... <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.
...And 4 more matches
Headers - Web APIs
headers.entries() re
turns an iterator allowing to go through all key/value pairs contained in this object.
... 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.
...And 4 more matches
IDBDatabaseSync - Web APIs
methods createobjectstore() creates and re
turns a new object store with the given name in the connected database.
... re
turns idbobjectstoresync an object to access the newly created object store.
... re
turns idbobjectstoresync an object to access the opened object store.
...And 4 more matches
Timing element visibility with the Intersection Observer API - Web APIs
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.
... styling the site with css with the structure of the site defined, we
turn to the styling for the site.
... refreshintervalid used to store the interval id re
turned by setinterval().
...And 4 more matches
KeyboardEvent.code - Web APIs
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.
... 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.
...And 4 more matches
KeyboardEvent.key - Web APIs
the keyboardevent interface's key read-only property re
turns the value of the key pressed by the user, taking into consideration the state of modifier keys such as shift as well as the keyboard locale and layout.
... if the pressed key has a printed representation, the re
turned value is a non-empty unicode character string containing the printable representation of the key.
... if the pressed key is a control or special character, the re
turned value is one of the pre-defined key values.
...And 4 more matches
MediaDevices.getDisplayMedia() - Web APIs
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.
...And 4 more matches
MediaKeyStatusMap - Web APIs
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.get() read only re
turns the value associated with the given key, or undefined if there is none.
...And 4 more matches
NodeList - Web APIs
nodelist objects are collections of nodes, usually re
turned by properties such as node.childnodes and methods such as document.queryselectorall().
...the ubiquitous document.queryselectorall() method re
turns a static nodelist.
... methods nodelist.item() re
turns an item in the list by its index, or null if the index is out-of-bounds.
...And 4 more matches
performance.now() - Web APIs
the performance.now() method re
turns a domhighrestimestamp, measured in milliseconds.
... the re
turned value represents the time elapsed since the time origin.
... 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.
...And 4 more matches
PerformanceResourceTiming - Web APIs
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.
...And 4 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
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 lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { re
turn createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { re
turn createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() constructor is deprecated.
... re
turn value a promise which is fulfilled once the value of the connection's remotedescription is successfully changed or rejected if the change cannot be applied (for example, if the specified description is incompatible with one or both of the peers on the connection).
...And 4 more matches
RTCPeerConnectionIceErrorEvent - Web APIs
constructor rtcpeerconnectioniceerrorevent() creates and re
turns a new rtcpeerconnectioniceerrorevent object, with its type and other properties initialized as specified in the parameters.
... 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.
...And 4 more matches
RTCRtpReceiver - Web APIs
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.
... 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.
...And 4 more matches
ReadableStream.ReadableStream() - Web APIs
the readablestream() constructor creates and re
turns a readable stream object from the given handlers.
...if this process is to be done asynchronously, it can re
turn a promise to signal success or failure.
...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.
...And 4 more matches
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.
...And 4 more matches
StylePropertyMapReadOnly - Web APIs
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.get() re
turns the value of the specified property.
...And 4 more matches
SubtleCrypto.sign() - Web APIs
it re
turns a promise which will be fulfilled with the signature.
... re
turn value signature is a promise that fulfills with an arraybuffer containing the signature.
... 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.
...And 4 more matches
VisualViewport - Web APIs
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.
...And 4 more matches
WebGL2RenderingContext.getSyncParameter() - Web APIs
the webgl2renderingcontext.getsyncparameter() method of the webgl 2 api re
turns parameter information of 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).
...And 4 more matches
WebRTC connectivity - Web APIs
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.
... 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.
... 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
pc.ontrack = ({track, streams}) => { track.onunmute = () => { if (remotevideo.srcobject) { re
turn; } remotevideo.srcobject = streams[0]; }; }; when the track event occurs, this handler executes.
... let ignoreoffer = false; signaler.onmessage = async ({ data: { description, candidate }}) => { try { if (description) { const offercollision = (description.type == "offer") && (makingoffer || pc.signalingstate != "stable"); ignoreoffer = !polite && offercollision; if (ignoreoffer) { re
turn; } await pc.setremotedescription(description); if (description.type =="offer") { await pc.setlocaldescription(); signaler.send(description: pc.localdescription) } } else if (candidate) { try { await pc.addicecandidate(candidate); } catch(err) { if (!ignoreoffer) { throw err; } } } } catch(err) {...
... 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.
...And 4 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
the following function re
turns a projection perspective matrix that integrates the specified field of view angle as well as the given near and far clipping plane distances: function createperspectivematrix(viewport, fovdegrees, nearclip, farclip) { const fovradians = fov * (math.pi / 180.0); const aspectratio = viewport.width / viewport.height; const transform = mat4.create(); mat4.perspective(transform, fovradians,...
... aspectratio, nearclip, farclip); re
turn transform; } after converting the fov angle, fovdegrees, from degrees to radians 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.
...And 4 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
all you really need to know is that it re
turns the time we are at right now.
...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.
... 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.
...And 4 more matches
Example and tutorial: Simple synth keyboard - Web APIs
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.
...285; notefreq[7]["e"] = 2637.020455302959437; notefreq[7]["f"] = 2793.825851464031075; notefreq[7]["f#"] = 2959.955381693075191; notefreq[7]["g"] = 3135.963487853994352; notefreq[7]["g#"] = 3322.437580639561108; notefreq[7]["a"] = 3520.000000000000000; notefreq[7]["a#"] = 3729.310092144719331; notefreq[7]["b"] = 3951.066410048992894; notefreq[8]["c"] = 4186.009044809578154; re
turn notefreq; } the result is an array, notefreq, with an object for each octave.
... if (!object.entries) { object.entries = function entries(o) { re
turn reduce(keys(o), (e, k) => concat(e, typeof k === 'string' && isenumerable(o, k) ?
...And 4 more matches
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.
...And 4 more matches
Window.openDialog() - Web APIs
the call to opendialog() re
turns immediately.
...these can be overridden (so "menubar=no,all"
turns on all chrome except the menubar.) this feature is explicitly ignored by window.open().
... default behavior the chrome and dialog features are always assumed on, unless explicitly
turned off ("chrome=no").
...And 4 more matches
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.caches read only re
turns the cachestorage object associated with the current context.
... 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.
...And 4 more matches
WritableStream - Web APIs
writablestream.getwriter() re
turns a new instance of writablestreamdefaultwriter and locks the stream to that instance.
...inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter.
...finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams.
...And 4 more matches
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.
...And 4 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.
... 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.
...And 4 more matches
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 reference space re
turned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace.
...And 4 more matches
@supports - CSS: Cascading Style Sheets
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.
...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.
...And 4 more matches
Adding captions and subtitles to HTML5 video - Developer guides
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.
... 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.
... 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.
...And 4 more matches
<input type="file"> - HTML: Hypertext Markup Language
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 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).
...t = 'no files currently selected for upload'; preview.appendchild(para); } else { const list = document.createelement('ol'); preview.appendchild(list); for(const file of curfiles) { const listitem = document.createelement('li'); const para = document.createelement('p'); if(validfiletype(file)) { para.textcontent = `file name ${file.name}, file size ${re
turnfilesize(file.size)}.`; const image = document.createelement('img'); image.src = url.createobjecturl(file); listitem.appendchild(image); listitem.appendchild(para); } else { para.textcontent = `file name ${file.name}: not a valid file type.
...And 4 more matches
JavaScript modules - JavaScript
re
turns an object containing the canvas's 2d context and the wrapper's id.
...re
turns the list's id.
...re
turns an object containing the square's size, position, and color.
...And 4 more matches
Inheritance and the prototype chain - JavaScript
// o.[[prototype]].[[prototype]].[[prototype]] is null, stop searching, // no property found, re
turn undefined.
... 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.
...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.
...And 4 more matches
Private class fields - JavaScript
syntax class classwithprivatefield { #privatefield } class classwithprivatemethod { #privatemethod() { re
turn 'hello world' } } class classwithprivatestaticfield { static #private_static_field } examples private static fields private fields are accessible on the class constructor from inside the class declaration itself.
... 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.
... 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 #.
...And 4 more matches
Classes - JavaScript
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.
... class point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; re
turn math.hypot(dx, dy); } } const p1 = new point(5, 5); const p2 = new point(10, 10); p1.distance; //undefined p2.distance; //undefined console.log(point.distance(p1, p2)); // 7.0710678118654755 binding this with prototype and static methods 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.
... class animal { speak() { re
turn this; } static eat() { re
turn this; } } let obj = new animal(); obj.speak(); // the animal object let speak = obj.speak; speak(); // undefined animal.eat() // class animal let eat = animal.eat; eat(); // undefined if we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls is automatically bound to the initial this value, which by default is the global object.
...And 4 more matches
The arguments object - JavaScript
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.
... 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.
... arguments[@@iterator] re
turns a new array iterator object that contains the values for each index in arguments.
...And 4 more matches
Array.prototype.reduceRight() - JavaScript
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.
... re
turn value the value that results from the reduction.
...if the array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the array is empty, the solo value would be re
turned without calling callback.
...And 4 more matches
Date.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string with a language sensitive representation of this date.
... in older implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation-dependent.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
...And 4 more matches
Math.ceil() - JavaScript
note: math.ceil(null) re
turns integer 0 and does not give a nan error.
... re
turn value the smallest integer greater than or equal to the given number.
... * @re
turns {number} the adjusted value.
...And 4 more matches
Math.floor() - JavaScript
the math.floor() function re
turns the largest integer less than or equal to a given number.
... re
turn value a number representing the largest integer less than or equal to the specified number.
... note: math.floor(null) re
turns 0, not a nan.
...And 4 more matches
Math.fround() - JavaScript
the math.fround() function re
turns the nearest 32-bit single precision float representation of a number.
... re
turn value the nearest 32-bit single precision float representation of the given number.
...if the number is outside the range of a 32-bit float, infinity or -infinity is re
turned.
...And 4 more matches
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.
... re
turn value the natural logarithm (base e) of the given number.
... if the number is negative, nan is re
turned.
...And 4 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.
... syntax math.random() re
turn value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
... 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.
...And 4 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.
... syntax math.random() re
turn value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
... 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.
...And 4 more matches
Number.prototype.toFixed() - JavaScript
re
turn value a string representing the given number using fixed-point notation.
... description tofixed() re
turns a string representation of numobj that does not use exponential notation and has exactly digits digits after the decimal place.
...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.
...And 4 more matches
Object.prototype.__lookupGetter__() - JavaScript
the __lookupgetter__ method re
turns the function bound as a getter to the specified property.
... syntax obj.__lookupgetter__(sprop) parameters sprop a string containing the name of the property whose getter should be re
turned.
... re
turn value the function bound as a getter to the specified property.
...And 4 more matches
Object.entries() - JavaScript
the object.entries() method re
turns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.
... the order of the array re
turned by object.entries() does not depend on how an object is defined.
... syntax object.entries(obj) parameters obj the object whose own enumerable string-keyed property [key, value] pairs are to be re
turned.
...And 4 more matches
Object.freeze() - JavaScript
freeze() re
turns the same object that was passed in.
... re
turn value the object that was passed to the function.
... freeze() re
turns the same object that was passed into the function.
...And 4 more matches
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.
... 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.
...And 4 more matches
Object.prototype.propertyIsEnumerable() - JavaScript
the propertyisenumerable() method re
turns a boolean indicating whether the specified property is enumerable and is the object's own property.
... re
turn value a boolean indicating whether the specified property is enumerable and is the object's own property.
...if the object does not have the specified property, this method re
turns false.
...And 4 more matches
Object.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the object.
... syntax object.tosource(); obj.tosource(); re
turn value a string representing the source code of the object.
... description the tosource() method re
turns the following values: for the built-in object object, tosource() re
turns the following string indicating that the source code is not available: function object() { [native code] } for instances of object, tosource() re
turns a string representing the source code.
...And 4 more matches
Object.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the object.
... syntax obj.tostring() re
turn value a string representing the object.
...if this method is not overridden in a custom object, tostring() re
turns "[object type]", where type is the object type.
...And 4 more matches
Promise.prototype.catch() - JavaScript
the catch() method re
turns a promise and deals with rejected cases only.
... 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.
...And 4 more matches
RegExp.prototype.test() - JavaScript
re
turns true or false.
... re
turns true if there is a match between the regular expression and the string str.
...test() re
turns a boolean, unlike the string.prototype.search() method (which re
turns the index of a match, or -1 if not found).
...And 4 more matches
String.prototype.localeCompare() - JavaScript
the localecompare() method re
turns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.
...in implementations which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation-dependent.
... re
turn value a negative number if referencestr occurs before comparestring; positive if the referencestr occurs after comparestring; 0 if they are equivalent.
...And 4 more matches
isNaN() - JavaScript
re
turn value true if the given value is nan; otherwise, false.
...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.
... a polyfill for isnan would be (the polyfill leverages the unique never-equal-to-itself characteristic of nan): var isnan = function(value) { var n = number(value); re
turn n !== n; }; examples isnan(nan); // true isnan(undefined); // true isnan({}); // true isnan(true); // false isnan(null); // false isnan(37); // false // strings isnan('37'); // false: "37" is converted to the number 37 which is not nan isnan('37.37'); // false: "37.37" is converted to the number 37.37 which is not nan isnan("37,5"); // true isnan('123ab...
...And 4 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.
... re
turn value a floating point number parsed from the given string.
... 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.
...And 4 more matches
Destructuring assignment - JavaScript
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.
... in this example, f() re
turns the values [1, 2] as its output, which can be parsed in a single line with destructuring.
...And 4 more matches
Equality (==) - JavaScript
the equality operator (==) checks whether its two operands are equal, re
turning a boolean result.
...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.
...And 4 more matches
Logical NOT (!) - JavaScript
when used with non-boolean values, it re
turns false if its single operand can be converted to true; otherwise, re
turns true.
... syntax !expr description re
turns false if its single operand can be converted to true; otherwise, re
turns true.
...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 4 more matches
instanceof - JavaScript
the re
turn value is a boolean value.
...for instance, [] instanceof window.frames[0].array will re
turn false, because array.prototype !== window.frames[0].array and arrays inherit from the former.
...components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and re
turns true if queryinterface succeeded.
...And 4 more matches
Expressions and operators - JavaScript
void the void operator discards an expression's re
turn value.
... arithmetic operators arithmetic operators take numerical values (either literals or variables) as their operands and re
turn a single numerical value.
... relational operators a comparison operator compares its operands and re
turns a boolean value based on whether the comparison is true.
...And 4 more matches
Template literals (Template strings) - JavaScript
for instance, if condition a is true, then re
turn this templated literal.
... 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.
...And 4 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
if a resource is cached and available offline, re
turn it first before trying to download it from the server.
...h; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); then we can manage the install event itself: self.addeventlistener('install', (e) => { console.log('[service worker] install'); e.waituntil( 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.
...it re
turns a promise — this approach is needed because installing may take some time, so we have to wait for it to finish.
...And 4 more matches
timers - Archive of obsolete content
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().
...And 3 more matches
/loader - Archive of obsolete content
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`.
... 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.
... let { loader } = require('toolkit/loader'); let manifest = { './main': { 'requirements': { 'panel': 'sdk/panel' } }, 'sdk/panel': { 'requirements': { 'chrome': 'chrome' } } 'chrome': { 'requirements': {} } }; let loader = loader({ resolve: function(id, requirer) { let requirements = manifest[requirer].requirements; if (id in manifest) re
turn requirements[id]; else throw error('module "' + requirer + '" has no authority to require ' + 'module "' + id + "') } }); thrown exceptions will propagate to the caller of require().
...And 3 more matches
places/history - Archive of obsolete content
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.
...an options object may be specified to determine overall settings, like sorting and how many objects should be re
turned.
... options : object optional options: name type count number the number of bookmark items to re
turn.
...And 3 more matches
preferences/service - Archive of obsolete content
re
turns string,number,boolean : preference value, re
turns defaultvalue if no preference is set, re
turns undefined if defaultvalue is not provided.
... re
turns boolean : re
turns whether or not the application preference name exists.
... re
turns array : re
turns an array of strings representing the child preferences of the root of this branch.
...And 3 more matches
Downloading Files - Archive of obsolete content
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.
... 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...
... instead of using qi like above, you can also implement nsiinterfacerequestor and re
turn nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests.
...And 3 more matches
HTML to DOM - Archive of obsolete content
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.
... the function below will safely parse simple html and re
turn a dom object which can be manipulated like web page elements.
...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>.
...And 3 more matches
Preferences - Archive of obsolete content
if there's a value of the correct type (for example, getboolvalue() expects a value of type nsiprefbranch.pref_bool), and the preference is not locked, the method re
turns that value.
... if there's a value of the expected type in the default tree, it is re
turned (with the only exception being that calling getcomplexvalue() with atype parameter specified as nsipreflocalizedstring, described above).
... another caveat you should be aware of is that nsiprefbranch.getchildlist("",{}) re
turns an array of preference names that start with that branch's root, for example var branch = prefs.getbranch("accessibility."); var children = branch.getchildlist("", {}); will re
turn these items (for the example tree above): "typeaheadfind.autostart", "typeaheadfind.enablesound", and "usebrailledisplay", not just direct children ("typeaheadfind" and "usebrailledisplay"), as you might have expec...
...And 3 more matches
Supporting search suggestions in search plugins - Archive of obsolete content
if you're a web site designer, and want to support search suggestions, you need to implement support for re
turning the suggestions in javascript object notation (json) given a search term.
... your server should then decide upon the suggestions to offer using whatever means it sees fit, and re
turn a json array of results: query string the first element in the array is the original query string.
...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.
...And 3 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
that new page may have links that take you to other pages, which may in
turn have more links, and so on.
...xmlhttprequest interface re
turns the dom for the document that was passed.
.../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.
...And 3 more matches
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...
...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.
...And 3 more matches
Nanojit - Archive of obsolete content
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.
... 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.
...And 3 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
le = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spacerequired + " k"); logcomment(" available: " + spaceavailable + " k"); re
turn(false); } re
turn(true); } in the verifydiskspace block, filegetdiskspaceavailable is called with dirpath as its expected input.
...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 ...
...if successful, this function re
turns a "0" and makes entries into theinstalled-chrome.txt file in the chrome subdirectory, which is then used to regenerate the various rdf files that make up the chrome registry.
...And 3 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) { re
turn null; }, // called when a rule matches this item.
...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 3 more matches
Template and Tree Listeners - Archive of obsolete content
or, the resource may no longer be part of the results, which is why we need to check the re
turn value of the getindexofresource method.
...in a content builder, it will re
turn the element with the datasources attribute, which in the template builder is referred to as the root element.
...all you need to do is add a tree builder observer which re
turns true for the candrop method.
...And 3 more matches
Styling a Tree - Archive of obsolete content
these re
turn information about an individual row, column and cell.
... 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.
...And 3 more matches
panel - Archive of obsolete content
re
turning false from this event handler prevents the popup from appearing.
...nsertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() re
turn type: no re
turn value closes the popup immediately.
... moveto( x, y ) re
turn type: no re
turn value moves the popup to a new location defined by screen coordinates (and not client coordinates).
...And 3 more matches
calICalendarView - Archive of obsolete content
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.
...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.
...And 3 more matches
Using the W3C DOM - Archive of obsolete content
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 implementation of getelementbyid(), which re
turns the first element with a matching name or id (id versus name when using getelementbyid, msdn: getelementbyid method).
... 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
HTML text fundamentals - Learn web development
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).
... lists now let's
turn our attention to lists.
...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 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> ...
...you don't have to understand all the code for now, but let's look at the part of the code that actually draws the 100 circles: 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(); } random(x), defined earlier in the code, re
turns a whole number between 0 and x-1.
...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).
...And 3 more matches
Handling text — strings in JavaScript - Learn web development
previous overview: first steps next next, we'll
turn our attention to strings — this is what pieces of text are called in programming.
... 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 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.
...And 3 more matches
Server-side web frameworks - Learn web development
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.
...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).
... # 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.
...And 3 more matches
Framework main features - Learn web development
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.
...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.
...And 3 more matches
Working with Svelte stores - Learn web development
the subscribe() method also re
turns a clean-up function, which takes care of releasing the subscription.
... the subscribe() method must re
turn an unsubscribe() function, which when called must stop its subscription.
...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 3 more matches
Setting up your own test automation environment - Learn web development
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.
... 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.
...And 3 more matches
Performance best practices for Firefox front-end engineers
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.
... 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.
...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.
...And 3 more matches
Overview of Mozilla embedding APIs
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_getglobalcomponentmanager this function re
turns an instance of the component manager service.
... webbrowser = do_createinstance(ns_webbrowser_contractid, &rv); if (ns_failed(rv)) re
turn rv; // give the webbrowser a pointer to the embedding component which // implements the callback interfaces.
...And 3 more matches
Embedding Tips
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.
...wait for persistence to complete before re
turning.
...that re
turned from nsiwebbrowserprint::getglobalprintsettings) that you wish to print the page with.
...And 3 more matches
IME handling guide
(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.
...are available if beginnativeinputtransaction() re
turn true.
...And 3 more matches
AddonManager
the callbacks will be called just once but that may be before or after the method re
turns.
... note: the extensions.enabledscopes preference lets you configure which of these scopes are enabled; however, you can't
turn off the profile scope.
... getstartupchanges() re
turns an array of add-on ids that changed for a given startup change type.
...And 3 more matches
DeferredTask.jsm
bool ispending(); re
turn value re
turns true if pending, false otherwise.
... 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.
...And 3 more matches
Refcount tracing and balancing
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.
... dosomethingwithfooandre
turnittoo() leaks two refcounts.
...And 3 more matches
NSPR Poll Method
the arguments and re
turn value of the poll method are described below.
... 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.
... re
turn value if the poll method stores a nonzero value in *out_flags, the re
turn value will be the value of in_flags.
...And 3 more matches
Nonblocking IO In NSPR
in nspr, a new socket re
turned by <tt>pr_newtcpsocket()</tt> or <tt>pr_newudpsocket()</tt> is always created in blocking mode.
...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.
...And 3 more matches
PR_LoadLibrary
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.
...And 3 more matches
PR_OpenSharedMemory
re
turns pointer to opaque structure prsharedmemory, or null if an error occurs.
...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.
...And 3 more matches
PR_Poll
if this time expires without any i/o becoming ready, pr_poll re
turns zero.
... re
turns the function re
turns one of these values: if successful, the function re
turns a positive number indicating the number of prpolldesc structures in pds that have events.
... description this function re
turns as soon as i/o is ready on one or more of the underlying socket objects.
...And 3 more matches
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.
...And 3 more matches
NSS Sample Code Sample_1_Hashing
* 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; } 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; } } if (column != level) { newline(ou...
...edesc *outfile, 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, digest, len); ...
...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, ...
... "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, p1)) { break; } pr_fprin...
...try again.\n"); } /* clear out the duplicate password string */ if (p1) { port_memset(p1, 0, port_strlen(p1)); port_free(p1); } fclose(input); fclose(output); re
turn p0; } /* change the password */ secstatus changepw(pk11slotinfo *slot, char *oldpass, char *newpass, char *oldpwfile, char *newpwfile) { secstatus rv; secupwdata pwdata; secupwdata newpwdata; char *oldpw = null; char *newpw = null; if (oldpass) { pwdata.source = pw_plaintext; pwdata.data = oldpass; } else if (oldpwfile) { pwdata.source = pw_fromfile; pwdata.data = oldpwfile; } else { pwdata.source = pw_none; pwdata.data = null; } if (newp...
...And 3 more matches
Hashing - sample 1
* re
turns null if the name if 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; } 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; } } if (column != level) { newlin...
.../ static int digestfile(prfiledesc *outfile, prfiledesc *infile, secoidtag hashoidtag) { unsigned int nb; unsigned char ibuf[4096]; unsigned char digest[64]; unsigned int len; 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, digest, len); ...
...And 3 more matches
sample1
* 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 h...
...ashtag; } /* 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; } ...
...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
FC_GetInfo
name fc_getinfo - re
turn general information about the pkcs #11 library.
... syntax ck_rv fc_getinfo(ck_info_ptr pinfo); parameters fc_getinfo has one parameter: pinfo points to a ck_info structure description fc_getinfo re
turns general information about the pkcs #11 library.
... on re
turn, the ck_info structure that pinfo points to has the following information: cryptokiversion: pkcs #11 interface version number implemented by the pkcs #11 library.
...And 3 more matches
JSPropertyOp
if a jspropertyop or jsstrictpropertyop does nothing and re
turns true, then property get, set, or add is unaffected.
... each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an exception and then re
turning false.
...otherwise the callback must re
turn true, and the property operation proceeds.
...And 3 more matches
JS_SetBranchCallback
specifies a callback function that is automatically called when a script branches backward during execution, when a function re
turns, and at the end of the script.
... 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.
...And 3 more matches
JS_malloc
on success, js_malloc re
turns a pointer to the beginning of the region.
...then it frees the region at p and re
turns a pointer to the new region.
...when p is not null, js_realloc(cx, p, 0) behaves like js_free(cx, p) and re
turns null.
...And 3 more matches
Using the Places annotation service
ary(auri, aname, adata, adatalen, amimetype); getitemannotationstring(aitemid, aname); getitemannotationint32(aitemid, aname); getitemannotationint64(aitemid, aname); getitemannotationdouble(aitemid, aname); getitemannotationbinary(aitemid, aname, adata, adatalen, amimetype); from javascript: getpageannotation(auri, aname); getitemannotation(aitemid, aname); these functions will re
turn/throw ns_error_not_available if the annotation requested does not exist.
... 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, aname); getitemannotationtype(aitemid, aname); the re
turned type will be one of the value_type constants in mozistoragevaluearray.idl: after bug 377066 the value_type_* type handling was changed to this: type_int32 = 1 type_double = 2 type_string = 3 type_binary = 4 type_int64 = 5 try { var value = annotationservice.getpageannotation(uri, "my_extension/some_annotation"); } catch(e) { // annotation does not exist } other functions getpageswithannotation(aname, resultcount, results); getitemswithannotation(aname, resultcount, results); ...
...And 3 more matches
extIPreferenceBranch
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.
... re
turn value the value of the preference or the given default value if preference does not exists.
...And 3 more matches
Components.lastResult
components.lastresult re
turns the 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.
...most interfaces only re
turn one success code -- ns_ok -- so components.lastresult is rarely necessary.
...And 3 more matches
Components.utils.exportFunction
if this is omitted, you need to assign the re
turn value of exportfunction() to an object in the target scope.
... re
turns the placeholder function which has been created in the target context.
...because structured cloning does not clone functions, this meant that the function may not re
turn a function, and by default, may not take any functions as arguments.
...And 3 more matches
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.
... -i this option
turns on the "interactive" mode -s this option toggles the javascript strict option on and off.
... -w (lower case) this option
turns on javascript warnings.
...And 3 more matches
mozIStorageRow
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: mozistoragevaluearray method overview nsivariant 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.
...And 3 more matches
nsIAccessibleRelation
method overview nsiaccessible gettarget(in unsigned long index); nsiarray gettargets(); attributes attribute type description relationtype unsigned long re
turns the type of the relation.
... targetscount unsigned long re
turns the number of targets for this relation.
... methods gettarget() re
turns accessible relation target at the given index.
...And 3 more matches
nsIAppShellService
attributes attribute type description applicationprovidedhiddenwindow boolean re
turn true if the application hidden window was provided by the application.
... hiddendomwindow nsidomwindow re
turn the (singleton) application hidden window, automatically created and maintained by this appshellservice.
... hiddenwindow nsixulwindow re
turn the (singleton) application hidden window, automatically created and maintained by this appshellservice.
...And 3 more matches
nsIAppStartup
re
turn value true if a window was opened.
... getstartupinfo() re
turns a javascript object with events from startup and the timestamps indicating when they occurred.
... re
turn value a javascript object with the following fields.
...And 3 more matches
nsIApplicationCache
gatherentries() re
turns a list of entries in the cache whose type matches one or more of the specified types.
...count on re
turn, indicates how many matching entries were found.
... getmatchingnamespace() re
turns the most specific namespace matching a given key.
...And 3 more matches
nsICacheSession
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).
...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.
...it re
turns a unique descriptor each time it is called, even if the same key is specified.
...And 3 more matches
nsIClipboard
re
turn value re
turns true, if data is present and it matches the specified flavor.
... otherwise it re
turns false.
... re
turn value re
turns true if kselectionclipboard is available.
...And 3 more matches
nsIDOMHTMLTimeRanges
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.
...And 3 more matches
nsIDOMStorage
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.
...And 3 more matches
nsIDOMStorage2
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.
...And 3 more matches
nsIDOMXPathResult
dom/interfaces/xpath/nsidomxpathresult.idlscriptable this interface describes an xpath result re
turned by nsidomxpathevaluator or document.evaluate inherits from: nsisupports last changed in gecko 1.7 method overview nsidomnode iteratenext(); nsidomnode snapshotitem(in unsigned long index); attributes attribute type description booleanvalue boolean if resulttype is boolean_type, the boolean value.
... constants type constants constant value description any_type 0 used when evaluating an xpath expression; the evaluator will re
turn the most appropriate type.
...re
turn value a dom node.
...And 3 more matches
nsIDOMXULElement
re
turns an nsicontrollers object that additional controllers may be appended to so as to provide focus-specific actions for commands.
...re
turns the template builder's database, if it is an rdf template.
...re
turns the nsirdfresource corresponding to the element's ref or id attribute, if any.
...And 3 more matches
nsIDictionary
re
turn value true if present, false if absent.
... void getkeys( out pruint32 count, [retval, array, size_is(count)] out string keys ); re
turn value array of all keys, unsorted.
... re
turn value the value associated with the specified key.
...And 3 more matches
nsIFileProtocolHandler
re
turn value a reference to a new nsifile object.
... re
turn value corresponding url string.
... re
turn value corresponding url string.
...And 3 more matches
nsIJSID
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the following methods re
turn objects that implement this interface: components.interfaces.name components.classes[contract] components.interfacesbyid[uuid] components.classesbyid[cid] the first two cases create a named jsid while the last two cases create an unnamed jsid.
...re
turns true if the jsid has been initialised.
... re
turn value true if the nsijsid's are valid and have the same nsid, otherwise false.
...And 3 more matches
nsIJumpListBuilder
a list of these items is re
turned by a call to initlistbuild().
... re
turn value true if the operation completed successfully.
...re
turn value true if the operation completed successfully.
...And 3 more matches
nsIMsgCustomColumnHandler
example implementation an example javascript implementation that does nothing: var columnhandler = { iseditable: function(arow, acol) {re
turn false;}, cyclecell: function(arow, acol) { }, getcelltext: function(arow, acol) { }, getsortstringforrow: function(ahdr) { re
turn ""; }, isstring: function() {re
turn true;}, getcellproperties: function(arow, acol, aprops) { }, getrowproperties: function(arow, aprops) { }, getimagesrc: function(arow, acol) {re
turn null;}, getsortlongforrow: functio...
...n(ahdr) {re
turn 0;} } to attach it use the nsimsgdbview.addcolumnhandler() method (recall gdbview is the global nsimsgdbview in thunderbird): gdbview.addcolumnhandler("newcolumn", columnhandler); after which it can be retrieved using the nsimsgdbview.getcolumnhandler() method: var handler = gdbview.getcolumnhandler("newcolumn"); and removed using the nsimsgdbview.removecolumnhandler() method: gdbview.removecolumnhandler("newcolumn"); method overview astring getsortstringforrow(in nsimsgdbhdr ahdr); unsigned long getsortlongforrow(in nsimsgdbhdr ahdr); boolean isstring(); methods getsortstringforrow() if the column displays a string, this will re
turn the string that the column should be sorted by.
... re
turn value the string value that sorting will be done with.
...And 3 more matches
nsINavHistoryQuery
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.
...otherwise, it will re
turn anything whose host name ends in domain.
... onlybookmarked boolean when set, re
turns only bookmarked items, when unset, re
turns anything.
...And 3 more matches
nsIParserUtils
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.
... re
turn value the plain text conversion of the html specified in src.
... re
turn value an nsidomdocumentfragment object for the resulting sanitized document fragment.
...And 3 more matches
nsISHistoryListener
the listener can prevent any action (except adding a new session history entry) from happening by re
turning false from the corresponding callback method.
... re
turn value true to allow the go back operation to proceed or false to cancel it.
... re
turn value true to allow the go forward operation to proceed or false to cancel it.
...And 3 more matches
nsIScriptableInputStream
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview unsigned long available(); void close(); void init(in nsiinputstream ainputstream); string read(in unsigned long acount); acstring readbytes(in unsigned long acount); methods available() re
turn the number of bytes currently available in the stream.
...re
turn value the number of bytes.
... warning: if the data contains a null byte, then this method will re
turn a truncated string.
...And 3 more matches
nsIScriptableUnicodeConverter
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.
...And 3 more matches
nsISupportsArray
lement); violates the xpcom interface guidelines boolean replaceelementat(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.
... 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 long aindex ); parameters aindex re
turn value enumeratebackwards() [notxpcom, noscript] boolean enumeratebackwards( in nsisupportsarrayenumfunc afunc, in voidptr adata ); parameters afunc adata re
turn value enumerateforwards() [notxpcom, noscript] boolean enumerateforwards( in nsisupportsarrayenumfunc afunc, in voidptr adata ); parameters afunc adata re
turn value violates the xpcom interface guidelines equals() boolean equals( [const] in nsisupportsarray other ); parameters other ...
...And 3 more matches
nsISupports proxies
if they match, it will re
turn the real non-proxied object.
...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.
...And 3 more matches
nsIWinTaskbar
er(); nsitaskbartabpreview createtaskbartabpreview(in nsidocshell shell, in nsitaskbarpreviewcontroller controller); nsitaskbarprogress gettaskbarprogress(in nsidocshell shell); nsitaskbarwindowpreview gettaskbarwindowpreview(in nsidocshell shell); void setgroupidforwindow(in nsidomwindow aparent, in astring aidentifier); attributes attribute type description available boolean re
turns true if the operating system supports windows 7 or later taskbar features; you can use this instead of in-place operating system version checking.
...re
turn value an nsijumplistbuilder.
... re
turn value an nsitaskbartabpreview object for the new tab preview.
...And 3 more matches
nsIXULTemplateBuilder
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.
...And 3 more matches
nsIZipReaderCache
.createinstance(components.interfaces.nsizipreadercache); method overview nsizipreader getinnerzip(in nsifile zipfile, in autf8string zipentry); nsizipreader getinnerzip(in nsifile zipfile, in string zipentry); 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.
... re
turn value the nsizipreader for the given zip file.
... getzip() re
turns a (possibly shared) cached nsizipreader for a zip file.
...And 3 more matches
Xptcall Porting Guide
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.
... // re
turn a refcounted pointer to the interfaceinfo for this object // note: on some platforms this must not fail or we crash!
... ns_imethod getinterfaceinfo(nsiinterfaceinfo** info) = 0; // call this method and re
turn result ns_imethod callmethod(pruint16 methodindex, const nsxptmethodinfo* info, nsxptcminivariant* params) = 0; }; code that wishes to make use of this stubs functionality (such as xpconnect) implement a class which inherits from nsxptcstubbase and implements the getinterfaceinfo and callmethod to let the platform specific code know how to get interface information and how to dispatch methods once their parameters have been pulled out of the platform specific calling frame.
...And 3 more matches
Creating a gloda message query
let mylistener = { /* called when new items are re
turned by the database query or freshly indexed */ onitemsadded: function mylistener_onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function mylistener_onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function mylistener...
... the max number of messages which are re
turned is governed by a preference: "mailnews.database.global.search.msg.limit" although you can deal with the messages as they show up via the listener, the list of messages in the collection is available in collection.items.
... foldermessage: re
turn the nsimsgdbhdr that corresponds to the message.
...And 3 more matches
Filelink Providers
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.
...the button to set up the account will only become enabled once the checkvalidity method for the form re
turns true.
...And 3 more matches
Mail and RDF
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.
...if asked about a folder along the #child arc, it will re
turn resources for all subfolders in that folder.
...And 3 more matches
Standard OS Libraries
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.
.../ 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 3 more matches
PointerType
syntax re
turns a new ctype object describing a new pointer data type.
... re
turn value a ctype object describing the newly created data type.
... ptr ctype re
turns a ctype representing the data type "pointer to this type".
...And 3 more matches
js-ctypes reference
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()).
... type constructors these are functions that define new types, and thus re
turn a ctype object.
... ctypes.functiontype(abi, re
turntype, argtype1 [, argtype2 ...]), which creates a new type describing a c function.
...And 3 more matches
Initialization and Destruction - Plugins
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.
...ownership of the buf field of the npsaveddata structure passes from the plug-in to the browser when npp_destroy re
turns.
...*/ 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.
...And 3 more matches
Debugger.Environment - Firefox Developer Tools
when true, getvariable re
turns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror.
... names() re
turn an array of strings giving the names of the identifiers bound by this environment.
... 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.
...And 3 more matches
Debugger.Source - Firefox Developer Tools
many properties below re
turn placeholder values.
...the text generation is disabled if the debugger has the allowwasmbinarysource property set, the "[wasm]" value will be re
turned in this case.
... (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.
...And 3 more matches
AudioBuffer - Web APIs
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.
...And 3 more matches
BlobBuilder - Web APIs
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.
... re
turn value a blob object containing all of the data passed to any calls to append() made since the blobbuilder was created.
...And 3 more matches
CSSStyleDeclaration - Web APIs
for example, document.stylesheets[0].cssrules[0].style re
turns a cssstyledeclaration object on the first css rule in the document's first stylesheet.
... methods cssstyledeclaration.getpropertypriority() re
turns the optional priority, "important".
... cssstyledeclaration.getpropertyvalue() re
turns the property value given a property name.
...And 3 more matches
CacheStorage.match() - Web APIs
this method re
turns a promise for a response, or a promise which resolves to undefined if no match is found.
...equivalent functionality is to call cache.match() on each cache (in the order re
turned by caches.keys()) until a response is re
turned.
... re
turn value a promise that resolves to the matching response.
...And 3 more matches
CredentialsContainer.get() - Web APIs
the get() method of the credentialscontainer interface re
turns a promise to a single credential instance that matches the provided parameters.
...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.
...And 3 more matches
DOMQuad - Web APIs
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.
... methods domquad.fromrect() re
turns a new domquad object based on the passed set of coordinates.
...And 3 more matches
DataTransferItem.webkitGetAsEntry() - Web APIs
if the item described by the datatransferitem is a file, webkitgetasentry() re
turns a filesystemfileentry or filesystemdirectoryentry representing it.
... if the item isn't a file, null is re
turned.
... re
turn value a filesystementry-based object describing the dropped item.
...And 3 more matches
Introduction to the DOM - Web APIs
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.
... 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.
...it refers to an element or a node of type element re
turned by a member of the dom api.
...And 3 more matches
Locating DOM elements using selectors - Web APIs
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.
...And 3 more matches
Element.closest() - Web APIs
will re
turn itself or the matching ancestor.
... if no such element exists, it re
turns null.
... ex: p:hover, .toto + q re
turn value closestelement is the element which is the closest ancestor of the selected element.
...And 3 more matches
Element.getAttribute() - Web APIs
the getattribute() method of the element interface re
turns the value of a specified attribute on the element.
... if the given attribute does not exist, the value re
turned will either be null or "" (the empty string); see non-existing attributes for details.
... 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.
...And 3 more matches
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.
...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.
...And 3 more matches
Event - Web APIs
ionevent paymentrequestupdateevent pointerevent popstateevent progressevent relatedevent rtcdatachannelevent rtcidentityerrorevent rtcidentityevent rtcpeerconnectioniceevent sensorevent storageevent svgevent svgzoomevent timeevent touchevent trackevent transitionevent uievent userproximityevent webglcontextevent wheelevent constructor event() creates an event object, re
turning it to the caller.
...setting its value to true before re
turning from an event handler prevents propagation of the event.
...(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.
...And 3 more matches
FetchEvent - Web APIs
used to notify the browser of tasks that extend beyond the re
turning of a response, such as streaming and caching.
...for get requests it tries to re
turn a match in the cache, and falls back to the network.
... if (event.request.method != 'get') re
turn; // prevent the default, and handle the request ourselves.
...And 3 more matches
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.
... 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.
...And 3 more matches
FormData - Web APIs
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.
...And 3 more matches
Using the Gamepad API - Web APIs
the index property also functions as the index into the array re
turned by navigator.getgamepads().
... 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.
... 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.
...And 3 more matches
HTMLCanvasElement - Web APIs
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.
...calling getcontext with "2d" re
turns a canvasrenderingcontext2d object, whereas calling it with "webgl" (or "experimental-webgl") re
turns a webglrenderingcontext object.
...And 3 more matches
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.
...And 3 more matches
HTMLTableElement - Web APIs
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.
... htmltableelement.tbodiesread only re
turns a live htmlcollection containing all the <tbody> of the element.
... htmltableelement.createthead() re
turns an htmlelement representing the first <thead> that is a child of the element.
...And 3 more matches
HTMLTableRowElement - Web APIs
htmltablerowelement.cells read only re
turns a live htmlcollection containing the cells in the row.
... 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.
...And 3 more matches
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.
...if there isn't, the callback can just re
turn immediately, or look for other work to do with the remaining time.
...And 3 more matches
KeyboardLayoutMap - Web APIs
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.
...And 3 more matches
LockedFile - Web APIs
re
turns a filerequest.
...re
turns a filerequest object.
...re
turns a filerequest object.
...And 3 more matches
MediaKeySession - Web APIs
properties mediakeysession.closed read only re
turns a promise signaling when a mediakeysession closes.
... 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.
...And 3 more matches
NavigationPreloadManager - Web APIs
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.
...And 3 more matches
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.
...for example, the property should re
turn false when users click links soon after they lose internet connection.
...And 3 more matches
NetworkInformation - Web APIs
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'.
...And 3 more matches
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.
...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.
...And 3 more matches
Node.textContent - Web APIs
syntax let text = somenode.textcontent someothernode.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.
... 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.
...And 3 more matches
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.
...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.
...And 3 more matches
ParentNode - Web APIs
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.
...And 3 more matches
Performance - Web APIs
performance.timeorigin read only re
turns the high resolution timestamp of the start time of the performance measurement.
... 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.
...And 3 more matches
PerformanceNavigationTiming - Web APIs
ono,monospace" fill="#4d4e53" text-anchor="middle" alignment-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".
...And 3 more matches
RTCPeerConnection.createOffer() - Web APIs
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.
...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.
...And 3 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.
... re
turn value a promise which resolves with an rtcstatsreport object providing connection statistics.
... 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.
...And 3 more matches
RTCPeerConnection.peerIdentity - Web APIs
the read-only rtcpeerconnection property peeridentity re
turns a javascript promise that resolves to an rtcidentityassertion which contains a domstring identifying the remote peer.
... 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.
...And 3 more matches
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.
... 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.
...And 3 more matches
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.
... 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.
...And 3 more matches
ReadableStream.pipeTo() - Web APIs
the pipeto() method of the readablestream interface 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.
...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.
...the method will re
turn a promise rejected with the source’s error, or with any error that occurs during aborting the destination.
...And 3 more matches
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
the readablestreamdefaultreader() constructor creates and re
turns a readablestreamdefaultreader object instance.
... re
turn value an instance of the readablestreamdefaultreader object.
...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 3 more matches
ReadableStreamDefaultReader.read() - Web APIs
the read() method of the readablestreamdefaultreader interface re
turns a promise providing access to the next chunk in the stream's internal queue.
... re
turn value a promise, which fulfills/rejects with a result depending on the state of the stream.
...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 3 more matches
SVGRectElement - Web APIs
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.
...And 3 more matches
Screen.lockOrientation() - Web APIs
a screen is considered in its primary portrait mode if the device is held in its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held
turned by 90° clockwise.
...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.
...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.
...And 3 more matches
ServiceWorkerContainer - Web APIs
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.
...it re
turns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an serviceworkerregistration.active worker.
...And 3 more matches
SharedWorkerGlobalScope - Web APIs
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.
...And 3 more matches
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).
... syntax var mytranscript = speechrecognitionalternativeinstance.transcript; re
turns a domstring.
... recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
SpeechRecognitionAlternative - Web APIs
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.
... recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
SpeechRecognitionEvent.results - Web APIs
the results read-only property of the speechrecognitionevent interface re
turns a speechrecognitionresultlist object representing all the speech recognition results for the current session.
... specifically this object will contain all final results that have been re
turned, followed by the current best hypothesis for all interim results.
... recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
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.
...And 3 more matches
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.
... recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
SpeechRecognitionResult - Web APIs
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.
... recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
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.
... recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
StaticRange - Web APIs
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.
... 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.
...And 3 more matches
StyleSheet - Web APIs
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.
...And 3 more matches
SubtleCrypto.decrypt() - Web APIs
it re
turns a promise which will be fulfilled with the decrypted data (also known as "plaintext").
... re
turn value result is a promise that fulfills with an arraybuffer containing the plaintext.
... function decryptmessage(privatekey, ciphertext) { re
turn window.crypto.subtle.decrypt( { name: "rsa-oaep" }, privatekey, ciphertext ); } aes-ctr this code decrypts ciphertext using aes in ctr mode.
...And 3 more matches
SubtleCrypto.encrypt() - Web APIs
it re
turns a promise which will be fulfilled with the encrypted data (also known as "ciphertext").
... re
turn value result is a promise that fulfills with an arraybuffer containing the "ciphertext".
... 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.
...And 3 more matches
SubtleCrypto.verify() - Web APIs
it re
turns a promise which will be fulfilled with a boolean value indicating whether the signature is valid.
... re
turn value result is a promise that fulfills with a boolean: true if the signature is valid, false otherwise.
...*/ 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.
...And 3 more matches
TrackDefault - Web APIs
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.
...And 3 more matches
UIEvent.layerX - Web APIs
the uievent.layerx read-only property re
turns the horizontal coordinate of the event relative to the current layer.
... this property takes scrolling of the page into account and re
turns a value relative to the whole of the document unless the event occurs inside a positioned element, where the re
turned value is relative to the top left of the positioned element.
...%; right:auto; width: 40%; border: solid blue 1px; padding: 20px; } #d3 { position: absolute; top: 240px; left: 20%; width: 50%; 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.
...And 3 more matches
UIEvent.layerY - Web APIs
the uievent.layery read-only property re
turns the vertical coordinate of the event relative to the current layer.
... this property takes scrolling of the page into account, and re
turns a value relative to the whole of the document, unless the event occurs inside a positioned element, where the re
turned value is relative to the top left of the positioned element.
...%; right:auto; width: 40%; border: solid blue 1px; padding: 20px; } #d3 { position: absolute; top: 240px; left: 20%; width: 50%; 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.
...And 3 more matches
USBAlternateInterface - Web APIs
properties usbalternateinterface.alternatesettingread only re
turns the alternate setting number of this interface.
... usbalternateinterface.interfaceclassread only re
turns the class of this interface.
... usbalternateinterface.interfacesubclassread only re
turns the subclass of this interface.
...And 3 more matches
Using the User Timing API - Web APIs
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("...
... 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("...
... 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("...
...And 3 more matches
User Timing API - Web APIs
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.
... 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.
...And 3 more matches
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.
...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.
...And 3 more matches
WebGL best practices - Web APIs
general topics address and eliminate webgl errors your application should run without generating any webgl errors (as re
turned by geterror).
... instead of: 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); 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.getshaderi...
...nfolog(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 info-log: ' + gl.getshaderinfolog(vs)); console.error('fs info-log: ' + gl.getshaderinfolog(fs)); } } khr_parallel_shader_compile for non-blocking compile/link status while we've described a pattern to allow browsers to compile and link in parallel, normally checking compile_status or link_status bloc...
...And 3 more matches
Window.prompt() - Web APIs
re
turn value a string containing the text entered by the user, or null.
...t(); // open the blank prompt window sign = prompt(); // open the blank 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.
...And 3 more matches
WritableStream.getWriter() - Web APIs
the getwriter() method of the writablestream interface re
turns a new instance of writablestreamdefaultwriter and locks the stream to that instance.
... re
turn value a writablestreamdefaultwriter object instance.
...inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter.
...And 3 more matches
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.
... 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.
...inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter.
...And 3 more matches
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.
...And 3 more matches
XRSession - Web APIs
environmentblendmode read only re
turns this session's blend mode which denotes how much of the real-world environment is visible through the xr device and how the device will blend the device imagery with it.
... inputsources read only re
turns a list of this session's xrinputsources, each representing an input device used to control the camera and/or scene.
... cancelanimationframe() removes a callback from the animation frame painting callback from xrsession's set of animation frame rendering callbacks, given the identifying handle re
turned by a previous call to requestanimationframe().
...And 3 more matches
XRWebGLLayer - Web APIs
constructor new xrwebgllayer() creates and re
turns a new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context.
... 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.
...And 3 more matches
ARIA: textbox role - Accessibility
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".
... 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.
...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.
...And 3 more matches
Keyboard-navigable JavaScript widgets - Accessibility
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 re
turns, the selected item within the group retains focus.
...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();".
...And 3 more matches
Using media queries - CSS: Cascading Style Sheets
note: a style sheet with a media query attached to its <link> tag will still download even if the query re
turns false.
... 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.
... not the not operator is used to negate a media query, re
turning true if the query would otherwise re
turn false.
...And 3 more matches
<angle> - CSS: Cascading Style Sheets
the <angle> css data type represents an angle value expressed in degrees, gradians, radians, or
turns.
...for example, 90deg equals -270deg, and 1
turn equals 4
turn.
...
turn represents an angle in a number of
turns.
...And 3 more matches
conic-gradient() - CSS: Cascading Style Sheets
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.
...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.
...And 3 more matches
Getting Started - Developer guides
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).
... <button id="ajaxbutton" type="button">make a request</button> <script> (function() { var httprequest; document.getelementbyid("ajaxbutton").addeventlistener('click', makerequest); function makerequest() { httprequest = new xmlhttprequest(); if (!httprequest) { alert('giving up :( cannot create an xmlhttp instance'); re
turn false; } httprequest.onreadystatechange = alertcontents; httprequest.open('get', 'test.html'); httprequest.send(); } function alertcontents() { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(httprequest.responsetext); } else { alert('there was a problem with the request.'); } } } })(); ...
... 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.
...And 3 more matches
Rich-Text Editing in Mozilla - Developer guides
the rich-text editing support in mozilla 1.3 supports the designmode feature which
turns html documents into rich-text editors.
...once designmode is
turned off however (as this now seems possible in mozilla 1.5) the events become active again.
... 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.
...And 3 more matches
Array.prototype.forEach() - JavaScript
re
turn value undefined.
...(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.
... early termination may be accomplished with: a simple for loop a for...of / for...in loops array.prototype.every() array.prototype.some() array.prototype.find() array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate re
turning a truthy value to determine if further iteration is required.
...And 3 more matches
Array.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string representing the elements of the array.
... re
turn value a string representing the elements of the array.
...if len is zero, re
turn the empty string.
...And 3 more matches
BigInt - JavaScript
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).
... instance methods bigint.prototype.tolocalestring() re
turns a string with a language-sensitive representation of this number.
... bigint.prototype.tostring() re
turns a string representing the specified object in the specified radix (base).
...And 3 more matches
Date.prototype.toLocaleDateString() - JavaScript
the tolocaledatestring() method re
turns a string with a language sensitive representation of the date portion of this date.
...in older implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
...And 3 more matches
Date.prototype.toLocaleTimeString() - JavaScript
the tolocaletimestring() method re
turns a string with a language sensitive representation of the time portion of this date.
...in older implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
...And 3 more matches
Intl.Collator.supportedLocalesOf() - JavaScript
the intl.collator.supportedlocalesof() method re
turns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.
... 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.
...And 3 more matches
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
the intl.datetimeformat.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.
... 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.
...And 3 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.
... 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.
...And 3 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.
... 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.
...And 3 more matches
Intl.NumberFormat.supportedLocalesOf() - JavaScript
the intl.numberformat.supportedlocalesof() method re
turns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.
... 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.
...And 3 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.
... 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.
...And 3 more matches
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
the intl.relativetimeformat.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.
... 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.
...And 3 more matches
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.
... re
turn value the base 2 logarithm of the given number.
... if the number is negative, nan is re
turned.
...And 3 more matches
Math.max() - JavaScript
the math.max() function re
turns the largest of the zero or more numbers given as input parameters.
... 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.
...And 3 more matches
Number.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string with a language-sensitive representation of this number.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
... re
turn value a string with a language-sensitive representation of the given number.
...And 3 more matches
Object.assign() - JavaScript
it re
turns the target object.
... 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.
... re
turn value the target object.
...And 3 more matches
Object.defineProperties() - JavaScript
the object.defineproperties() method defines new or modifies existing properties directly on an object, re
turning the object.
...the function's re
turn value will be used as the value of the property.
... re
turn value the object that was passed to the function.
...And 3 more matches
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.
...And 3 more matches
Object.prototype.hasOwnProperty() - JavaScript
the hasownproperty() method re
turns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
... re
turn value a boolean indicating whether or not the object has the specified property as own property.
... note hasownproperty re
turns true even if the value of the property is null or undefined.
...And 3 more matches
Object.setPrototypeOf() - JavaScript
re
turn value the specified object.
...* re
turns @object (if it was a primitive value it will transformed into an object).
...* re
turns the function.
...And 3 more matches
Object.prototype.valueOf() - JavaScript
the valueof() method re
turns the primitive value of the specified object.
... syntax object.valueof() re
turn value the primitive value of the specified object.
...every built-in core object overrides this method to re
turn an appropriate value.
...And 3 more matches
Promise() constructor - JavaScript
the executor has no meaningful re
turn value.
... 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.
...And 3 more matches
Reflect.defineProperty() - JavaScript
the static reflect.defineproperty() method is like object.defineproperty() but re
turns a boolean.
... re
turn value a boolean indicating whether or not the property was successfully defined.
... one key difference: object.defineproperty re
turns the object or throws a typeerror if the property has not been successfully defined.
...And 3 more matches
String.fromCodePoint() - JavaScript
the static string.fromcodepoint() method re
turns a string created by using the specified sequence of code points.
... re
turn value a string created by using the specified sequence of code points.
... description this method re
turns a string (and not a string object).
...And 3 more matches
String.prototype.lastIndexOf() - JavaScript
the lastindexof() method re
turns the index within the calling string object of the last occurrence of the specified value, searching backwards from fromindex.
... re
turns -1 if the value is not found.
...if searchvalue is an empty string, then fromindex is re
turned.
...And 3 more matches
WeakMap.prototype.get() - JavaScript
the get() method re
turns a specified element from a weakmap object.
...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.
...And 3 more matches
Comma operator (,) - JavaScript
the comma operator (,) evaluates each of its operands (from left to right) and re
turns the value of the last operand.
... one or more expressions, the last of which is re
turned as the value of the compound 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).
...And 3 more matches
Operator precedence - JavaScript
this is because the assignment operator re
turns the value that is assigned.
...then the a is also set to 5, the re
turn value of b = 5, aka right operand of the assignment.
... 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 t...
...And 3 more matches
function declaration - JavaScript
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.
...typeof foo is ${typeof foo}`); if (false) { function foo(){ re
turn 1; } } // in chrome: // 'foo' name is hoisted.
...And 3 more matches
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.
...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.
...And 3 more matches
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.
... node-set (optional) an expression pointing to a node-set in the external document that should be re
turned.
... re
turns a node-set.
...And 3 more matches
Interacting with page scripts - Archive of obsolete content
cloneinto() creates a structured clone of the object in the target context, and re
turns a reference to the clone.
...note that the function's closure will be exported, too: // content-script.js var salutation = "hello, "; function greetme(user) { re
turn salutation + user; } exportfunction(greetme, unsafewindow, {defineas: "greetme"}); finally, the "page.html" file adds a button and a page script that calls the exported function when the user pushes the button: <html> <head> </head> <body> <input id="test" type="button" value="click me"/> <script> var test = document.getelementbyid("test"); test.addeventlistener("cli...
...ck", function() { alert(window.greetme("page script")); }, false); </script> </body> </html> exportfunction() works by structured cloning the arguments and re
turn value of the function from one scope to the other.
...And 2 more matches
LookupNamespaceURI - Archive of obsolete content
this function is not necessary for gecko-based browsers (though the function will quickly re
turn the standard value for mozilla browsers) when used to reflect on static documents.
... addlookupnamespaceuri(doc); addlookupnamespaceuri(element); function addlookupnamespaceuri (type) { if (!type.prototype.lookupnamespaceuri) { type.prototype.lookupnamespaceuri = lookupnamespaceuri; } function lookupnamespaceuri (prefix) { re
turn lookupnamespaceurihelper(this, prefix); } function lookupnamespaceurihelper (node, prefix) { // adapted directly from http://www.w3.org/tr/dom-level-3-core/namespaces-algorithms.html#lookupnamespaceurialgo var i, att, htmlmode = document.contenttype, // mozilla only xmlnspattern = /^xmlns:(.*)$/; switch (node.nodetype) { case 1: // elem...
...ent_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; } re
turn null; // unknown } ...
...And 2 more matches
Rosetta - Archive of obsolete content
"); if (!odicts.hasownproperty(smimetype)) { alert("rosetta.translatescript() \u2013 unknown mime-type \"" + smimetype + "\": script ignored."); re
turn; } var ocompiled = document.createelement("script"); oscript.parentnode.insertbefore(obaton, oscript); oscript.parentnode.removechild(oscript); for (var aattrs = oscript.attributes, nattr = 0; nattr < aattrs.length; nattr++) { ocompiled.setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.sr...
...nction (vmimetypes, fcompiler) { if (arguments.length < 2) { throw new typeerror("rosetta.appendcompiler() \u2013 not enough arguments"); } 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).
...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 () { if (!window.rosetta) { re
turn; } /* this function takes as argument a plain text (in this case, a code written in c) and re
turns another plain text written in ecmascript */ function createecmasrc (scsrc) { /* this is just an empty example...
...And 2 more matches
Installing Extensions and Themes From Web Pages - Archive of obsolete content
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 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.
... 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.
...And 2 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
instance, when you want to modify the result of dom mutations that you know are the result of the doawesomedomstuff() function, you can wrap it as follows: { let originaldoawesomedomstuff = doawesomedomstuff; doawesomedomstuff = function _doawesomedomstuff() { let res = originaldoawesomedomstuff.apply(this, arguments); doawesomerdomstuff(res, arguments); re
turn res; }; } now, whenever doawesomedomstuff() is called, the original function will be called, followed by your own doawesomerdomstuff() function, which can then further modify the dom as needed.
... variations on this method include modifying the arguments passed to the wrapped function, modifying its re
turn value, and making changes both before and after the original method is called.
... * @optional @default document * * @re
turns {function} a function which may be called to unregister the * listener.
...And 2 more matches
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
openchannel re
turns to openuri which just opens the channel, setting the nsdocumentopeninfo as the stream listener.
...the basic idea is that dispatchcontent calls nsdocumentopeninfo::trycontentlistener on various content listeners; if that re
turns true, we have found the right listener and we are done.
...if any of those steps fails, the function re
turns false so that another content listener will be looked for.
...And 2 more matches
Style System Overview - Archive of obsolete content
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.
... 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.
...And 2 more matches
Clipboard - Archive of obsolete content
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.
...And 2 more matches
Clipboard - Archive of obsolete content
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.
...And 2 more matches
Clipboard - Archive of obsolete content
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.
...And 2 more matches
LIR - Archive of obsolete content
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.
... 5 allocp pointer allocate stack space (result is an address) 6 reti void re
turn an int 7 retq void 64 bit re
turn a quad 8 retd void re
turn a double 9 livei void extend live range of an int 10 liveq void 64 bit extend live range of a quad 11 lived void extend live range of a double 12 file void source filename for debug symbols 13 line void source line number for debug symbols 14 comment void a comment shown, on its own line, in lir dumps 15 ...
... store int truncated to char 26 sti2s void store int truncated to short 27 sti void store int 28 stq void 64 bit store quad 29 std void store double 30 std2f void store double as a float (losing precision) 31 not in use call 32 not in use 33 callv void call subroutine that re
turns void 34 calli integer call subroutine that re
turns an int 35 callq quad 64 bit call subroutine that re
turns a quad 36 calld double call subroutine that re
turns a double branch 37 j void jump always 38 jt void jump if true 39 jf void jump if false 40 jtbl void jump to address in table 41 label ...
...And 2 more matches
DOM Interfaces - Archive of obsolete content
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.
... re
turn value element - the re
turn value of getanonymouselementbyattribute is an anonymous descendant of the given element with matching attribute name and value.
... re
turn value element - the re
turn value of getbindingparent is the element responsible for the given anonymous node.
...And 2 more matches
modDateChanged - Archive of obsolete content
summary re
turns whether file has been modified since a certain 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.
...And 2 more matches
compareTo - Archive of obsolete content
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.
...And 2 more matches
cancelInstall - Archive of obsolete content
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.
...And 2 more matches
Building accessible custom components in XUL - Archive of obsolete content
var next = find_cell_left(current); if (next) { next.focus(); } } function spreadsheet_right(current) { var next = find_cell_right(current); if (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); var columns = current.parentnode.parentnode.childnodes; re
turn column = 0 ?
...And 2 more matches
Working With Directories - Archive of obsolete content
note that nsifile.append() modifies the file object, rather than re
turning a new one.
...this method re
turns true if a file object re
turned by nsiscriptableio.getfile() refers to a directory, and false otherwise.
...it re
turns an enumeration which can be iterated over.
...And 2 more matches
Getting File Information - Archive of obsolete content
it is convenient to pass the re
turned time to the date constructor.
...the following four methods re
turn true or false: nsifile.isreadable() - re
turns true if the file can be read from.
... nsifile.iswritable() - re
turns true if the file can be written to.
...And 2 more matches
findbar - Archive of obsolete content
aschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), 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.
... onfindagaincommand( findprevious ) re
turn type: no re
turn value call this method to handle your application's "find next" and "find previous" commands.
...And 2 more matches
Adding Properties to XBL-defined Elements - Archive of obsolete content
the script should re
turn the value that should be treated as the value of that property.
...<property name="size" onget="re
turn 77;" onset="alert('changed to:'+val);"/> this property will always re
turn 77 when retrieved.
...the script calculates the value and re
turns it.
...And 2 more matches
Manipulating Lists - Archive of obsolete content
the former re
turns the index of the selected item while the latter re
turns the selected element.
...if no item is selected, selectedindex will re
turn -1, while selecteditem will re
turn null.
...it also has a selectedindex function which will re
turn the index of the selected tab.
...And 2 more matches
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.
...And 2 more matches
preference - Archive of obsolete content
://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="re
turn myfunction(event);"/> </window> readonly type: boolean if set to true, then the user cannot change the value of the element.
... properties defaultvalue (readonly) re
turns the default value of the preference.
... if the preference has no default value, this property re
turns null.
...And 2 more matches
toolbox - 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.
...ace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), 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.
...the method re
turns the dom element for the created toolbar.
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
re
turn to mozilla-dev-extensions faq friday, september 22 - 29, 2006 (↑ top) how to write an xpcom component in c++ that can communicate to a com component?
... 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?
...if you
turn off the xul cache you don't even need to restart to see changes, simply open a new window.
...And 2 more matches
NPN_Invoke - Archive of obsolete content
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.
...And 2 more matches
NPN_InvokeDefault - Archive of obsolete content
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.
...And 2 more matches
NPN_PostURLNotify - Archive of obsolete content
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.
...And 2 more matches
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
if you haven't you can re
turn an error and the plugin will be ignored.
... */ err = callnpn_getvalueproc(gnetscapefuncs.getvalue, null, npnvsupportsxembedbool, (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 does...
...n't support xembed and doesn't use gtk2 as a toolkit we re
turn an error.
...And 2 more matches
Accessing XML children - Archive of obsolete content
in this case, accessing foo.bar will re
turn an xml list object, of all child elements of the type "bar".
...e4x behaves no differently when re
turning these properties.
...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.
...And 2 more matches
Namespaces - Archive of obsolete content
ml namespace = "http://www.w3.org/1999/xhtml"; var a = <p>some text</p>; default xml namespace = "http://www.mozilla.org/keymaster/gat...re.is.only.xul"; var b = <label>more text</label>; a.appendchild(b); gives <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).
...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.
...And 2 more matches
GetObject - Archive of obsolete content
the getobject function re
turns a reference to an automation object from a file.
...assign the object re
turned by getobject to the object variable.
...if pathname is a zero-length string (""), getobject re
turns a new object instance of the specified type.
...And 2 more matches
VBArray - Archive of obsolete content
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.
...And 2 more matches
New in JavaScript 1.3 - Archive of obsolete content
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).
...And 2 more matches
New in JavaScript 1.8.5 - Archive of obsolete content
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.
...And 2 more matches
Object.prototype.watch() - Archive of obsolete content
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).
...And 2 more matches
JSException - Archive of obsolete content
exception extends runtimeexception java.lang.object | +----java.lang.throwable | +----java.lang.exception | +----java.lang.runtimeexception | +----netscape.javascript.jsexception description jsexception is an exception which is thrown when javascript code re
turns an error.
... getwrappedexceptiontype instance method getwrappedexceptiontype re
turns the int mapping of the type of the wrappedexception object.
... declaration public object getwrappedexception() description getwrappedexception() re
turns an object that represents the value that the javascript actually threw.
...And 2 more matches
3D collision detection - Game development
f the aabb, we can calculate whether a collision has occurred between the two using the following formula: f(p,b)=(px>=bminx∧px<=bmaxx)∧(py>=bminy∧py<=bmaxy)∧(pz>=bminz∧pz<=bmaxz)f(p,b)= (p_x >= b_{minx} \wedge p_x <= b_{maxx}) \wedge (p_y >= b_{miny} \wedge p_y <= b_{maxy}) \wedge (p_z >= b_{minz} \wedge p_z <= b_{maxz}) or in javascript: function ispointinsideaabb(point, box) { re
turn (point.x >= box.minx && point.x <= box.maxx) && (point.y >= box.miny && point.y <= box.maxy) && (point.z >= box.minz && point.z <= box.maxz); } aabb vs.
... 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.
...)^2 + (p_y - s_y)^2 + (p_z - s_z)^2} or in javascript: function ispointinsidesphere(point, sphere) { // we are using multiplications because is faster than calling math.pow var distance = math.sqrt((point.x - sphere.x) * (point.x - sphere.x) + (point.y - sphere.y) * (point.y - sphere.y) + (point.z - sphere.z) * (point.z - sphere.z)); re
turn distance < sphere.radius; } the code above features a square root, which can be expensive to calculate.
...And 2 more matches
Plug-in Development Overview - Gecko Plugin API Reference
this exported c function should re
turn a string containing the type, extension list, and type description separated by colons.
... caution: gecko caches the values re
turned by these functions and will only call it if the plug-in's timestamp has changed.
...if nothing is found there, gecko checks for an np_getmimedescription entry point, and will use the information re
turned by this function.
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
deo</div> but as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>play video</button> not only do html <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — users can navigate between buttons using the tab key and activate their selection using re
turn or enter.
... 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.
... 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.
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
deo</div> but as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>play video</button> not only do html <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — users can navigate between buttons using the tab key and activate their selection using re
turn or enter.
... 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.
... 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.
...And 2 more matches
Introduction to events - Learn web development
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.
...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.
...And 2 more matches
Test your skills: Functions - Learn web development
this aim of this skill test is to assess whether you've understood our functions — reusable blocks of code, build your own function, and function re
turn values articles.
... 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.
...And 2 more matches
Manipulating documents - Learn web development
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.
...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.
... 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.
...And 2 more matches
Silly story generator - Learn web development
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.
...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.
... placing the event handler and incomplete function: now re
turn to the raw text file.
...And 2 more matches
Solve common problems in your JavaScript code - Learn web development
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.
...And 2 more matches
Inheritance in JavaScript - Learn web development
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()!
... 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.
...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.
...And 2 more matches
Object prototypes - Learn web development
for example: person1.valueof() valueof() re
turns the value of the object it is called on.
...you can check this by entering the following in the console: person2.__proto__ this will re
turn the person1 object.
... 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.
...And 2 more matches
Creating our first Vue component - Learn web development
so mutating props in a component would trigger the component to rerender, which may in-
turn trigger the mutation again.
...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 will re
turn an object containing a single property that we'll call isdone, whose value is this.done.
...And 2 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
add a data() method to our todoform component object that re
turns a label field.
... 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.
... export default { name: 'app', components: { todoitem, todoform }, data() { re
turn { todoitems: [ { id:uniqueid('todo-'), label: 'learn vue', done: false }, { id:uniqueid('todo-'), label: 'create a vue project with the cli', done: true }, { id:uniqueid('todo-'), label: 'have fun', done: true }, { id:uniqueid('todo-'), label: 'create a to-do list', done: false } ] }; }, methods: { addtodo() { console.log('to-do added'...
...And 2 more matches
Implementing feature detection - Learn web development
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.
...And 2 more matches
Mozilla’s UAAG evaluation report
(p1) vg alt for img: rendered when images
turned off.
...(p3) g alt for img: rendered when images
turned off title for *any* element: rendered as tooltip longdesc for img element: in context menu - properties content of object element: ?
... here are all the "hidden prefs" lines that can be added to the user's prefs.js file, for controlling popup behavior:
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.default.windowinternal.open", "noaccess"); override popping up new windows on target=anything: ...
...And 2 more matches
HTTP logging
at any point during while your browser is running, you can
turn logging on and off.
... copy and paste the following commands into the terminal window, hitting the re
turn key after each line.
...
turning off logging of socket-level transactions if you're not interested in socket-level log information, either because it's not relevant to your bug or because you're debugging something that includes a lot of noise that's hard to parse through, you can do that.
...And 2 more matches
Using the Browser API
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.
...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.
...And 2 more matches
Infallible memory allocation
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.
...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.
...And 2 more matches
FileUtils.jsm
re
turn value re
turns a nsifile object for the file specified.
... re
turn value re
turns a nsifile object for the location specified.
... modeflags optional file open flags (see constants above) re
turn value re
turns nsifileoutputstream (the non-safe variant) to write to.
...And 2 more matches
FxAccountsOAuthClient.jsm
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.
... constructor fxaccountsoauthclient() creates and re
turns a new fxaccountsoauthclient object.
... 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.
...And 2 more matches
Memory reporting
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.
... re
turn moz_collect_report( "explicit/mystring", kind_heap, units_bytes, gmystring->sizeofincludingthis(mallocsizeof), "memory used for mystring."); } }; ns_impl_isupports1(mystringreporter, nsimemoryreporter) note that moz_define_malloc_size_of defines a function of type mozilla::mallocsizeof that is specific to this memory reporter (and will be identified as such in dmd's output).
...} virtual size_t sizeofexcludingthis(nsmallocsizeoffun amallocsizeof) const { re
turn ...
...And 2 more matches
PR_AcceptRead
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.
...on re
turn, peeraddr points to the address of the remote socket.
...And 2 more matches
PR_ConnectContinue
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.
...And 2 more matches
PR EnumerateAddrInfo
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.
...And 2 more matches
PR_EnumerateHostEnt
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.
... 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.
...And 2 more matches
PR_PopIOLayer
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.
...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.
...And 2 more matches
PR_ReadDir
re
turns a pointer to the next entry in the directory.
... 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, pr_skip_hidden = 0x4 } prdirflags; the memory associated with the re
turned prdirentry structure is managed by nspr.
...And 2 more matches
PR_WaitSemaphore
re
turns the value of the environment variable.
... 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.
...And 2 more matches
PR_dtoa
if rve is not null, *rve is set to point to the end of the re
turned value.
...this gives a re
turn value similar to that of ecvt, except that trailing zeros are suppressed.
...this gives a re
turn value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative.
...And 2 more matches
PR_strtod
re
turns the result of the conversion is a prfloat64 value equivalent to the input string.
...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.
...And 2 more matches
NSS 3.12.5 release_notes
memory for the strings are owned by the caller, who is free to free them once nss_contextinit re
turns.
... 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.
...And 2 more matches
NSS 3.45 release notes
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.
...And 2 more matches
Notes on TLS - SSL 3.0 Intolerant Servers
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.
...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.
... 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.
...And 2 more matches
PKCS11 Implement
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.
...if a token has been removed during a session, c_getsessioninfo should re
turn either ckr_session_closed or ckr_session_handle_invalid.
...And 2 more matches
NSS tools : modutil
if any of these databases already exist in a specified directory, modutil re
turns an error message.
...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.
...nufacturer: mozilla foundation type: software version number: 3.11 firmware version: 0.0 status: enabled token name: nss certificate db token manufacturer: mozilla foundation token model: nss 3 token serial number: 0000000000000000 token version: 8.3 token firmware version: 0.0 access: not write protected login type: login required user pin: initialized a related command, -rawlist re
turns information about the database configuration for the modules.
...And 2 more matches
NSS tools : modutil
if any of these databases already exist in a specified directory, modutil re
turns an error message.
...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.
...n type: software version number: 3.11 firmware version: 0.0 status: enabled token name: nss certificate db token manufacturer: mozilla foundation token model: nss 3 token serial number: 0000000000000000 token version: 8.3 token firmware version: 0.0 access: not write protected login type: login required user pin: initialized a related command, -rawlist re
turns information about the database configuration for the modules.
...And 2 more matches
Tutorial: Embedding Rhino
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.
...the null parameter tells initstandardobjects to create and re
turn a scope object that we use in later calls.
...$ java runscript3 "function f(a) { re
turn a; }" x is not defined.
...And 2 more matches
Rhino shell
environment re
turns the current environment object.
...if multiple arguments are given, each file is read in and executed in
turn.
... 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.
...And 2 more matches
Exact Stack Rooting
bool hello(jscontext *cx, handleobject foo) { re
turn hello(cx, foo); } .....
... 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.
... 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.
...And 2 more matches
JS::AutoIdArray
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.
...And 2 more matches
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.
... description js::currentglobalornull() re
turns the global object for whatever function is currently running on the context.
...And 2 more matches
JS::PersistentRooted
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.
... persistentval.ref() = args.get(0); // or // *persistentval = args.get(0); // [spidermonkey 38] // persistentval = args.get(0); 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.
...And 2 more matches
JSNative
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.
...(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.
...And 2 more matches
JSObjectOps.lookupProperty
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.
...And 2 more matches
JS_CallFunction
on success, *rval receives the re
turn value from the function call.
...if js engine fails to get the function, it re
turns false.
... rval is a pointer to a variable that will hold the function's re
turn value, if any, on successful function execution.
...And 2 more matches
JS_EncodeCharacters
if utf-8 is
turned on, the length of the encoded string may vary.
...*/ 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.
...And 2 more matches
JS_EncodeString
if js_cstringsareutf8 is true, then the re
turned string of js_encodestring is utf-8, and the conversion is lossless.
... the array re
turned by js_encodestring on success is allocated as though by a call to js_malloc.
... 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.
...And 2 more matches
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.
... c jscompartment * the compartment for which to re
turn the global object.
...And 2 more matches
JS_GetGlobalForScopeChain
this article covers features introduced in spidermonkey 1.8.5 re
turns the global object for the active function on the context.
... syntax jsobject * js_getglobalforscopechain(jscontext *cx); name type description cx jscontext * the context for which to re
turn the global object.
... description js_getglobalforscopechain() re
turns the global object for whatever function is currently running on the context.
...And 2 more matches
JS_GetProperty
in the simplest case, js_getproperty stores the value of the property in *vp and re
turns true.
...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.
...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.
...And 2 more matches
JS_GetStringBytes
if js_cstringsareutf8 is true, then the re
turned string is utf-8, and the conversion is lossless.
...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.
...And 2 more matches
JS_PropertyStub
it behaves exactly like a property callback that accepts the default property behavior: it does nothing and re
turns true.
...it behaves exactly like a property callback that accepts the default property behavior: it does nothing and re
turns true.
...it behaves exactly like a property callback that accepts the default property behavior: it does nothing and re
turns true.
...And 2 more matches
JS_SetContextCallback
for future compatibility the callback must do nothing and re
turn true if any other value is passed.
...if the callback re
turns js_false, the instance will be destroyed and js_newcontext re
turns null.
...the callback may perform its own cleanup and must always re
turn true.
...And 2 more matches
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.
...And 2 more matches
extISessionStorage
re
turn type method boolean has(in astring aname) void set(in astring aname, in nsivariant avalue) 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 st...
... 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.
... 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.
...And 2 more matches
Accessing the Windows Registry Using XPCOM
both methods take a relative path and access mode as parameters and re
turn a new object implementing nsiwindowsregkey.
...this method re
turns an integer indicating the data type of the value.
... 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.
...And 2 more matches
Aggregating the In-Memory Datasource
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!
...aresult) re
turn ns_error_null_pointer; if (aiid.equals(nscomtypeinfo<nsimyinterface>::getiid()) || aiid.equals(nscomtypeinfo<nsisupports>::getiid())) { *aresult = ns_static_cast(nsiglobalhistory*, this); } else if (aiid.equals(nscomtypeinfo<nsirdfdatasource>::getiid())) { re
turn minner->queryinterface(aiid, aresult); } else { *aresult = nsnull; re
turn ns_nointerface; } ns_ad...
...dref(ns_static_cast(nsisupports*, aresult)); re
turn ns_ok; } the only other thing that you'll need to be aware of is that you'll need to queryinterface() from nsisupports to nsirdfdatasource before you can actually do anything useful with the datasource from within your object.
...And 2 more matches
Components.utils.evalInWindow
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.
... 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.
...And 2 more matches
Language bindings
s value will.components.idcomponents.id is a constructor that creates native objects that conform to the nsijsid interface.components.interfacescomponents.interfaces is a read-only object whose properties are interfaces indexed by their names.components.interfacesbyidcomponents.interfacesbyid is a read-only array of classes indexed by iid.components.issuccesscodedetermines 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.components.lastresultcomponents.managercomponents.manager is a convenience reflection of the global 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.
...it re
turns a reference to the clone:components.utils.createobjectincomponents.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.components.utils.evalinsandboxthe evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.components.utils.evalinwindowthis function enables code runni...
...And 2 more matches
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.
...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.
...And 2 more matches
amIInstallTrigger
re
turn value install() starts a new installation of a set of add-ons.
... re
turn value true if the installations were successfully started.
... re
turn value true if the installation was successfully started.
...And 2 more matches
imgIRequest
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.
...And 2 more matches
nsIAbCard
re
turn value the value of the attribute asked for.
... 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.
...And 2 more matches
nsIAutoCompleteInput
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.
...And 2 more matches
nsICacheEntryDescriptor
re
turn value re
turns the string value containing the meta data for the provided key.
...the re
turned stream may implement nsiseekablestream.
... re
turn value re
turns blocking, unbuffered input stream.
...And 2 more matches
nsICacheService
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.
... re
turn value re
turns a new cache session.
...And 2 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() ...
...re
turn value missing description exceptions thrown missing exception missing description getcharptrproperty() string getcharptrproperty( in string propertyname ); parameters propertyname missing description re
turn value missing description exceptions thrown missing exception missing description native code only!getlocale obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 ...
...And 2 more matches
nsIDNSRecord
since a dns query may re
turn more than one resolved ip address, the record acts like an enumerator, allowing the caller to easily step through the list of ip addresses.
... 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.
...And 2 more matches
nsIDNSService
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().
... re
turn value an object that can be used to cancel the host lookup.
...And 2 more matches
nsIDOMEvent
when not available, a value of 0 will be re
turned.
... back 0x20000000 text 0x40000000 alt_mask 0x00000001 control_mask 0x00000002 shift_mask 0x00000004 meta_mask 0x00000008 methods violates 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.
... re
turn value getpreventdefault() note: use the defaultprevented attribute instead.
...And 2 more matches
nsIDOMOfflineResourceList
mozhasitem re
turns a boolean value indicating whether or not the specified uri represents a resource that's in the application cache's list.
... 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.
...And 2 more matches
nsIDOMStorageManager
getlocalstorageforprincipal() re
turns the instance of the localstorage object for auri's origin.
...nsidomstorage getlocalstorageforprincipal( nsiprincipal aprincipal, domstring adocumenturi ); parameters aprincipal the principal for which to re
turn the local storage object.
... re
turn value the local storage object for the specified principal.
...And 2 more matches
nsIFeedTextConstruct
various other feed-related interfaces, such as nsifeed, nsifeedentry, and nsifeedcontainer have attributes that re
turn objects implementing nsifeedtextconstruct.
... 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.
...And 2 more matches
nsIFilePicker
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.
... re
turn value one of the re
turn constants.
...And 2 more matches
nsIHttpChannelInternal
void getrequestversion(out unsigned long major, out unsigned long minor); void getresponseversion(out unsigned long major, out unsigned long minor); void httpupgrade(in acstring aprotocolname, in nsihttpupgradelistener alistener); void setcookie(in string acookieheader); void setupfallbackchannel(in string afallbackkey); attributes attribute type description canceled boolean re
turns true if and only if the channel has been canceled.
...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.
...And 2 more matches
nsIMemoryReporterManager
this reporter is special-cased because it is interesting, is available on all platforms, and re
turns a meaningful result on all common platforms.
... methods enumeratemultireporters() re
turns an enumerator for looking at the installed memory multi-reporters.
...re
turn value an enumerator of nsimemorymultireporters that are currently registered.
...And 2 more matches
nsIPrintingPrompt
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.
... for the print dialog: you may stub out this service by having all the methods re
turn ns_error_not_implemented.
...And 2 more matches
nsIProcess
tional] in boolean holdweak); void runw(in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count); void runwasync([array, size_is(count)] in wstring args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); attributes attribute type description exitvalue long the value re
turned by the process upon exit.
... 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.
...And 2 more matches
nsIPushService
.getservice(ci.nsiscriptsecuritymanager); const pushservice = cc["@mozilla.org/push/service;1"] .getservice(ci.nsipushservice); pushservice.subscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error creating subscription: " + code); re
turn; } // `subscription` implements `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.
... 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.
...And 2 more matches
nsISHistory
when the document finishes loading the value -1 is re
turned.
...the enumerator object thus re
turned by this method can be traversed using nsisimpleenumerator.
... use nsisimpleenumerator.getnext() on the object re
turned by step #1 to obtain handle to the next object in the list.
...And 2 more matches
nsIScreenManager
methods native code only!screenfornativewidget re
turns the nsiscreen instance for the native widget pointer.
... re
turn value the nsiscreen instance for the native widget pointer.
... screenforrect() re
turns the nsiscreen containing the specified rectangle.
...And 2 more matches
nsIStreamConverter
you can supply the service with a stream of type x and it will convert it to your desired output type and re
turn a converted (blocking) stream to you.
...it will then convert that data from type x to your desired output type and re
turn converted data to you via the nsistreamlistener you passed in by calling its nsistreamlistener.ondataavailable() method.
... atotype the mime type of the re
turned stream.
...And 2 more matches
nsITaggingService
re
turn value re
turns array of uris tagged with atag.
...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.
...And 2 more matches
nsITelemetry
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.
... 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.
... re
turn value the re
turned jsval object has the following functions: add(key, [optional] value) - adds an integer value to the appropriate bucket.
...And 2 more matches
nsIThread
when this function re
turns, the thread will be shut down and will no longer be available to receive events.
... 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.
...And 2 more matches
nsITreeBoxObject
selectionregion nsiscriptableregion readonly: re
turn the region for the visible parts of the selection, in device pixels.
...re
turns -1 for invalid mouse coordinates.
...re
turns -1 for invalid mouse coordinates.
...And 2 more matches
nsIUTF8ConverterService
if not, convert to utf-8 assuming it's encoded in acharset and re
turn the converted string in utf-8.
... re
turn value the converted string in utf-8.
...if not, convert it to utf-8, assuming it's encoded in acharset, and re
turn the result.
...And 2 more matches
nsIUTF8StringEnumerator
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.
...must be preceded by a call to hasmore(), which re
turns pr_true.
...re
turn value the next string in the enumerator.
...And 2 more matches
nsIXSLTProcessor
re
turns null otherwise.
... re
turn value an nsivariant containing the value of the parameter.
... re
turn value an document containing the result of the transformation.
...And 2 more matches
nsIZipWriter
getentry() re
turns a specified entry or null if there is no such entry in the current zip file.
... re
turn value an nsizipentry object describing the specified entry, or null if there is no such entry.
... re
turn value true if there is an entry with the given path in the zip file, otherwise re
turns false.
...And 2 more matches
NS_CStringGetMutableData
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).
...And 2 more matches
Setting HTTP request headers
var httprequestobserver = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); httpchannel.setrequestheader("x-hello", "world", false); } }, get observerservice() { re
turn cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); }, register: function() { this.observerservice.addobserver(this, "http-on-modify-request", false); }, unregister: function() { this.observerservice.removeobserver(this, "http-on-modify-request"); } }; this object has a convenience register() and unregister() methods, so in order...
... 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:...
... 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, this.myprogid, filespec, location, type); log("----------------------------> regist...
...And 2 more matches
already_AddRefed
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).
...already_addrefed<nsifoo> getfoo() { nsifoo* foo = mfoo; ns_if_addref(foo); re
turn foo; } // or already_addrefed<nsifoo> getfoo() { nscomptr<nsifoo> foo = mfoo; // ...
...And 2 more matches
MailNews fakeserver
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.
...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.
...the server provides the following api to xpcshell tests: <caption> nsmailserver xpcshell api </caption> name arguments re
turns description performtest none nothing runs until the test is forcibly aborted or stopped normally isstopped none if the server is stopped helper for performtest istestfinished none if the test is finished helper for performtest playtransaction none the transaction the transaction is an object with two properties: us, and them; us is an array of responses we sent, them an array of commands...
...And 2 more matches
Adding items to the Folder Pane
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.
...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...
...And 2 more matches
Folders and message lists
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.
... gfolderdisplay.selectedmessages: re
turns an array of nsimsgdbhdrs for the selected messages.
...And 2 more matches
Library
method overview close(); cdata declare(name, [abi, ], re
turntype[, argtype1, ...]); methods close() closes the library.
... cdata declare( name[, abi, re
turntype argtype1, ...] ); parameters name the 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.
... re
turntype the ctype type re
turned by the defined api, if it's a function.
...And 2 more matches
Memory - Plugins
this function re
turns a pointer to the allocated memory or null if not enough memory is available.
...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.
...And 2 more matches
Plug-in Development Overview - Plugins
this exported c function should re
turn a string containing the type, extension list, and type description separated by colons.
... caution: gecko caches the values re
turned by these functions and will only call it if the plug-in's timestamp has changed.
...if nothing is found there, gecko checks for an np_getmimedescription entry point, and will use the information re
turned by this function.
...And 2 more matches
URLs - Plugins
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.
...it re
turns immediately and only later handles the request and calls npp_urlnotify.
...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.
...And 2 more matches
Debugger.Memory - Firefox Developer Tools
given a debugger.object instancedobj referring to some object, dobj.allocationsite re
turns a saved call stack indicating wheredobj’s referent was allocated.
... 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.
...And 2 more matches
Page inspector keyboard shortcuts - Firefox Developer Tools
enter re
turn enter step forward through the attributes of a node tab tab tab step backward through the attributes 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 breadcrumbs bar these shortcuts work when the breadcrumbs bar is focused.
... the search box is focused, and content has been entered) esc esc esc step forward through properties and values tab tab tab step backward through properties and values shift + tab shift + tab shift + tab start editing property or value (rules view only, when a property or value is selected, but not already being edited) enter or space re
turn or space enter or space cycle up and down through auto-complete suggestions (rules view only, when a property or value is being edited) up arrow , down arrow up arrow , down arrow up arrow , down arrow choose current auto-complete suggestion (rules view only, when a property or value is being edited) enter or tab re
turn or tab enter or tab increment...
...And 2 more matches
Animation - Web APIs
animation.finished read only re
turns the current finished promise for this animation.
... animation.playstate read only re
turns an enumerated value describing the playback state of an animation.
... animation.ready read only re
turns the current ready promise for this animation.
...And 2 more matches
Background Tasks API - Web APIs
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.
... 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.
...we'll be using that to compute the value re
turned by our shim for timeremaining().
...And 2 more matches
BluetoothAdvertisingData - Web APIs
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.
... bluetoothadvertisingdata.rssi read only re
turns the power at which the device’s packets are being received, measured in dbm.
...And 2 more matches
BluetoothRemoteGATTDescriptor - Web APIs
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.
...And 2 more matches
Body - Web APIs
it re
turns a promise that resolves with an arraybuffer.
...it re
turns a promise that resolves with a blob.
...it re
turns a promise that resolves with a formdata object.
...And 2 more matches
Cache.keys() - Web APIs
the keys() method of the cache interface re
turns a promise that resolves to an array of cache keys.
... the requests are re
turned in the same order that they were inserted.
... note: requests with duplicate urls but different headers can be re
turned if their responses have the vary header set on them.
...And 2 more matches
Cache.match() - Web APIs
the match() method of the cache interface re
turns a promise that resolves to the response associated with the first matching request in the cache object.
... re
turn value a promise that resolves to the first response that matches the request or to undefined if no match is found.
...inside the catch() clause, match() is used to re
turn the correct response.
...And 2 more matches
Cache.put() - Web APIs
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.
... re
turn value a promise that resolves with undefined.
... 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().
...And 2 more matches
CanvasRenderingContext2D - Web APIs
canvasrenderingcontext2d.measuretext() re
turns a textmetrics object.
... canvasrenderingcontext2d.getlinedash() re
turns the current line dash pattern array containing an even number of non-negative numbers.
...this method re
turns a canvaspattern.
...And 2 more matches
Compositing example - Web APIs
; main program when the page loads, this code runs to set up and run the example: window.onload = function() { // lum in srgb var lum = { r: 0.33, g: 0.33, b: 0.33 }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightmix() colorsphere(); runcomposite(); re
turn; }; and this code, runcomposite(), handles the bulk of the work, relying on a number of utility functions to do the hard parts.
... 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; re
turn canvas; } function runcomposite() { var dl = document.createelement("dl"); document.body.appendchild(dl); while(gco.length) { var pop = gco.pop(); var dt = document.createelement("dt"); dt.textcontent = pop; dl.appendchild(dt); var dd = document.createelement("dd"); var p = document.createelement("p"); p.textcontent = gcotext.pop(); dd.appendchild(p); var canvastodrawon = createcanvas(); var canvastodrawfrom = createcanvas(); ...
...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
Clipboard - Web APIs
all of the clipboard api methods operate asynchronously; they re
turn a promise which is resolved once the clipboard access has been completed.
... read() requests arbitrary data (such as images) from the clipboard, re
turning a promise.
... 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.
...And 2 more matches
ClipboardItem - Web APIs
types read only re
turns an array of mime types available within the clipboarditem.
... 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.
...And 2 more matches
CustomEvent - Web APIs
setting its value to true before re
turning from an event handler prevents propagation of the event.
...(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.
...And 2 more matches
DedicatedWorkerGlobalScope - Web APIs
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.
...And 2 more matches
Document.getElementById() - Web APIs
the document method getelementbyid() re
turns an element object representing the element whose id property matches the specified string.
... 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.
...st1">hello word2</p> <p>hello word3</p> <p>hello word4</p> </div> <script> 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.
...And 2 more matches
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.
... 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.
...there, getelementsbyname() also re
turns elements that have an id attribute with the specified value.
...And 2 more matches
Document.getElementsByTagNameNS() - Web APIs
re
turns a list of elements with the given tag name belonging to the given namespace.
... 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.
...And 2 more matches
Document.querySelectorAll() - Web APIs
the document method queryselectorall() re
turns a static (not live) nodelist representing a list of the document's elements that match the specified group of selectors.
... 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.
...And 2 more matches
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.
...And 2 more matches
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.
... 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.
...And 2 more matches
EXT_disjoint_timer_query.getQueryObjectEXT() - Web APIs
the ext_disjoint_timer_query.getqueryobjectext() method of the webgl api re
turns the state of a query object.
... syntax any ext.getqueryobjectext(query, pname); parameters query a webglquery object from which to re
turn information.
... pname a glenum specifying which information to re
turn.
...And 2 more matches
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.
... 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.
...And 2 more matches
Element.localName - Web APIs
the element.localname read-only property re
turns the local part of the qualified name of an element.
... syntax name = element.localname re
turn value a domstring representing the local part of the element's qualified name.
...for example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix: <ecomm:business id="soda_shop" type="brick_n_mortar" xmlns: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).
...And 2 more matches
Element.querySelectorAll() - Web APIs
the element method queryselectorall() re
turns a static (not live) nodelist representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.
... 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.
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
re
turn value undefined.
... 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.
...And 2 more matches
Using the Geolocation API - Web APIs
a third, optional, parameter is an options object where you can set the maximum age of the position re
turned, the time to wait for a request, and if you want high accuracy for the position.
...devices with a gps, for example, can take a minute or more to get a gps fix, so less accurate data (ip location or wifi) may be re
turned to getcurrentposition().
... 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.
...And 2 more matches
HTMLCanvasElement.toDataURL() - Web APIs
the htmlcanvaselement.todataurl() method re
turns a data uri containing a representation of the image in the format specified by the type parameter (defaults to png).
... the re
turned image is in a resolution of 96 dpi.
... if the height or width of the canvas is 0 or larger than the maximum canvas size, the string "data:," is re
turned.
...And 2 more matches
HTMLFormElement.elements - Web APIs
the htmlformelement property elements re
turns an htmlformcontrolscollection listing all the form controls contained in the <form> element.
... you can access a particular form control in the re
turned collection by using either an index or the element's name or id.
... prior to html 5, the re
turned object was an htmlcollection, on which htmlformcontrolscollection is based.
...And 2 more matches
HTMLMedia​Element​.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.
...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.
...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.
...And 2 more matches
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.
...And 2 more matches
HTMLSlotElement - Web APIs
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).
...And 2 more matches
Recommended Drag Types - Web APIs
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.
...note that the instanceof operator is used here as the mozgetdataat() method will re
turn an nsisupports that needs to be checked and converted into an nsifile.
...And 2 more matches
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.
... re
turns a bytestring sequence representing the values of the retrieved header or null if this header is not set.
...And 2 more matches
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.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
...And 2 more matches
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.
...note that this doesn't re
turn the whole record as idbindex.get does.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
...And 2 more matches
ImageCapture - Web APIs
properties imagecapture.track read only re
turns a reference to the mediastreamtrack passed to the constructor.
... 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.
...And 2 more matches
InputEvent - Web APIs
inputevent.dataread only re
turns a domstring with the inserted characters.
... 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.
...And 2 more matches
compareVersion - Web APIs
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.
...And 2 more matches
LockManager.request() - Web APIs
the requested lock is passed to a callback, while the function itself re
turns a promise that resolves with undefined.
... callback … re
turn value a promise that resolves with undefined when the request is granted.
...once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback re
turns.
...And 2 more matches
MediaDeviceInfo.groupId - Web APIs
the groupid readonly property of the mediadeviceinfo interface re
turns a domstring that is a group identifier.
... 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.
... finally, the list, which now contains a mediadeviceinfo object for each device in the same group, is re
turned to the caller.
...And 2 more matches
MediaDeviceInfo - Web APIs
properties mediadeviceinfo.deviceidread only re
turns a domstring that is an identifier for the represented device that is persisted across sessions.
... mediadeviceinfo.groupidread only re
turns a domstring that is a group identifier.
... mediadeviceinfo.kindread only re
turns an enumerated value that is either "videoinput", "audioinput" or "audiooutput".
...And 2 more matches
MediaRecorder - Web APIs
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.videobitspersecond read only re
turns the video encoding bit rate in use.
...And 2 more matches
MediaSource - Web APIs
op"><rect x="151" y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="206" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mediasource</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mediasource() constructs and re
turns a new mediasource object with no associated source buffers.
... properties mediasource.sourcebuffers read only re
turns a sourcebufferlist object 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.
...And 2 more matches
MediaStream.getTrackById() - Web APIs
the mediastream.gettrackbyid() method re
turns a mediastreamtrack object representing the track with the specified id string.
... if there is no track with the specified id, this method re
turns null.
... syntax var track = mediastream.gettrackbyid(id); parameters id a domstring which identifies the track to be re
turned.
...And 2 more matches
MediaStreamTrack.getConstraints() - Web APIs
the getconstraints() method of the mediastreamtrack interface re
turns a mediatrackconstraints object containing the set of constraints most recently established for the track using a prior call to applyconstraints().
... 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.
...And 2 more matches
MimeType - Web APIs
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.
...And 2 more matches
NavigatorPlugins.plugins - Web APIs
re
turns a pluginarray object, listing the plugin objects describing the plugins installed in the application.
... 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.
...And 2 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.
... examples standard dom a standard dom example: let test = document.createelement('p'); console.log(test.isconnected); // re
turns false document.body.appendchild(test); console.log(test.isconnected); // re
turns true shadow dom a shadow dom example: // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create some css to apply to the shadow dom var style = document.createelement('style'); console.log(style.isconnected); // re
turns false style.textcontent = ` .wrapper { position: relative; } .info { font-size: 0.8rem; width: 200px; display: inline-block; border: 1px solid black; padding: 10px; background: white; border-radius: 10px; opacity: 0; transition: 0.6s all; positions: absolute; bottom: 20px; left: 10px; z-index: 3 } `; // attac...
...And 2 more matches
Node.nodeValue - Web APIs
the nodevalue property of the node interface re
turns or sets the value of the current node.
...for the document itself, nodevalue re
turns null.
... for text, comment, and cdata nodes, nodevalue re
turns the content of the node.
...And 2 more matches
NodeFilter - Web APIs
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.
...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.
...And 2 more matches
ParentNode.querySelectorAll() - Web APIs
the parentnode mixin defines the queryselectorall() method as re
turning a nodelist representing a list of elements matching the specified group of selectors which are descendants of the object on which the method was called.
... 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.
...And 2 more matches
PaymentResponse.retry() - Web APIs
re
turn value a promise which is resolved when the payment is successfully completed.
... 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.
... 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.
...And 2 more matches
performance.getEntriesByName() - Web APIs
the getentriesbyname() method re
turns a list of performanceentry objects for the given name and type.
... 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.
...And 2 more matches
PerformanceResourceTiming.initiatorType - Web APIs
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".
...And 2 more matches
PhotoCapabilities - Web APIs
properties photocapabilities.redeyereduction read only re
turns one of "never", "always", or "controllable".
... 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.
...And 2 more matches
PushManager - Web APIs
properties pushmanager.supportedcontentencodings re
turns an array of supported content codings that can be used to encrypt the payload of a push message.
...it re
turns a promise that resolves to a pushsubscription object containing details of an existing subscription.
... 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'.
...And 2 more matches
PushRegistrationManager - Web APIs
re
turns an interface to register or unregister a push registration, get an active registration, or check the permission status of the registration.
... methods pushregistrationmanager.register() re
turns a promise that resolves to a pushregistration with details of a new registration.
... pushregistrationmanager.unregister() re
turns a promise that resolves to a pushregistration with details of the unregistered registration.
...And 2 more matches
RTCConfiguration - Web APIs
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.
...a value of relay limits the candidates to those relayed through another server, such as a stun or
turn server.
...And 2 more matches
RTCDataChannel - Web APIs
the default is "blob".bufferedamount read 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 identifi...
...es the rtcdatachannel.label read only the read-only rtcdatachannel property label re
turns a domstring containing a name describing the data channel.
... these labels are not required to be unique.maxpacketlifetime read only the read-only rtcdatachannel property maxpacketlifetime re
turns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null.maxretransmits read only the read-only rtcdatachannel property maxretransmits re
turns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or null, which indicates that there is no maximum.negotiated read only the read-only rtcdatachannel property negotiated indicates whether the rtcdatachannel's connection was negotiated by the web app (true) or by the webrtc layer (false).ordered read only the read-only rtcdatachannel prop...
...And 2 more matches
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 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 value re
turned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair.
...And 2 more matches
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.
... 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.
...And 2 more matches
RTCPeerConnection.createAnswer() - Web APIs
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.
... 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.
...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.
...And 2 more matches
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.
...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.
...And 2 more matches
ReadableStream.getReader() - Web APIs
re
turn value a readablestreamdefaultreader or readablestreambyobreader object instance, depending on the mode value.
...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.
... function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() re
turns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...And 2 more matches
ReadableStream.pipeThrough() - Web APIs
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.
...the method will re
turn a promise rejected with the source’s error, or with any error that occurs during aborting the destination.
...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.
...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.
... re
turn value an array containing two readablestream instances.
... function teestream() { const teedoff = stream.tee(); fetchstream(teedoff[0], list2); fetchstream(teedoff[1], list3); } function fetchstream(stream, list) { const reader = stream.getreader(); let charsreceived = 0; // read() re
turns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...And 2 more matches
ReadableStream - Web APIs
constructor readablestream() creates and re
turns a readable stream object from the given handlers.
... properties readablestream.locked read only the locked getter re
turns whether or not the readable stream is locked to a reader.
... 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.
...And 2 more matches
ReadableStreamDefaultReader.cancel() - Web APIs
re
turn value a promise, which fulfills with the value given in the reason parameter.
...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.
... function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() re
turns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...And 2 more matches
ReadableStreamDefaultReader - Web APIs
constructor readablestreamdefaultreader() creates and re
turns a readablestreamdefaultreader object instance.
...re
turns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors.
... readablestreamdefaultreader.read() re
turns a promise providing access to the next chunk in the stream's internal queue.
...And 2 more matches
SVGTextPositioningElement - Web APIs
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.
...And 2 more matches
SVGTransformList - Web APIs
methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list.
...the re
turn value is the item inserted into the list.
... getitem(in unsigned long index) svgtransform re
turns the specified item from the list.
...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).
...And 2 more matches
Screen Wake Lock API - Web APIs
concepts and usage most devices by default
turn off their screen after a specified amount of time to prolong the life of the hardware.
... the screen wake lock api prevents the screen from
turning off, dimming or locking.
... navigator.wakelock re
turns a wakelock object instance, from which all other functionality can be accessed.
...And 2 more matches
ServiceWorkerGlobalScope - Web APIs
this re
turns a promise that resolves to the response object representing the response to your request.
...when fired, the code re
turns a promise that resolves to the first matching request in the cache object.
...it will re
turn a normal response object that has the appropriate error code set.
...And 2 more matches
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() { ...
... 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.
...And 2 more matches
SpeechRecognitionResult.item() - Web APIs
syntax var myalternative = speechrecognitionresultinstance[0]; re
turns a speechrecognitionalternative object.
... 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.
...And 2 more matches
SpeechRecognitionResultList.item() - Web APIs
syntax var myresult = speechrecognitionresultlistinstance[0]; re
turns a speechrecognitionresult object.
... 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.
...And 2 more matches
SpeechRecognitionResultList - Web APIs
properties speechrecognitionresultlist.length read only re
turns the length of the "array" — the number of speechrecognitionresult objects in the list.
... 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.
...And 2 more matches
SpeechSynthesis - Web APIs
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.
...And 2 more matches
SubtleCrypto.deriveKey() - Web APIs
it re
turns a promise which will be fulfilled with a cryptokey object representing the new key.
... re
turn value result is a promise that fulfills with a cryptokey.
... /* derive an aes key, given: - our ecdh private key - their ecdh public key */ function derivesecretkey(privatekey, publickey) { re
turn window.crypto.subtle.derivekey( { name: "ecdh", public: publickey }, privatekey, { name: "aes-gcm", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agreesharedsecretkey() { // generate 2 ecdh key pairs: one for alice and one for bob // in more normal usage, they would generate their key pairs // separately and exchange ...
...And 2 more matches
TaskAttributionTiming - Web APIs
the taskattributiontiming interface of the long tasks api re
turns information about the work involved in a long task and its associate frame context.
...th="210" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="306" y="30" font-size="12px" font-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.
...And 2 more matches
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.
... 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.
...And 2 more matches
UIEvent.pageY - Web APIs
the uievent.pagey read-only property re
turns the vertical coordinate of the event relative to the whole document.
...%; right:auto; width: 40%; border: solid blue 1px; padding: 20px; } #d3 { position: absolute; top: 240px; left: 20%; width: 50%; 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!
...And 2 more matches
WakeLockSentinel - Web APIs
an object representing the wake lock is re
turned via the navigator.wakelock.request() method.
...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.
... type read only re
turns a string representation of the currently acquired wakelocksentinel type.
...And 2 more matches
WebGL2RenderingContext.getQueryParameter() - Web APIs
the webgl2renderingcontext.getqueryparameter() method of the webgl 2 api re
turns parameter information of 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.
...And 2 more matches
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
the webglrenderingcontext.checkframebufferstatus() method of the webgl api re
turns the completeness status of the webglframebuffer object.
... 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.
...And 2 more matches
WebGLRenderingContext.getShaderParameter() - Web APIs
the webglrenderingcontext.getshaderparameter() method of the webgl api re
turns information about the given shader.
...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.
...And 2 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
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.
...among the simplest things you can do is to implement a "hold" feature, wherein a participant in a call can click a button and
turn off their microphone, begin sending music to the other peer instead, and stop accepting incoming audio.
...this enormously simplifies and makes far more readable the code dealing with the promises re
turned by webrtc methods.
...And 2 more matches
Introduction to WebRTC protocols - Web APIs
ice uses stun and/or
turn servers to accomplish this, as described below.
...in this situation we need to
turn to
turn.
...
turn some routers using nat employ a restriction called ‘symmetric nat’.
...And 2 more matches
Geometry and reference spaces in WebXR - Web APIs
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..
... 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.
...And 2 more matches
Web Locks API - Web APIs
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 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.
...And 2 more matches
Functions and classes available to Web Workers - Web APIs
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.
... workers can also create a new url using the url() constructor and call any normal method on the re
turned object.
... no support no support no support websocket creates and re
turns a new websocket object; this mimics the behavior of the standard websocket() constructor.
...And 2 more matches
Window: beforeunload event - Web APIs
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.
... examples the html specification states that authors should use the event.preventdefault() method instead of using event.re
turnvalue.
...And 2 more matches
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.
... 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.
...And 2 more matches
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.
... 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.
...And 2 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
re
turn value an instance of the writablestreamdefaultwriter object.
...inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter.
...finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams.
...And 2 more matches
WritableStreamDefaultWriter.close() - Web APIs
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.
...inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter.
...finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams.
...And 2 more matches
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.
... type optional specifies the type of result to be re
turned by evaluating the expression.
... result optional allows to specify a result object which may be reused and re
turned by this method.
...And 2 more matches
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.
... type optional specifies the type of result to be re
turned by evaluating the expression.
... result optional allows to specify a result object which may be reused and re
turned by this method.
...And 2 more matches
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.
...And 2 more matches
attr() - CSS: Cascading Style Sheets
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.
...it is not reparsed, and in particular the characters are used as-is instead of css escapes being
turned into different characters.
...)where <type-or-unit> = string | color | url | integer | number | length | angle | time | frequency | cap | ch | em | ex | ic | lh | rlh | rem | vb | vi | vw | vh | vmin | vmax | mm | q | cm | in | pt | pc | px | deg | grad | rad |
turn | ms | s | hz | khz | % examples content property html <p data-foo="hello">world</p> css [data-foo]::before { content: attr(data-foo) " "; } result <color> value html <div class="background" data-background="lime">background expected to be red if your browser does not support advanced usage of attr()</div> css .background { height: 100vh; } .background { background-colo...
...And 2 more matches
Cross-browser audio basics - Developer guides
} canplaytype() re
turns one of three values: probably maybe "" (an empty string) in practice, we usually check if the result is true or false.
... 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.
... play the play event is initiated after the play() method is re
turned or when the autoplay attribute has caused playback to begin.
...And 2 more matches
<input type="url"> - HTML: Hypertext Markup Language
the text must not include carriage re
turns or line feeds.
... 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.
... 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.
...And 2 more matches
Content-Location - HTTP
the content-location header indicates an alternate location for the re
turned data.
...location is a header associated with the response, while content-location is associated with the data re
turned.
... 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.
...And 2 more matches
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.
...And 2 more matches
Array.prototype.lastIndexOf() - JavaScript
the lastindexof() method re
turns the last index at which a given element can be found in the array, or -1 if it is not present.
...if the calculated index is less than 0, -1 is re
turned, i.e.
... re
turn value the last index of the element in the array; -1 if not found.
...And 2 more matches
BigInt.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified bigint object.
... re
turn value a string representing the specified bigint object.
...for bigint objects, the tostring() method re
turns a string representation of the object in the specified radix.
...And 2 more matches
Boolean.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified boolean object.
... syntax bool.tostring() re
turn value a string representing the specified boolean object.
...for boolean objects, the tostring method re
turns a string representation of the object.
...And 2 more matches
Function.prototype.apply() - JavaScript
re
turn value the result of calling the function with the specified this value and arguments.
...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.
...t grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time: function minofarray(arr) { let min = infinity; let quantum = 32768; for (var i = 0, len = arr.length; i < len; i += quantum) { var submin = math.min.apply(null, arr.slice(i, math.min(i+quantum, len))); min = math.min(submin, min); } re
turn min; } let min = minofarray([5, 6, 2, 3, 7]); using apply to chain constructors you can use apply to chain constructors for an object (similar to java).
...And 2 more matches
Generator.prototype.next() - JavaScript
the next() method re
turns an object with two properties done and value.
... 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.
...And 2 more matches
Intl.NumberFormat.prototype.formatToParts() - JavaScript
re
turn value an array of objects containing the formatted number in parts.
...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: "integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" } ] possible types are the following: currency the currency string, such as the symbols "$" and "€" or the name "dollar", "euro" depending on how currencydisplay is specified.
...And 2 more matches
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.
... 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.
...And 2 more matches
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.
... 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.
...And 2 more matches
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.
... 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.
...And 2 more matches
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.
... re
turn value the base 10 logarithm of the given number.
... if the number is negative, nan is re
turned.
...And 2 more matches
Math.log1p() - JavaScript
the math.log1p() function re
turns the natural logarithm (base e) of 1 + 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.
... 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.
...And 2 more matches
Math.tan() - JavaScript
the math.tan() function re
turns the tangent of a number.
... 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.
...And 2 more matches
Number.isInteger() - JavaScript
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.
...And 2 more matches
Number.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified number object.
... re
turn value a string representing the specified number object.
...for number objects, the tostring() method re
turns a string representation of the object in the specified radix.
...And 2 more matches
Object.prototype.constructor - JavaScript
the constructor property re
turns a reference to the object constructor function that created the instance object.
...*/ } 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?
...*/ } 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.
...And 2 more matches
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.
... re
turn value a property descriptor of the given property if it exists on the object, undefined otherwise.
...And 2 more matches
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.
... 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.
...And 2 more matches
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.
... 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.
... 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.
...And 2 more matches
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.
... 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.
...And 2 more matches
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.
...And 2 more matches
handler.getPrototypeOf() - JavaScript
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 target is not extensible, object.getprototypeof(proxy) method must re
turn the same value as object.getprototypeof(target).
...And 2 more matches
handler.set() - JavaScript
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.
...And 2 more matches
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.
... re
turn value a boolean indicating whether or not the prototype was successfully set.
...And 2 more matches
RegExp - JavaScript
regexp.prototype.tostring() re
turns a string representing the specified object.
... 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.
...And 2 more matches
String.prototype.replaceAll() - JavaScript
the replaceall() method re
turns a new string with all matches of a pattern replaced by a replacement.
...the matches are replaced with newsubstr or the value re
turned by the specified function.
... re
turn value a new string, with all matches of a pattern replaced by a replacement.
...And 2 more matches
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.
...(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.
...(for example, if endindex is -3 it is treated as str.length - 3.) re
turn value a new string containing the extracted section of the string.
...And 2 more matches
TypedArray.prototype.every() - JavaScript
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 re
turns false.
...And 2 more matches
TypedArray.prototype.slice() - JavaScript
the slice() method re
turns a shallow copy of a portion of a typed array into a new typed array object.
... re
turn value a new typed array containing the extracted elements.
...it re
turns a shallow copy of elements from the original typed array.
...And 2 more matches
TypedArray.prototype.some() - JavaScript
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.
...And 2 more matches
WeakMap - JavaScript
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.
...And 2 more matches
Strict equality (===) - JavaScript
the strict equality operator (===) checks whether its two operands are equal, re
turning a boolean result.
... 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.
...And 2 more matches
yield* - JavaScript
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).
...And 2 more matches
Codecs used by WebRTC - Web media technologies
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.
...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.
... 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.
...And 2 more matches
Performance fundamentals - Web Performance
in re
turn, they perceive outputs through sight, touch, and hearing.
...(strobe lights are fun because they
turn that upside down, starving your brain of inputs to create the illusion of discrete reality).
...to improve power usage, simple scenes are rendered using special dedicated composition hardware, while the gpu idles or
turns off.
...And 2 more matches
Example - SVG: Scalable Vector Graphics
</div> <form action="" onsubmit="re
turn false;"> <p> <label>number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>max.
... function display() { re
turn document.getelementbyid('display'); } // determine dimensions of the display element.
... // re
turn this as a 2-tuple (x,y) in an array function dimensions() { // our rendering element var display = display(); var width = parseint( display.getattributens(null,'width') ); var height = parseint( display.getattributens(null,'height') ); re
turn [width,height]; } // this is called by mouse move events var mouse_x = 200, mouse_y = 150; function onmousemove(evt) { mouse_x = evt.clientx; mouse_y = evt.clienty; var widget = document.getelementbyid('cursor'); widget.setattributens(null,'cx',mouse_x); widget.setattributens(null,'cy',mouse_y); } document.onmousemove = onmousemove; // determine (x,y) of the cursor function cursor() { re
turn [mouse_x, mouse_y]; } // determine average (x,y) of the swarm function averagemotepos...
...And 2 more matches
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.
... re
turns a string representing uri of the namespace in which the given node resides.
...And 2 more matches
XPath snippets - XPath
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.
... 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.
...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).
...And 2 more matches
panel - Archive of obsolete content
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.
...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.
...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.
...only
turn this off if necessary, to prevent accessibility issue.
querystring - Archive of obsolete content
re
turns string : the query string.
... re
turns object : an object containing the components of the query string as name : value pairs.
... re
turns string : the escaped query string.
... re
turns string : the unescaped string.
selection - Archive of obsolete content
getting the selection when there is no current selection re
turns null.
...getting the selection when iscontiguous is true re
turns the text of the first selection.
...getting the selection when there is no current selection re
turns null.
...getting the selection when iscontiguous is true re
turns the text of the first selection.
self - Archive of obsolete content
methods data.load(name) the data.load() method re
turns the contents of an embedded data file, as a string.
... 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.
... re
turns string : resource:// url pointing to the given location under data.
io/text-streams - Archive of obsolete content
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.
... read(numchars) reads and re
turns a string from the stream.
... re
turns string : the string read.
... if the stream is at the end, the empty string is re
turned.
loader/sandbox - Archive of obsolete content
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.
... re
turns result : re
turns whatever the evaluated code re
turns.
... re
turns result : re
turns whatever the evaluated code re
turns.
ui/button/action - Archive of obsolete content
button({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled: true }); } to fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will re
turn the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
... change its label for only the currently active window like this: button.state("window", { "label" : "window-specific label" }); you can change its label for only the currently active tab like this: button.state("tab", { "label" : "tab-specific label" }); to fetch the button state for a specific window or tab, call state(), passing it the window or tab you're interested in, and it will re
turn a state object containing all the properties for the button associated with that window or tab.
...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.
ui/button/toggle - Archive of obsolete content
button({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled: true }); } to fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will re
turn the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
... change its label for only the currently active window like this: button.state("window", { "label" : "window-specific label" }); you can change its label for only the currently active tab like this: button.state("tab", { "label" : "tab-specific label" }); to fetch the button state for a specific window or tab, call state(), passing it the window or tab you're interested in, and it will re
turn a state object containing the id, label, icon, and disabled properties for the button associated with that window or tab.
...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.
Creating annotations - Archive of obsolete content
$('*').mouseenter(function() { if (!active || $(this).hasclass('annotated')) { re
turn; } resetmatchedelement(); ancestor = $(this).closest("[id]"); matchedelement = $(this).first(); originalbgcolor = $(matchedelement).css('background-color'); $(matchedelement).css('background-color', 'yellow'); $(matchedelement).bind('click.annotator', function(event) { event.stoppropagation(); event.preventdefault(); self.port.emit('show', [ document.locati...
... index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } edit toggleactivation() to notify the workers of a change in activation state: function activateselectors() { selectors.foreach( function (selector) { selector.postmessage(annotatorison); }); } function toggleactivation() { annotatorison = !annotatorison; activateselectors(); re
turn annotatorison; } we'll be using this url in all our screenshots.
... 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.
...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.
IsDefaultNamespace - Archive of obsolete content
this function is not necessary for gecko-based browsers (though the function will quickly re
turn the standard value for mozilla browsers).
... // http://www.w3.org/tr/dom-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.parentnode) { // entityreferences may have to be skipped to get to it re
turn isdefaultnamespace(node.parentnode, namespaceuri); } else { re
turn false; // unknown; } case 9: // document_node re
turn isdefaultnamespace(node.documentelement, namespaceuri); case 6: // entity_node case 12: // notation_node case 10: // document_type_node case 11: // document_fragment_node re
turn false; // unknown case 2: // attribute_node: if (node.ownerelement ) { re
turn isdefaultnamespace(node.ownerelement , namespaceuri); } else { re
turn false; // unknown } ...
... default: if (node.parentnode) { // entityreferences may have to be skipped to get to it re
turn isdefaultnamespace(node.parentnode, namespaceuri); } else { re
turn false; // unknown } } } ...
JS XPCOM - Archive of obsolete content
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.
...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=mystuff", queryinterface: xpcomutils.generateqi([ci.nsiaboutmodule]) } var nsgetmodule = xpcomutils.generatensgetmodule([abouthandler]); } ...
JavaScript Debugger Service - Archive of obsolete content
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.
...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...
...t.filename + "@" + f.line + "@" + f.functionname + "\n"; } dump(stacktrace); re
turn components.interfaces.jsdiexecutionhook.re
turn_continue; } }; filters jsd also allows the use of filters to track which scripts should trigger the hooks.
...(jsdifilter.flag_enabled | jsdifilter.flag_pass) : jsdifilter.flag_enabled, urlpattern: pattern, startline: 0, endline: 0 }; re
turn filter; }, we then add the filters we want.
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.
... // if you'd like to convert it to a array for convenience, use this instead: // re
turn array.prototype.slice.call(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(select...
...or); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) { // only for xul re
turn this.queryselector(selector); }; example: <label value="test!"/> <script type="text/javascript"><![cdata[ xuldocument.prototype.$ = function (selector) { // only for xul re
turn this.queryselector(selector); }; alert(document.$('label')); // [object xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml re
turn this.queryselector(selector); }; var foo = document.implementation.createdocument('somens', 'foo', null); // create an xml document <foo xmlns="somens"/> var bar = foo.createelementns('somens', 'bar'); // add <bar xmlns="somens"/> foo.documentelement.appendchild(bar); alert(foo.$('bar').nodena...
...me); // gives 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml re
turn this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { re
turn this.queryselector(selector); }; alert(document.getelementsbytagname('h1')[0].$('a').nodename); // 'a' xul example: <hbox><vbox/></hbox> <script type="text/javascript"><![cdata[ element.prototype.$ = function (selector) { re
turn this.queryselector(selector); }; var xulns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getelementsbytagnamens(xulns, 'hbox')[0].$('vbox').nodename); // vbox ]]></script> xml example: <foo xmlns="somens"><bar/></foo> in document earlier var foo = document.getelementsbytagnamens('some...
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 next matching local name up in the hierarchy (until the document root) while (thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { att = thisitem.getattribute('xml:base'); // xml: namespaces must use 'xml' prefix if (att) { protocolpos = att.indexof('//'); var protocolmatch = att.match(scheme); if (protocolmatch) { // if has protocol, can stop if (abs) { var skipfile = (att.indexof('///') === protocolpos) ?
...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; } ...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
on(event) { event.preventbubble(); var fileenum = this._dir.directoryentries; while (fileenum.hasmoreelements()) { var file = fileenum.getnext().queryinterface(components.interfaces.nsifile); file.remove(false); // debug dump("sessionstore> clear: " + file.leafname + "\n"); } }, _readfile method reads the nslfile object passed as a parameter, and re
turns its contents as a text string.
... 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.
...in practice, what you’ll do is remove the pointer file, relaunch firefox, re
turn the pointer file, and relaunch firefox again.
... getbrowserstate() re
turns a json-formatted5 text string representing the state of every currently open browser window.
JavaScript Object Management - Archive of obsolete content
* @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.
Dehydra Object Reference - Archive of obsolete content
.isstatic boolean flag .isre
turn boolean flag the variable is being re
turned.
...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).
... function type these represent the types functions and methods in the type system: property type description .type type object the function re
turn type.
Drag and Drop JavaScript Wrapper - Archive of obsolete content
getsupportedflavours() this function should re
turn a list of flavors that the object being dragged over can accept.
...the getsupportedflavours function should re
turn a list of flavours that the element being dragged over can accept for dropping.
...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'.
...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.
File object - Archive of obsolete content
if no argument is supplied to the constructor, the current working directory is the file object that is re
turned.
... file.readall() read the entire file in, re
turning an array of lines.
...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.
Using Breakpoints in Venkman - Archive of obsolete content
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.
...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.
confirm - Archive of obsolete content
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).
... 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, confirm() always re
turned a plain integer (in pre-gecko-1.8 versions either 0 or 1).
getLastError - Archive of obsolete content
getlasterror re
turns the most recent nonzero error code.
...re
turns the most recent nonzero error code.
... for a list of possible values, see re
turn codes.
...the getlasterror method does not re
turn errors from methods that re
turn objects, such as getfolder.
patch - Archive of obsolete content
re
turns an integer error code.
... for a list of possible values, see re
turn codes.
...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.
...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.
Methods - Archive of obsolete content
(mac os only) getcomponentfolder re
turns an object representing the directory in which a component is installed.
... getfolder re
turns an object representing a directory, for use with the addfile method.
... getlasterror re
turns the most recent non-zero error code.
... loadresources re
turns an object whose properties are localized strings loaded from the specified property file.
XUL Events - Archive of obsolete content
re
turning false from this event handler prevents the popup from appearing.
...re
turning false from this event handler prevents the popup from appearing.
...the script may re
turn a value to set the element to a specific value rather than the value of the preference.
...the script may re
turn a value to set the preference to a specific value rather than the value of the element.
Accessing Files - Archive of obsolete content
one such method it provides is nsiscriptableio.getfile() which re
turns a new nsifile object.
...that is, nsiscriptableio.getfile() will still re
turn a valid file reference even if the file 'sample.txt' does not yet exist.
...the exists method re
turns true if the file is present and false if it is not.
...for instance, on windows, the value 'strt' re
turns the start directory, where applications which run when the system starts up are placed.
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 = ...
...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, reverse sort if (column) { columnname = column.id; if (tree.getattribute("sortresource") == columnname) { order *= -1; } } else { columnname = tree.getattribute("sortresource"); } function columnsort(a, b) { if (prepareforcomparison(a[columnname]) > prepareforcomparison(b[columnname])) re
turn 1 * order; if (prepareforcomparison(a[columnname]) < prepareforcomparison(b[columnname])) re
turn -1 * order; //tie breaker: name ascending is the second level sort if (columnname != "name") { if (prepareforcomparison(a["name"]) > prepareforcomparison(b["name"])) re
turn 1; if (prepareforcomparison(a["name"]) < prepareforcomparison(b["name"])) re
turn -1; } re
turn 0; } table.sort(columnsort); //se...
...for strings, lowercases them function prepareforcomparison(o) { if (typeof o == "string") { re
turn o.tolowercase(); } re
turn o; } function gettopvisiblerow() { re
turn tree.treeboxobject.getfirstvisiblerow(); } function settopvisiblerow(topvisiblerow) { re
turn tree.treeboxobject.scrolltorow(topvisiblerow); } function inputfilter(event) { //do this now rather than doing it at every comparison var value = prepareforcomparison(event.target.value); setfilter(value); document.getelementb...
SQLite Templates - Archive of obsolete content
<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.
...you can re
turn multiple columns or filtered data by using a more complex query.
Tree Widget Changes - Archive of obsolete content
ns[5]; once you have a column, you can get various properties of it: column.index - the index of the column in displayed order column.id - the id attribute of the column column.element - the treecol element column.x - the x position in the tree of the left edge of the column column.width - the width of the column in c++ code, you can also get the atom attribute of nsitreecolumn which re
turns an nsiatom for the column, making it fast to do comparisons.
...it re
turns the number of rows that can be displayed in the tree.
...it should re
turn true if a drop is allowed on a row.
...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.
Creating Dialogs - Archive of obsolete content
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 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.
...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 ...
XPCOM Examples - Archive of obsolete content
the function getwindowforresource() takes the resource and re
turns a window that matches it.
...the cookie manager has an enumerator method which re
turns an object which implements nsisimpleenumerator.
...an enumerator has a hasmoreelements() method which will re
turn true until we get to the last cookie.
...since an enumerator just re
turns a generic object, we need to queryinterface() it to an nsicookie before we can use it.
XPCOM Interfaces - Archive of obsolete content
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.
...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.
... isdirectory() re
turns true if the nsilocalfile represents a directory.
... function copyfile(sourcefile,destdir) { // get a component for the file to copy var afile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); if (!afile) re
turn false; // get a component for the directory to copy to var adir = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); if (!adir) re
turn false; // next, assign urls to the file components afile.initwithpath(sourcefile); adir.initwithpath(destdir); // finally, copy the file, without renaming it afile.copyto(adir,null); } copyf...
XUL Questions and Answers - Archive of obsolete content
re
turn to mozilla-dev-tech-xul summaries the frequently asked questions should be moved to xul faq (make sure they have a clear answer.) where can i get more information about creating mozsearch plugins?
... 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.
...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...
...j.wpl.state_is_network ) { // fires when all load are really over, // do something "final" here // (my two cents) } else { // this fires when a load finishes } } } re
turn 0; } // this fires when the location bar changes i.e load event is confirmed // or when the user switches tabs listobj.onlocationchange = function(aprogress, arequest, auri) { // do whatever you want to do re
turn 0; } // for definitions of the remaining functions see xulplanet.com listobj.onprogresschange = function() { re
turn 0 }; listobj.onstatuschange = function() { re
turn 0 }; listobj.onsecuritychange = function() { re
turn 0 }; listobj.onlinkiconavailable = function() { re
turn 0 }; /* i use the progress listener to trap the end of a local html "template" file loa...
promptBox - Archive of obsolete content
it's re
turned by the tabbrowser method gettabmodalpromptbox method.
... re
turn value an nsidomelement object representing the new prompt.
... listprompts() re
turns a list of all the prompts on the tabbrowser.
... re
turn value a nodelist containing all of the prompt elements on the tabbrowser.
radio - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an element that can be
turned on and off.
...the user can switch which radio button is
turned on by selecting it with the mouse or keyboard.
... other radio buttons in the same group are
turned off.
... 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.
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 value increases the value of the scale by the page increment.
stringbundle - Archive of obsolete content
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 applocale obsolete since gecko 1.9.1 type: nsilocale re
turns the xpcom object which holds information about the user's locale.
... stringbundle type: nsistringbundle re
turns the xpcom string bundle object which implements nsistringbundle.
... methods getformattedstring( key, strarray ) re
turn type: string looks up the format string for the given key name in the string bundle and re
turns a formatted copy where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
... getstring( key ) re
turn type: string re
turns the string with the given key name from the string bundle.
tree - Archive of obsolete content
columns type: nsitreecolumns re
turns the columns for the tree as an nsitreecolumns object.
...rtbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata startediting( row, column ) re
turn type: no re
turn value activates user editing of the given cell, which is specified by row index number and the nsitreecolumn in which it is located.
... stopediting( shouldaccept ) re
turn type: no re
turn value stops editing the cell currently being edited.
...the value of the id attribute for each of the selected rows of a tree: var idlist = []; var rangecount = tree.view.selection.getrangecount(); for (var i = 0; i < rangecount; i++) { var start = {}; var end = {}; tree.view.selection.getrangeat(i, start, end); for (var c = start.value; c <= end.value; c++) { idlist.push(tree.view.getitematindex(c).firstchild.id); } } the following re
turns a array of the indicies of the rows where the value is checked in a checkbox type column: function getcellchecked(tree, columnid) { var arr = []; var column = tree.columns.getnamedcolumn(columnid); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, column) == 'true') arr.push(i); } re
turn arr; } to get the text value for a specific column (for exa...
NPEvent - Archive of obsolete content
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.
... 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.
NPN_GetIntIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary re
turns an opaque identifier for the integer that is passed in.
... syntax #include <npruntime.h> npidentifier npn_getintidentifier(int32_t intid); parameters the function has the following parameter: <tt>intid</tt> the integer for which an opaque identifier should be re
turned.
... re
turns an npidentifier identifying the integer.
... description all calls for the same integer are guaranteed to re
turn the same exact identifier.
NPN_GetStringIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary re
turns an opaque identifier for the string that is passed in.
... syntax #include <npruntime.h> npidentifier npn_getstringidentifier(const nputf8 *name); parameters the function has the following parameters: <tt>name</tt> the string for which an opaque identifier should be re
turned.
... re
turns an npidentifier identifying the string.
... description all calls for the same string are guaranteed to re
turn the same exact identifier.
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.
... 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_GetURLNotify - Archive of obsolete content
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.
...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 nperr_invalid_param.
NPN_GetValueForURL - Archive of obsolete content
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.
NPN NewStream - Archive of obsolete content
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.
...the stream is re
turned in the stream parameter.
...if the new stream has the target of _self, this function should re
turn an invalid_param np error.
NPN_RequestRead - Archive of obsolete content
re
turns if successful, the function re
turns nperr_no_error.
... if unsuccessful, the function re
turns an error code.
...the plug-in can free these as soon as the call re
turns.
... 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.
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_Destroy - Archive of obsolete content
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.
...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.
...ownership of the buf field of the npsaveddata structure passes from the plug-in to the browser when npp_destroy re
turns.
NPP_Write - Archive of obsolete content
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 re
turning a negative value.
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.
...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.
...if the user revisits a web page that contains a plug-in, the browser re
turns the npsaveddata to the new instance of the plug-in in a call to npp_new().
Processing XML with E4X - Archive of obsolete content
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.
... 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.
...uently, filters can also run against the value of a single node contained within the current element: var people = <people> <person> <name>bob</name> <age>32</age> </person> <person> <name>joe</name> <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.
Descendants and Filters - Archive of obsolete content
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 .
...consider var element = <dogs> <fido color="brown"/> <spike color="black"/> <killer color="brown"/> </dogs>; var list = element.*.(@color == "brown"); originally, elements.* re
turns a list with all 3 dogs in it.
The global XML object - Archive of obsolete content
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 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.
...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.
Date.getVarDate() - Archive of obsolete content
the getvardate method re
turns a vt_date value from 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.
...the actual format of the re
turned value depends on regional settings.
Enumerator.atEnd - Archive of obsolete content
the enumerator.atend method re
turns a boolean value indicating if the enumerator is at the end of the collection.
... 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.
... s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } re
turn(s); } 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 internet explorer 10 standards.
Enumerator.item - Archive of obsolete content
the enumerator.item method re
turns the current item in the collection.
... the item method re
turns the current item.
... if the collection is empty or the current item is undefined, it re
turns undefined.
... s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } re
turn(s); } 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 internet explorer 10 standards.
handler.enumerate() - Archive of obsolete content
re
turn value an iterator object.
... 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.
... 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.
Anatomy of a video game - Game development
this is more of a
turn-based approach that doesn't demand a constant update every frame, only when the player reacts.
...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.
...*/ ;(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().
...this value is re
turned as a decimal number accurate to a thousandth of a millisecond.
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... most of the time, idl attributes will re
turn their values as they are really used.
...however, the type idl attribute will re
turn the string "text".
...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.
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...
... // 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?
... 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; } ...
Legacy layout methods - Learn web development
lass="col">6</div> <div class="col">7</div> <div class="col">8</div> <div class="col">9</div> <div class="col">10</div> <div class="col">11</div> <div class="col">12</div> </div> <div class="row"> <div class="col span1">13</div> <div class="col span6">14</div> <div class="col span3">15</div> <div class="col span2">16</div> </div> </div> the aim is to
turn this into a demonstration grid of two rows on a twelve column grid — the top row demonstrating the size of the individual columns, the second row some different sized areas on the grid.
...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.
... here we are
turning each row into a flex container.
create fancy boxes - Learn web development
it's fun because it's all about
turning a design idea into working code; it's challenging because of annoying constraints and crazy freedom in the use of css.
... 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.
...i want to be fancy.</div> let's have an example by
turning our box into a cloud: .fancy { text-align: center; /* same trick as previsouly used to make circles */ box-sizing: border-box; width : 150px; height : 150px; padding : 80px 1em 0 1em; /* we make room for the "ears" of our cloud */ margin : 0 100px; position: relative; background-color: #a4c9cf; /* well, actually we are not making a full circle as we...
Styling links - Learn web development
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.
...the outline is a useful accessibility aid, so think carefully before
turning it off; you should at least double up the styles given to the link hover state on the focus state too.
... 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.
The HTML5 input types - Learn web development
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.
... 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.
...while time may display in 12-hour format, the value re
turned is in 24-hour format.
...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.
Advanced text formatting - Learn web development
for example, the following markup is taken from the mdn <blockquote> element page: <p>the <strong>html <code><blockquote></code> element</strong> (or <em>html block quotation element</em>) indicates that the enclosed text is an extended quotation.</p> to
turn this into a block quote, we would just do this: <p>here below is a blockquote...</p> <blockquote cite="/docs/web/html/element/blockquote"> <p>the <strong>html <code><blockquote></code> element</strong> (or <em>html block quotation element</em>) indicates that the enclosed text is an extended quotation.</p> </blockquote> browser default styling will render this as an indented paragra...
...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.
Video and audio content - Learn web development
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).
...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.
... muted causes the media to play with the sound
turned off by default.
...note that to
turn the subtitles on, you need to press the "cc" button and select an option — english, deutsch, or español.
General asynchronous programming concepts - Learn web development
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.
...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.
...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.
JavaScript building blocks - Learn web development
in this module, we continue our coverage of all javascript's key fundamental features,
turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.
... 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 web APIs - Learn web development
it provides a special set of constructs you can use to query the twitter service and re
turn specific information.
... 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.
... 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.
...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.
Video and Audio APIs - Learn web development
previous overview: client-side web apis next 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.
...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.
...this re
turns a boolean true/false result.
... can you work out a way to
turn the timer inner <div> element into a true seek bar/scrobbler — i.e., when you click somewhere on the bar, it jumps to that relative position in the video playback?
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 === false; }); } using array.filter(), we declare that "incomplete" todos are ones that have iscompleted equal to false.
...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.
... get todocountisone() { re
turn this.incomplete.length === 1; } then go back over to footer.hbs and update the previous template section we edited to the following: <strong>{{this.todos.incomplete.length}}</strong> {{#if this.todos.todocountisone}} todo {{else}} todos {{/if}} left now save and test, and you'll see the correct pluralization used when you only have one todo item present!
Accessibility in React - Learn web development
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.
... 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().
...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.
...add it to the top of your app.js file, just below the imports: function useprevious(value) { const ref = useref(); useeffect(() => { ref.current = value; }); re
turn ref.current; } now add the following, above the re
turn statement inside the app() function: const prevtasklength = useprevious(tasks.length); here we are invoking useprevious() to track the length of the tasks state, like so: note: since we're now utilizing useprevious() in two files, a good efficiency refactor would be to move the useprevious() function into its own file, export it from tha...
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:...
... add isediting below your existing isdone data point: data() { re
turn { isdone: this.done, isediting: false }; } now add your methods inside a methods property, right below your data() property: methods: { deletetodo() { this.$emit('item-deleted'); }, toggletoitemeditform() { this.isediting = true; } } conditionally displaying components via v:if and v:else now we have an isediting flag that we can use to signify that the...
... 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.
... result: toggletoitemeditform() method is invoked, which toggles this.isediting to true, which in
turn displays the todo item's edit form on re-render.
Rendering a list of Vue components - Learn web development
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.
... your app.vue <script> element contents should now look like this: import todoitem from './components/todoitem.vue'; import uniqueid from 'lodash.uniqueid' export default { name: 'app', components: { todoitem }, data() { re
turn { todoitems: [ { id: uniqueid('todo-'), label: 'learn vue', done: false }, { id: uniqueid('todo-'), label: 'create a vue project with the cli', done: true }, { id: uniqueid('todo-'), label: 'have fun', done: true }, { id: uniqueid('todo-'), label: 'create a to-do list', done: false } ] }; } }; now, add the v-for directive and key attribute t...
...instead of generating the id for the checkboxes inside your todoitem component, we can
turn the id into a prop.
... 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.
Application cache implementation overview
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.
...this re
turns the top level document the whole load group is bound to.
... note: the processnexturi method early re
turns when state of the update is different then downloading.
... on finished state loadcompleted just early re
turns.
A bird's-eye view of the Mozilla framework
if nsirdfnode doesn't support nsirdfliteral, it re
turns null and it's up to the client to choose an alternate course of action.
... 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.
Displaying Places information using views
(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.
... switch (acol.id || acol.element.getattribute("anonid")) { // uri for all nodes (like folders), not just uri nodes (like bookmarks) case "fulluri": re
turn this.nodefortreeindex(arowindex).uri; break; // index of node in parent container case "indexinparent": re
turn this.nodefortreeindex(arowindex).bookmarkindex; break; // is the row even or odd?
... case "parity": re
turn (arowindex % 2 === 0 ?
... re
turn this._getcelltext(arowindex, acol); }; view._cycleheader = view.cycleheader; view.cycleheader = function (acol) { switch (acol.id || acol.element.getattribute("anonid")) { case "fulluri": case "indexinparent": case "parity": // you might resort by column here.
Cross Process Object Wrappers
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.
...when you access a property of the wrapper, it sends a synchronous message to the content process and re
turns the result.
...we know it's blocked waiting for the synchronous message to re
turn, and we know that won't change during the cpow call.
PopupNotifications.jsm
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.
... re
turn value the corresponding notification object, or null if no such notification exists.
... re
turn value re
turns the notification object corresponding to the added notification.
...the anchorelement property re
turns the notification's anchor element.
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.
...for example, the equivalent of var deferred = promise.defer(); dosomething(function cb(good) { if (good) deferred.resolve(); else deferred.reject(); }); re
turn deferred.promise; would be re
turn new promise(function(resolve, reject) { dosomething(function cb(good) { if (good) resolve(); else reject(); }); }); method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly cr...
... function deferred() { // update 062115 for typeof if (typeof(promise) != 'undefined' && promise.defer) { //need import of promise.jsm for example: cu.import('resource:/gree/modules/promise.jsm'); re
turn promise.defer(); } else if (typeof(promiseutils) != 'undefined' && promiseutils.defer) { //need import of promiseutils.jsm for example: cu.import('resource:/gree/modules/promiseutils.jsm'); re
turn promiseutils.defer(); } else { /* a method to resolve the associated promise with the value passed.
...} } and use this function as would promise.defer: function funcwithdefer() { var deferred = new deferred(); var promise = deferred.promise; promise.then( function(aval) { console.log('fullfilled - ', aval); }, function(areason) { console.error('rejected - areason:', areason) } ); //deferred.resolve('aval of resolved'); deferred.reject('reject val'); re
turn promise; } var promise_funcwithdefer = funcwithdefer(); promise_funcwithdefer.then( function(aval) { console.log('fullfilled - promise_funcwithdefer - ', aval); }, function(areason) { var refobj = {name:'promise_funcwithdefer', areason:areason}; console.error('rejected - promise_funcwithdefer - ', refobj); } ).catch( function(acatch) { console.error('caught - promise_fu...
SourceMap.jsm
sourcemapconsumer.prototype.originalpositionfor(generatedposition) re
turns the original source, line, and column information for the generated source's line and column positions provided.
... and an object is re
turned with the following properties: source: the original source file, or null if this information is not available.
... sourcenode.prototype.tostring() re
turn the string representation of this source node.
... 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.
Localization and Plurals
/** * get the correct plural form of a word based on the number * * @param anum * the number to decide which plural form to use * @param awords * a semi-colon (;) separated string of words to pick the plural form * @re
turn the appropriate plural form of the word */ string pluralform get(int anum, string awords) here is an example of using this method: // load pluralform and for this example, assume english components.utils.import("resource://gre/modules/pluralform.jsm"); // pluralform.get expects a semi-colon separated list of words let downloads = "download;downloads"; // pretend this number came from somewher...
... * * @param arulenum * the plural rule number to create functions * @re
turn a pair: [function that gets the right plural form, * function that re
turns the number of plural forms] */ [string pluralform get(int anum, string awords), int numforms numforms()] makegetter(int arulenum) here is an example usage of makegetter: components.utils.import("resource://gre/modules/pluralform.jsm"); // let's get irish (plural rule #11) let [get, numforms] = pluralf...
...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.
Creating localizable web applications
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) ?
...this is useful for strings occurring in the webapp multiple times, like "re
turn to top", "comments", "click to see larger image" etc.
...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.
...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.
TraceMalloc
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!).
Creating a Cookie Log
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).
NSPR Types
miscellaneous types are used for representing size, pointer difference, boolean values, and re
turn values.
... here are some simple examples of the use of these types: in dowhim.h: pr_extern( void ) dowhatimean( void ); static void pr_callback rootfunction(void *arg); in dowhim.c: pr_implement( void ) dowhatimean( void ) { re
turn; }; prthread *thread = pr_createthread(..., rootfunction, ...); algebraic types nspr provides the following type definitions with unambiguous bit widths for algebraic operations: 8-, 16-, and 32-bit integer types 64-bit integer types floating-point number type for convenience, nspr also provides type definitions with platform-dependent bit widths: native os integer types 8-, 16-,...
... printn pruintn miscellaneous types size type pointer difference types boolean types status type for re
turn values size type prsize pointer difference types types for pointer difference.
... prbool prpackedbool status type for re
turn values prstatus ...
PL_HashTableLookup
looks up the entry with the specified key and re
turn its value.
... 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.
PR_FindSymbol
pr_findsymbol() will re
turn an untyped reference to a symbol in a 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.
... re
turns an untyped pointer.
... description this function finds and re
turns an untyped reference to the specified symbol in the specified library.
PR_GetLibraryName
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.
... re
turns if successful, re
turns a new character string containing a constructed path name.
... in case of error, re
turns null.
... if sufficient storage cannot be allocated to contain the constructed path name, the function re
turns null.
PR_GetLibraryPath
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.
PR_Initialize
re
turning from prmain leads to termination of the process.
... re
turns the value re
turned from the root function, prmain.
...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.
PR_Now
re
turns the current time.
... re
turns the current time as a prtime value.
... description pr_now() re
turns the current time as number of microseconds since the nspr epoch, which is midnight (00:00:00) 1 january 1970 utc.
... you cannot assume that the values re
turned by pr_now() are monotonically increasing because the system clock of the computer may be reset.
PR_Writev
re
turns one of the following values: a positive number indicates the number of bytes successfully written.
...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.
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.
...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.
... re
turns full description of the re
turn value, for example: a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found.
NSS 3.12.4 release notes
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 ?
... bug 321755: implement crldistributionpoint extension in libpkix bug 391434: avoid multiple encoding/decoding of pkix_pl_oid to and from ascii string bug 405297: problems building nss/lib/ckfw/capi/ with mingw gcc bug 420991: libpkix re
turns wrong nss error code bug 427135: add super-h (sh3,4) architecture support bug 431958: improve des and sha512 for x86_64 platform bug 433791: win16 support should be deleted from nss bug 449332: secu_parsecommandline does not validate its inputs bug 453735: when using cert9 (sqlite3) db, set or change master password fails bug 463544: warning: passing enum* for an int* argument in pkix_validate.c...
...plemented on os/2 bug 493912: sqlite3_reset should be invoked in sdb_findobjectsinit when error occurs bug 494073: update rsa/dsa powerupself tests to be compliant for 2011 bug 494087: passing null as the value of cert_pi_trustanchors causes a crash in cert_pkixsetparam bug 494107: during nss_nodb_init(), softoken tries but fails to load libsqlite3.so crash [@ @0x0 ] bug 495097: sdb_mapsqlerror re
turns signed int bug 495103: nss_initreadwrite(sql:<dbdir>) causes nss to look for sql:<dbdir>/libnssckbi.so bug 495365: add const to the 'nickname' parameter of sec_certnicknameconflict bug 495656: nss_initreadwrite(sql:<configdir>) leaves behind a pkcs11.txu file if libnssckbi.so is in <configdir>.
...bug 505858: nss_registershutdown can re
turn without unlocking nssshutdownlist.lock bug 507041: invalid build options for vc6 bug 507228: coreconf.dep doesn't need to contain the nss version number bug 507422: crash [[@ port_freearena - lg_mksecretkeyrep] when port_newarena fails bug 507482: nss 3.12.3 (and later) doesn't build on aix 5.1 bug 507937: pwdecrypt program problems bug 508259: pk11mode crashed on linux2.4 bug 508467: libpkix ocs...
NSS 3.21 release notes
the re
turned strings must be freed by the caller.
... 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.
...(c) kasım 2005 sha-1 fingerprint: b4:35:d4:e1:11:9d:1c:66:90:a7:49:eb:b3:94:bd:63:7b:a7:82:b7 the following ca certificate had the websites trust bit
turned off ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a the following ca certificates were added cn = certification authority of wosign g2 sha1 fingerprint: fb:ed:dc:90:65:b7:27:20:37:bc:55:0c:9c:56:de:bb:f2:78:94:e1 cn = ca wosign ecc root sha1 fingerprint: ...
...d2:7a:d2:be:ed:94:c0:a1:3c:c7:25:21:ea:5d:71:be:81:19:f3:2b cn = oiste wisekey global root gb ca sha1 fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed the version number of the updated root ca list has been set to 2.6 bugs fixed in nss 3.21 this bugzilla query re
turns all the bugs fixed in nss 3.21: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.21 acknowledgements the nss development team would like to thank karthikeyan bhargavan from inria for responsibly disclosing the issue in bug 1158489.
NSS 3.31 release notes
pk11uri_parseuri - parse pkcs#11 uri and re
turn a new pk11uri object.
... 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.
... 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.
NSS 3.35 release notes
the websites (tls/ssl) trust bit was
turned off for the following ca certificates: cn = chambers of commerce root sha-256 fingerprint: 0c:25:8a:12:a5:67:4a:ef:25:f2:8b:a7:dc:fa:ec:ee:a3:48:e5:41:e6:f5:cc:4e:e6:3b:71:b3:61:60:6a:c3 cn = global chambersign root sha-256 fingerprint: ef:3c:b4:17:fc:8e:bf:6f:97:87:6c:9e:4e:ce:39:de:1e:a5:fe:64:91:41:d1:02:8b:7d:11:c0:b2:29:8c:ed significant...
... 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.
... 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.
NSS Sample Code sample6
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.
... */ 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*/, &keyiditem, pr_true, 0); if (key == null) { fprintf(stderr, "pk11_tokenkeygen failed (err %d)\n", pr_geterror()); pk11_freeslot(slot); re
turn; } fprintf(stderr, "key length of generated key is %d\n", pk11_getkeylength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", pk11_getmechanism(key), ciphermech); pk11_freesymkey(key); key = pk11_findfixedkey(slot, ciphermech, &keyiditem, 0); if (key == null) { fprintf(stderr, "pk11_findfixedkey failed (err %d)\n", pr_geterror()); pk11_freeslot(sl...
...ot); re
turn; } fprintf(stderr, "found key!\n"); fprintf(stderr, "key length of generated key is %d\n", pk11_getkeylength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", pk11_getmechanism(key), ciphermech); pk11_freesymkey(key); pk11_freeslot(slot); } char *passwdcb(pk11slotinfo *info, prbool retry, void *arg) { if (!retry) re
turn pl_strdup("test"); else re
turn null; } ...
FC_GetTokenInfo
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.
... re
turn value ckr_ok token information was successfully copied.
... fc_gettokeninfo should re
turn ckr_arguments_bad if pinfo is null.
ssltyp.html
secstatus the re
turn value for many ssl functions.
...in this case the value re
turned by pr_geterror is meaningless.
... re
turns the function re
turns one of these values: if successful, secsuccess.
... re
turns the function re
turns one of these values: if successful, secsuccess.
Pork Tools
outparamdel outparamdel converts functions to re
turn via re
turn value instead of an outparam.
... 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 = ...
... if (result) re
turn nsnull; // error re
turns are changed to nsnull //instead ns_ok, actual result is re
turned re
turn result; } caller1 { //case 1 nsresult rv; rv = getter(&var); ns_ensure_success(rv,rv); //case 2: naked call getter(&var); //case 3: nsresult decl nsresult rv2 = getter(&var); ns_ensure_success(rv2,rv2); } caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam call + ns_ensure_success.
...o lhs var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_error_failure) } outparamdel also support rewriting getters such that they re
turn already_addrefed<nsifoo>.
Scripting Java
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.
... public class overload { public string f(object o) { re
turn "f(object)"; } public string f(string s) { re
turn "f(string)"; } public string f(int i) { re
turn "f(int)"; } public string g(string s, int i) { re
turn "g(string,int)"; } public string g(int i, string s) { re
turn "g(int,string)"; } public static void main(string[] args) { overload o = new overload(); object[] a = new object[] { new integer(3), "hi", overloa...
...n be used to query the type of an exception: try { java.lang.class.forname("nonexistingclass"); } catch (e) { if (e.javaexception instanceof java.lang.classnotfoundexception) { print("class not found"); } } rhino also supports an extension to the try...catch statement that allows to define conditional catching of exceptions: function classforname(name) { try { re
turn java.lang.class.forname(name); } catch (e if e.javaexception instanceof java.lang.classnotfoundexception) { print("class " + name + " not found"); } catch (e if e.javaexception instanceof java.lang.nullpointerexception) { print("class name is null"); } } classforname("nonexistingclass"); classforname(null); ...
JIT Optimization Outcomes
needstypebarrier optimization failed because somehow the property was accessed in a way that re
turned a different type than the expected constant.
...objects which are used in ways that suggest they are hashtables are
turned into dictionary objects and their types marked as such.
...for example, function f() { var x; re
turn function () { x++; } } closes over x in f.
...it lacks observed type information for its arguments, its re
turn value, or both.
JSErrorReport
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.
JS_GetFunctionObject
description js_getfunctionobject re
turns the javascript function object for a specified function pointer, fun.
...in other cases, the object re
turned by js_getfunctionobject is not necessarily safe to call and should not be exposed to script.
...calling the jsobject re
turned by it could cause a crash or worse.
... js_getfunctionobject always re
turns a pointer to an object.
JS_GetInstancePrivate
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 mismatch error before re
turning null.
JS_GetScopeChain
description js_getscopechain re
turns the first jsobject on the scope chain for the javascript code currently running in the given context, cx.
... 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.
JS_InstanceOf
js_instanceof re
turns true if obj is of the given class and false otherwise.
... that is, it re
turns js_getclass(obj) == clasp.
...if obj is of the given class, it re
turns true.
... otherwise, it re
turns false; it also reports a typeerror containing the function's name.
JS_InternString
description js_internstring and js_internstringn re
turn an interned javascript string with a specified value, s.
...if an interned string already exists with the desired value, these functions re
turn the existing string.
...on success, these functions re
turn a pointer to the interned string.
... otherwise they report an error and re
turn null.
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.
... js_mapgcroots re
turns the count of roots that were successfully mapped.
JS_NewScriptObject
re
turn the javascript script object that wraps a compiled script.
... description js_newscriptobject re
turns the script object associated with the given jsscript.
... on success, js_newscriptobject re
turns a pointer to the script's object.
... otherwise it re
turns null.
JS_PreventExtensions
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.
... 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.
... 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.
JS_SetElement
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.
JS_SetGCCallback
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.
...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.
JS_SetPropertyAttributes
if js_setpropertyattributes cannot locate an object with the specified property, it re
turns js_false, and the value left in *foundp is undefined.
...then, if the property exists, but is associated with a different object, js_setpropertyattributes re
turns js_true.
...if the attributes can be set, js_setpropertyattributes re
turns js_true.
... if not, it re
turns js_false.
JS_ValueToFunction
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.
... 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.
Fun With XBL and XPConnect
now accesses to autocompletesession will re
turn the xp-connect 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.
...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.
... <handlers> <handler type="keypress" keycode="vk_re
turn" value="autocomplete(anonymouscontent[0].value, this.autocompletelistener);"/> </handlers> </implementation> </binding> original document information author(s): scott macgregor last updated date: april 13, 2000 copyright information: copyright (c) scott macgregor ...
Generic factory
*/ 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.
... for this class, simply write the following: nsifactory* newcomponentfactory(nsirepository* repository) { nsigenericfactory* factory = null; nscid kgenericfactorycid = ns_genericfactory_cid; nsresult res = repository->createinstance(kgenericfactorycid, null, nsigenericfactory::iid(), &factory); if (res == ns_ok) { factory->setconstructor(&mycomponent::create); } re
turn factory; } this example assumes that the xpcom repository is available as an interface (which it soon will be).
...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(); ...
... 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.
How to build an XPCOM component in JavaScript
implementation this example component will expose a single method, which re
turns the string "hello world!".
...if not // provided, the default factory is used, which re
turns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
... // 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.
...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
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).
... ns_shutdownxpcom re
turns and the application may exit normally.
...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.
... « previousnext » copyright (c) 2003 by doug
turner and ian oeschger.
Using XPCOM Components
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.
... managing cookies from cpp nscomptr<nsiservicemanager> servman; nsresult rv = ns_getservicemanager(getter_addrefs(servman)); if (ns_failed(rv)) re
turn -1; nscomptr<nsicookiemanager> cookiemanager; rv = servman->getservicebycontractid("@mozilla.org/cookiemanager", ns_get_iid(nsicookiemanager), getter_addrefs(cookiemanager)); if (ns_failed(rv)) re
turn -1; pruint32 len; deletedcookies->getlength(&len); for (int c=0; c<len; c++) cookiemanager->remove(deletedcookies[...
...to instantiate an xpcom component in javascript, you create a new component object and pass in the contract id for the component you want and ask for either a singleton or an instance of that component to be re
turned: var cmgr = components.classes["@mozilla.org/cookiemanager;1"] .getservice(); the resulting cookiemanager object then provides access to all of the methods for that component that have been defined in idl and compiled into the type library.
... « previousnext » copyright (c) 2003 by doug
turner and ian oeschger.
XPCOM Stream Guide
primitive output streams type native class contract id interface how to bind to a data target generic nsstoragestream @mozilla.org/storagestream;1 nsistoragestream stream.getoutputstream(); // re
turns nsioutputstream file nsfileoutputstream @mozilla.org/network/file-output-stream;1 nsifileoutputstream stream.init(file, ioflags, perm, behaviorflags); file nssafefileoutputstream @mozilla.org/network/safe-file-output-stream;1 nsisafefileoutputstream, nsifileoutputstream stream.init(file, ioflags, perm, behaviorflags); channels have s...
...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...
... */ 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.
How to build a binary XPCOM component using Visual Studio
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.
...the interface defines the methods, including arguments and re
turn types, of the component.
...string mname; }; #endif cpp file: #include "comp-impl.h" ns_impl_isupports1(cspecialthing, ispecialthing) cspecialthing::cspecialthing() { /* member initializers and constructor code */ mname.assign(l"default name"); } cspecialthing::~cspecialthing() { /* destructor code */ } /* attribute astring name; */ ns_imethodimp cspecialthing::getname(nsastring & aname) { aname.assign(mname); re
turn ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & aname) { mname.assign(aname); re
turn ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::add(print32 a, print32 b, print32 *_retval) { *_retval = a + b; re
turn ns_ok; } lastly, we need to create the module implementation.
... use in javascript: function doxpcom() { try { const cid = "@starkravingfinkle.org/specialthing;1"; var obj = components.classes[cid].createinstance(); obj = obj.queryinterface(components.interfaces.ispecialthing); } catch (err) { alert(err); re
turn; } var res = obj.add(3, 4); alert('3+4 = ' + res); var name = obj.name; alert('name = ' + name); obj.name = 'new name'; name = obj.name; alert('name = ' + name); } other resources creating xpcom components - mozilla how to build an xpcom component in javascript - mozilla an introduction to xpcom - ibm xpcom project page - mozilla ...
Components.Constructor
another 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.
...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.
... 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; } ...
NS_GetComponentManager
« xpcom api reference summary the ns_getcomponentmanager function re
turns a reference to the xpcom component manager.
... re
turn values the ns_getcomponentmanager function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
... remarks the object re
turned is a singleton that is valid until ns_shutdownxpcom is called.
NS_GetComponentRegistrar
« xpcom api reference summary the ns_getcomponentregistrar function re
turns a reference to the xpcom component registrar.
... re
turn values the ns_getcomponentregistrar function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
... remarks the object re
turned is a singleton that is valid until ns_shutdownxpcom is called.
NS_GetMemoryManager
« xpcom api reference summary the ns_getmemorymanager function re
turns a reference to the xpcom memory manager.
... re
turn values the ns_getmemorymanager function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
... remarks the object re
turned is a singleton that is valid until ns_shutdownxpcom is called.
NS_GetServiceManager
« xpcom api reference summary the ns_getservicemanager function re
turns a reference to the xpcom service manager.
... re
turn values the ns_getservicemanager function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
... remarks the object re
turned is a singleton that is valid until ns_shutdownxpcom is called.
NS_InitXPCOM2
you may pass null if you are not interested in this re
turn value.
...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.
... re
turn values the ns_initxpcom2 function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
NS_InitXPCOM3
you may pass null if you are not interested in this re
turn value.
...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.
... re
turn values the ns_initxpcom3 function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
NS_NewLocalFile
re
turn values the ns_newlocalfile function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
...this error is re
turned if a relative file path is passed to ns_newlocalfile.
... 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.
NS_NewNativeLocalFile
re
turn values the ns_newnativelocalfile function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
...this error is re
turned if a relative file path is passed to ns_newnativelocalfile.
... 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.
NS_ShutdownXPCOM
#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.
...once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to re
turn object instances.
nsACString_internal
the caller must not modify the characters at the re
turned address.
... @re
turns the length of the buffer in characters.
... 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.
operator+=
re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
nsAString_internal
the caller must not modify the characters at the re
turned address.
... @re
turns the length of the buffer in characters.
... 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.
nsDependentCSubstring
the caller must not modify the characters at the re
turned address.
... @re
turns the length of the buffer in characters.
... 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.
nsDependentSubstring
the caller must not modify the characters at the re
turned address.
... @re
turns the length of the buffer in characters.
... 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.
operator=
re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
operator=
re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
mozIStorageFunction
re
turn value an nsivariant this is the re
turn value of the function.
... 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.
...var squarefunction = { onfunctioncall: function(aarguments) { let value = aarguments.getint32(0); re
turn value * value; } }; // now, register our function with the database connection.
... nsivariant **_result) { print32 value; nsresult rv = aarguments->getint32(&value); ns_ensure_success(rv, rv); nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_error_out_of_memory); rv = result->setasint64(value * value); ns_ensure_success(rv, rv); ns_addref(*_result = result); re
turn ns_ok; } }; // now, register our function with the database connection.
GetChildAt
« nsiaccessible page summary this method re
turns nth accessible child using zero-based index.
...re
turn value re
turns nth accessible child using zero-based index.
... if child index is less than zero then re
turns last child.
... if child index is greater than children count then re
turns null.
GetChildAtPoint
« nsiaccessible page summary this method re
turns an accessible child which contains the coordinate at (x, y) in screen pixels.
...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.
nsIChannel
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 asyncopen re
turns successfully, the channel is responsible for keeping itself alive until it has called onstoprequest on alistener or called onchannelredirect.
... re
turn value blocking input stream to the channel's data.
nsIChromeRegistry
a new nsiuri is re
turned; the original is left unmodified.
... 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.
... re
turn value true if xpcnativewrappers are enabled for the specified uri; otherwise false.
nsIClipboardDragDropHooks
re
turn value true indicates to the operating system that if a drop does happen on this browser, it will be accepted.
... re
turn value true if the drag can proceed.
... re
turn value true to indicate that copy/drag can proceed.
... re
turn value true to indicate the action was handled, do not perform built-in behavior.
nsIConsoleService
if no messages are logged, this function will re
turn a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when called from the script.
...if no messages are logged, this function will re
turn a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when called from the script.
... examples retrieving the message array to retrieve the message array in gecko prior to version 19: function getconsolemessagearray() { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .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 message a common usage is logging a message string to the console: function log(msg) { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); consoleservice.logstringmessage(msg); } alternative logging methods include components.utils.reporterror and dump().
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() boolean issupported( in domstring feature, in domstring version ); parameters feature version re
turn value normalize() void normalize(); parameters none.
... removechild() nsidomnode removechild( in nsidomnode oldchild ); parameters oldchild re
turn value replacechild() nsidomnode replacechild( in nsidomnode newchild, in nsidomnode oldchild ); parameters newchild oldchild re
turn value see also document object model (dom) level 2 core specificationrec ...
nsIDOMWindow
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.
... 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.
... re
turn value the nsiselection object for the window.
nsIDirectoryServiceProvider2
xpcom/io/nsidirectoryservice.idlscriptable an extension of nsidirectoryserviceprovider which allows multiple files to be re
turned for the given key.
... re
turn value an enumerator for a list of file locations.
...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).
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.
... methods getdebugobject() re
turns the debugger object if the debug service is active.
...re
turn value if jsdidebuggerservice is active and the listener is implemented in js, this re
turns the listener as a jsdivalue.
...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++).
nsIEventTarget
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.
...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.
nsIFileView
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.
... showonlydirectories boolean if true only directory entries will be re
turned.
... setfilter() set the filter to be applied to the file list, for example "*.jpg" would only re
turn jpg files.
nsIFormHistory2
g value); boolean entryexists(in astring name, in astring value); boolean nameexists(in astring name); 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.
... hasentries boolean re
turns true if the form history has any entries.
...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.
nsIFrameScriptLoader
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>].
nsILoginInfo
methods clone() re
turns a clone of this login.
... re
turn value an nsilogininfo containing a clone of the login on which this method was invoked.
... re
turn value true if the two logins are exactly equal or false if they're not.
... re
turn value true if the two logins are equivilant or false if they're not.
nsILoginManagerCrypto
methods decrypt() decrypts the specified string, re
turning the plain text value.
... re
turn value the decrypted string.
... encrypt() encrypts the specified string, re
turning the ciphertext value.
... re
turn value the encrypted string.
nsIMicrosummaryGenerator
if the generator doesn't specify an interval, null is re
turned.
... re
turn value the interval in milliseconds until the next update request.
... re
turn value a boolean indicating if the two generators are equal.
... re
turn value the text result of processing the template.
nsIModule
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 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.
nsIPermissionManager
re
turn value a pruint32 representing the permission, or unknown_action if no permission exists.
... re
turn value a pruint32 representing the permission, or unknown_action if no permission exists.
... re
turn value a pruint32 representing the permission, or unknown_action if no permission exists.
... re
turn value a pruint32 representing the permission, or unknown_action if no permission exists.
nsIPrefService
when using a get method a user set value will be re
turned if one exists, otherwise a default value will be re
turned.
... re
turn value nsiprefbranch - the object representing the requested branch.
...when using a get method a default value will always be re
turned.
... re
turn value nsiprefbranch - the object representing the requested default branch.
nsIProcessScriptLoader
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].
nsIProfile
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.
... re
turn value true if there is a profile with the specified name.
nsIProtocolHandler
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.
... re
turn value re
turn true if the override is approved; otherwise, re
turn false.
... re
turn value re
turn the newly constructed channel.
... re
turn value the new uri object suitable for loading using the protocol.
nsIPushSubscription
methods getkey() re
turns a byte array containing the key material for this subscription.
...when called from javascript, nsipushsubscription.getkey() only takes name as a parameter, and re
turns key.
... bool quotaapplies(); nsipushsubscription.quotaapplies() always re
turns false for system subscriptions.
... bool isexpired(); nsipushsubscription.isexpired() always re
turns false for system subscriptions.
nsISimpleEnumerator
must be preceded by a call to hasmoreelements() which re
turns pr_true.
...re
turn value ns_ok if the call succeeded in re
turning a non-null value through the out parameter.
...hasmoreelements() called to determine whether or not the enumerator has any elements that can be re
turned via getnext().
...re
turn value pr_true if there are remaining elements in the enumerator.
nsIStringBundleService
chrome://global/locale/global.properties re
turn value a string bundle corresponding to the properties file.
... on the re
turn value object on you can call functions like getstringfromname and formatstringfromname see nsistringbundle.
... re
turn value an extensible bundle corresponding to the properties file(s).
... re
turn value the formatted message.
nsIStringEnumerator
must be preceded by a call to hasmoreelements() which re
turns pr_true.
...re
turn value the next string in the enumerator.
...hasmore() called to determine whether or not the enumerator has any strings that can be re
turned via getnext().
...re
turn value true if there are remaining strings in the enumerator.
nsITaskbarPreviewController
re
turn value true if you want a frame drawn around the preview, otherwise false.
... re
turn value true if you want a frame drawn around the thumbnail, otherwise false.
... re
turn value true if the top level window corresponding to the preview should be activated, false if activation is not accepted.
...this can be compared to the buttons re
turned by the nsitaskbarwindowpreview.getbutton().
nsIThreadManager
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.
... re
turn value the nsithread matching the specified prthread, or null if there is no matching nsithread.
... re
turn value the newly created nsithread.
nsIToolkitProfileService
this will always re
turn 0, 1, or 2; if there are more than 2 profiles, 2 is always re
turned.
... re
turn value an nsitoolkitprofile object representing the newly-created profile.
... re
turn value an nsitoolkitprofile object describing the specified profile.
... re
turn value an nsiprofilelock object representing the locked directory.
nsITransport
this means that if the stream has no data and is not closed, then reading from it re
turns ns_base_stream_would_block.
... re
turn value openoutputstream() open an output stream on this transport.
...this means that if the stream is full and is not closed, then writing to it re
turns ns_base_stream_would_block.
... re
turn value seteventsink() set the transport event sink.
nsITreeSelection
getrangeat() re
turns two objects whose value properties represent the minimum and maximum indices of the given selection range.
... getrangecount() re
turns a count of selection ranges.
...re
turn value long - number of selection ranges invalidateselection() can be used to invalidate the selection.
... re
turn value rangedselect() select the range specified by the indices.
Storage
no results to be re
turned if you do not need to get any results back, you can use mozistorageconnection.executesimplesql() api like this in javascript: dbconn.executesimplesql("create temp table table_name (column_name integer)"); similarly, the c++ looks like this: rv = mdbconn->executesimplesql(ns_literal_cstring("create temp table table_name (column_name integer)")); ns_ensure_success(rv, rv); results to be ret...
... 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.
...if your function re
turns without calling commit on the helper object, the transaction will be rolled back.
... re
turn transaction.commit(); } collation (sorting) sqlite provides several collation methods (binary, nocase, and rtrim), but these are all very simple and have no support for various text encodings or the user's locale.
Using the clipboard
const nssupportsstring = components.constructor("@mozilla.org/supports-string;1", "nsisupportsstring"); function supportsstring(str) { // create an instance of the supports-string class var res = nssupportsstring(); // store the javascript string that we want to wrap in the new nsisupportsstring object res.data = str; re
turn res; } // create a constructor for the built-in transferable class const nstransferable = components.constructor("@mozilla.org/widget/transferable;1", "nsitransferable"); // create a wrapper to construct an nsitransferable instance and set its source to the given window, when necessary function transferable(source) { var res = nstransferable(); if ('init' in res) { // when passe...
... if (source instanceof ci.nsidomwindow) // note: in gecko versions >16, you can import the privatebrowsingutils.jsm module // and use privatebrowsingutils.privacycontextfromwindow(sourcewindow) instead source = source.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation); res.init(source); } re
turn res; } here, the string "text to copy" will be copied but you can replace this with the text string that you want to copy.
... services.clipboard.setdata(trans, null, services.clipboard.kglobalclipboard); re
turn true; } pasting clipboard contents to paste data from the clipboard we can use a similar process, except we use getdata instead of setdata and gettransferdata instead of settransferdata.
...next we create two javascript objects which will hold the re
turn values from gettransferdata.
Weak reference
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; } // ...
...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.
... 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.
Gloda examples
a) show all messages in a conversation regardless of the folder in which they are stored, b) search messages by subject assuming that you have a message (glodamessage) in the conversation already, this is straight forward using glodamessage.conversation.getmessagescollection() alistener = { /* 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(...
...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(...
... this requires two chained asynchronous calls: //first take an email address and
turn it into an identity object id_q = gloda.newquery(gloda.noun_identity); id_q.kind("email"); id_q.value("test@example.com"); id_coll = id_q.getcollection({ onitemsadded: function _onitemsadded(aitems, acollection) { }, onitemsmodified: function _onitemsmodified(aitems, acollection) { }, onitemsremoved: function _onitems...
...removed(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 freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items tha...
Activity Manager examples
// 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 ...
...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...
...e = do_queryinterface(ptr); if (copyservice) copyservice->undo(folder); } re
turn (*result = ns_ok); } ///////////////////////////////////////////////////////////////////////////// //// creating an undoable copy event nscomptr<nsiactivityundohandler> undohandler = new mycopyeventundo(); nscomptr<nsiactivityevent> copyevent(do_createinstance("@mozilla.org/activity-event;1")); // the initiator of this particular event is copyservice.
...er.prototype = { getcontextdisplaytext: function(contexttype, contextobj) { // in this particular example we know that contexttype is "sender" // since we also pass the contexttype along with the contextobject // in some cases, one helper can be registered for a group of context types // we know that the context object is the author of the message // localization is omitted re
turn "messages coming from " + contextobj.surname + ", " + contextobj.firstname; } } // step 2: register the helper for this context type gactivitymanager.registercontextdisplayhelper("sender", new sendercontextdisplayhelper()); // step 3: create the process ...
Declaring and Calling Functions
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.
... 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).
ABI
method overview string tosource() string tostring() methods tosource() re
turns the string "ctypes.***_abi".
... re
turn value a javascript expression that evaluates to the abi.
... tostring() re
turns a string identifying the abi.
... re
turn value a string identifying the abi.
Mozilla
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.
... error codes re
turned by mozilla apis the following tables list errors that can occur when calling various mozilla apis.
...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.
Set a breakpoint - Firefox Developer Tools
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.
... other context menu options worth mentioning are: disable breakpoint:
turn it off, but don't remove it completely.
... if the breakpoint is an unconditional breakpoint, you'll get an option add condition, which allows you to
turn it into a conditional breakpoint.
... 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.
Network request list - Firefox Developer Tools
here is a list of all available columns: status: the http status code re
turned.
... 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.
... enter a string in the search field of the sidebar, and press enter or re
turn.
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
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).
... unchecking the "display line numbers" box
turns them off.
... unchecking the "display area names" box
turns them off.
Sorting algorithms comparison - Firefox Developer Tools
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.
Attr.localName - Web APIs
the attr.localname read-only property re
turns the local part of the qualified name of an attribute.
... syntax name = attribute.localname re
turn value a domstring representing the local part of the attribute's qualified name.
... 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.
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.
... re
turn value a mediastreamtrackaudiosourcenode object which acts as a source for audio data found in the specified audio track.
...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().
...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.
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.
... 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 current audio context.
... audiocontext.getoutputtimestamp() re
turns a new audiotimestamp object containing two audio timestamp values relating to the current audio context.
AudioNode.connect() - Web APIs
it is possible to connect an audionode to another audionode, which in
turn connects back to the first audionode, creating a cycle.
... 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.
AudioTrack.label - Web APIs
the read-only audiotrack property label re
turns a string specifying the audio track's human-readable label, if one is available; otherwise, it re
turns an empty string.
...otherwise, an empty string ("") is re
turned.
... 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.
... 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.
AudioTrack - Web APIs
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().
... 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.
... 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.
AudioWorkletGlobalScope - Web APIs
properties currentframe read only re
turns an integer that represents the ever-increasing current sample-frame of the audio block being processed.
... currenttime read only re
turns a double that represents the ever-increasing context time of the audio block being processed.
... samplerate read only re
turns a float that represents the sample rate of the associated baseaudiocontext.
...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 - Web APIs
audioworkletnode.port read only re
turns a messageport used for bidirectional communication between the node and its associated audioworkletprocessor.
... audioworkletnode.parameters read only re
turns an audioparammap — a collection of audioparam objects.
...if the audioworkletprocessor has a static parameterdescriptors getter, the audioparamdescriptor array re
turned from it is used to create audioparam objects on the audioworkletnode.
... // 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.
AudioWorkletProcessor - Web APIs
in
turn, an audioworkletnode based on it runs on the main thread.
... properties port read only re
turns a messageport used for bidirectional communication between the processor and the audioworkletnode which it belongs to.
...the array of audioparamdescriptor-based objects re
turned is used internally to create the audioparams during the instantiation of the audioworkletnode.
... // 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.
Bluetooth.getAvailability() - Web APIs
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.
... re
turn value a promise that resolves with boolean.
Body.arrayBuffer() - Web APIs
it re
turns a promise that resolves with an arraybuffer.
... re
turn value a promise that resolves with an arraybuffer.
... once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) function getdata() { source = audioctx.createbuffersource(); var myrequest = new request('viper.ogg'); fetch(myrequest).then(function(response) { re
turn response.arraybuffer(); }).then(function(buffer) { audioctx.decodeaudiodata(buffer, function(decodeddata) { source.buffer = decodeddata; source.connect(audioctx.destination); }); }); }; // wire up buttons to stop and play audio play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); } reading files the response() constru...
... function readfile(file) { re
turn new response(file).arraybuffer(); } <input type="file" onchange="readfile(this.files[0])"> specifications specification status comment fetchthe definition of 'arraybuffer()' in that specification.
CSSKeyframesRule - Web APIs
csskeyframesrule.cssrules read only re
turns a cssrulelist of the css rules in the media rule.
... 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.
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.
... re
turn value value is a cssvalue containing the css value for a property.
... if none exists, re
turns null.
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.
... 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.
CSSUnparsedValue - Web APIs
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.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.
Determining the dimensions of elements - Web APIs
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.
...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 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.
... re
turn value a promise that resolves with undefined.
... 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.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.
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.
... re
turn value a promise that resolves to true if the cache object is found and deleted, and false otherwise.
...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.
... 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.
CacheStorage.keys() - Web APIs
the keys() method of the cachestorage interface re
turns a promise that 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.
... re
turn value a promise that resolves with an array of the cache names inside the cachestorage object.
...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.
... 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.
CacheStorage.open() - Web APIs
the open() method of the cachestorage interface re
turns a promise that resolves to the cache object matching the cachename.
... note: if the specified cache does not exist, a new cache is created with that cachename and a promise that resolves to this new cache object is re
turned.
... re
turn value a promise that resolves to the requested cache object.
... self.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { re
turn cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); specifications specification ...
Clients - Web APIs
methods clients.get() re
turns a promise for a client matching a given id.
... clients.matchall() re
turns a promise for an array of client objects.
... an options argument allows you to control the types of clients re
turned.
... clients.openwindow() opens a new browser window for a given url and re
turns a promise for the new windowclient.
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.
... re
turn value a promise that resolves with a datatransfer object containing the clipboard's contents.
Clipboard.readText() - Web APIs
the clipboard interface's readtext() method re
turns a promise which resolves with a copy of the textual contents of the system clipboard..
... re
turn value a promise that resolves with a domstring containing the textual contents of the clipboard.
... re
turns an 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.
... example this example retrieves the textual contents of the clipboard and inserts the re
turned text into an element's contents.
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.
... re
turn value a promise that resolves with a blob object.
... 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.
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.
ContentIndex.getAll() - Web APIs
the getall() method of the contentindex interface re
turns a promise that resolves with an iterable list of content index entries.
... re
turn value re
turns a promise that resolves with an array of contentdescription items.
... contentdescription each item re
turned is an object containing the following data: id: a unique string identifier.
...if there are no items in the content index, an empty array is re
turned.
CredentialsContainer - Web APIs
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.
... 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 is allowed for future visits to the current origin, then re
turns an empty promise.
... 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.
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.
... 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.
CustomElementRegistry - Web APIs
customelementregistry.get() re
turns the constuctor for the named custom element, or undefined if the custom element is not defined.
... 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.
... // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent re
turn text.split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element conte...
DOMException - Web APIs
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.
... domexception.message read only re
turns a domstring representing a message or description associated with the given error name.
... domexception.name read only re
turns a domstring that contains one of the strings associated with an error name.
DOMImplementation.hasFeature() - Web APIs
the domimplementation.hasfeature() method re
turns a boolean flag indicating if a given feature is supported.
... it is deprecated and modern browsers re
turn true in all cases.
...the latest version of the spec settled to force this method to always re
turn true, where the functionality was accurate and in use.
... living standard modified to always re
turn true except for svg features.
DOMRectReadOnly - Web APIs
note that this constructor cannot be called by 3rd party javascript; doing so re
turns an "illegal constructor" typeerror.
... 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).
... domrectreadonly.left read only re
turns the left coordinate value of the domrect (usually the same as x).
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.
DOMTokenList.item() - Web APIs
the item() method of the domtokenlist interface re
turns an item in the list by its index.
... syntax tokenlist.item(index) parameters index a domstring representing the index of the item you want to re
turn.
... re
turn value a domstring representing the re
turned item.
... it re
turns null if the number is greater than or equal to the length of the list.
DOMTokenList.replace() - Web APIs
if the first token doesn't exist, replace() re
turns false immediately, without adding the new token to the token list.
... 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.
...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.
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.
... force optional a boolean that, if included,
turns the toggle into a one way-only operation.
... re
turn value a boolean indicating whether token is in the list after the call.
DataTransfer.getData() - Web APIs
if the drag operation does not include data, this method re
turns an empty string.
... 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.
...this may result in unexpected behavior, being datatransfer.getdata() not re
turning an expected value.
DataTransfer.mozTypesAt() - Web APIs
the datatransfer.moztypesat() method re
turns a list of the format types that are 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.
... re
turn value nsivariant a list of data formats (which are strings).
... if the index is not in the range from 0 to the number of items minus one, an empty string list is re
turned.
DataTransferItemList.DataTransferItem() - Web APIs
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.
Document.execCommand() - Web APIs
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.
... insertbronre
turn controls whether the enter key inserts a <br> element, or splits the current block element into two.
Document.lastModified - Web APIs
the lastmodified property of the document interface re
turns a string containing the date and time on which the current document was last modified.
... alert(document.lastmodified); // re
turns: tuesday, december 16, 2017 11:09:42 transforming lastmodified into a date object this example transforms lastmodified into a date object.
...cument.cookie.replace(/(?:(?:^|.*;)\s*last_modif\s*\=\s*([^;]*).*$)|^.*$/, "$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.
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.
... 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.
... 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.
Element.attachShadow() - Web APIs
the element.attachshadow() method attaches a shadow dom tree to the specified element and re
turns a reference to its shadowroot.
...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.
... re
turn value re
turns a shadowroot object.
... // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent re
turn text.trim().split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element...
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.
... 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.
... 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.
Element.requestFullscreen() - Web APIs
if permission to enter full screen mode is granted, the re
turned promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode.
... 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.
... 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.
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.
...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.
ExtendableMessageEvent - Web APIs
extendablemessageevent.data read only re
turns the event's data.
... extendablemessageevent.origin read only re
turns the origin of the client that sent the message.
... extendablemessageevent.source read only re
turns a reference to the client object that sent the message.
... extendablemessageevent.ports read only re
turns the array containing the messageport objects representing the ports of the associated message channel.
FeaturePolicy - Web APIs
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.
... featurepolicy.allowedfeatures re
turns a list of names of all features supported by the user agent and allowed by the feature policy.
... featurepolicy.getallowlistforfeature re
turns the allow list for the specified feature.
FetchEvent.request - Web APIs
the request read-only property of the fetchevent interface re
turns the request that triggered the event handler.
...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.
... 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 'request' in that specification.
FileSystemDirectoryEntry.getDirectory() - Web APIs
the filesystemdirectoryentry interface's method getdirectory() re
turns a filesystemdirectoryentry object corresponding 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.
... re
turn value undefined.
...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.
FileSystemDirectoryEntry.getFile() - Web APIs
} the filesystemdirectoryentry interface's method getfile() re
turns a 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.
... re
turn value undefined.
...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.
FontFace - Web APIs
constructor fontface() constructs and re
turns a new fontface object, built from an external resource described by an url or from an arraybuffer.
... 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.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.
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.
... 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.
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.
... 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.
... 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.
Using the Frame Timing API - Web APIs
function create_frame_observer() { if (window.performanceobserver === undefined) re
turn; // register the performance observer var observe_frame = new performanceobserver(function(list) { // log the frame entries var perfentries = list.getentriesbytype("frame"); for (var i=0; i < perfentries.length; i++) { console.log("obs #1: [" + i + "] = " + perfentries[i].name); } }); // only observe 'frame' events observe_frame.observe({entrytypes: ['frame']}); }...
...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.
Geolocation API - Web APIs
geolocation.watchposition(): registers a handler function that will be called automatically each time the position of the device changes, re
turning the updated location.
...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.
... 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.
...re
turns a geolocation object instance, from which all other functionality can be accessed.
HTMLCanvasElement.getContext() - Web APIs
the htmlcanvaselement.getcontext() method re
turns a drawing context on the canvas, or null if the context identifier is not supported.
... later calls to this method on the same canvas element re
turn the same drawing context instance as was re
turned the last time the method was invoked with the same contexttype argument.
... 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.
HTMLCollection.item - Web APIs
the htmlcollection method item() re
turns the node located at the specified offset into the collection.
... syntax var element = htmlcollection.item(index) parameters index the position of the node to be re
turned.
... 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.
HTMLDialogElement.close() - Web APIs
an optional domstring may be passed as an argument, updating the re
turnvalue of the the dialog.
... syntax dialoginstance.close(re
turnvalue); parameters re
turnvalue optional a domstring representing an updated value for the htmldialogelement.re
turnvalue of the dialog.
... re
turn value void.
...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.offsetParent - Web APIs
the htmlelement.offsetparent read-only property re
turns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element.
... if there is no positioned ancestor element, the nearest ancestor td, th, table will be re
turned, or the body if there are no ancestor table elements either.
... note: offsetparent re
turns null in the following situations: the element or its parent element has the display property set to none.
... the element has the position property set to fixed (firefox re
turns <body>).
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, in
turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads.
... re
turn value a promise which is resolved once the image data is ready to be used.
...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.
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a microtask is a short function which is executed after the function or program which created it exits and only if the javascript execution stack is empty, but before re
turning control to the event loop being used by the user agent to drive the script's execution environment.
... first, each time a task exits, the event loop checks to see if the task is re
turning control to other javascript code.
... queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not re
turn a value.
...an urgent callback has run!"); let dowork = () => { let result = 1; queuemicrotask(urgentcallback); for (let i=2; i<=10; i++) { result *= i; } re
turn result; }; log("main program started"); settimeout(callback, 0); log(`10!
Headers.getAll() - Web APIs
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.
... re
turns an array containing a bytestring sequence representing the values of the retrieved header.
... 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 retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // re
turns [ "image/jpeg" ] if the header has multiple values associated with it, the array 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.getall('accept-encoding'); // re
turns [ "deflate", "gzip" ] note: use headers.get to re
turn only the first value added to the headers object.
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.url = filterurl(spage, null); } oreq.open("get", filterurl(opageinfo.url, "json"), true); oreq.send(); oloadingbox.parentnode || document.body.appendchild(oloadingbox); } function requestpage (surl) { if (history.pushstate) { bupdateurl = true; getpage(surl); } else { /* ajax navigation is not supported */ location.assign(surl); } } function processlink () { if (this.c...
...lassname === 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", sviewkey = "view_as", sajaxclass = "ajax-nav", /* not customizable constants */ rsearch = /\?.*$/, rhost = /^[^\?]*\?*&*/, rview = new regexp("&" + sviewkey + "\\=[^&]*|&*$", "i"), rendqstmark = /\?$/, oloadingbox = document.createelement("div"), ocover = document.createelement("div"), oloadingimg ...
IDBDatabase - Web APIs
methods inherits from: eventtarget idbdatabase.close() re
turns immediately and closes the connection to a database in a separate thread.
... idbdatabase.createobjectstore() creates and re
turns a new object store or index.
... idbdatabase.transaction() immediately re
turns a transaction object (idbtransaction) containing the idbtransaction.objectstore method, which you can use to access your object store.
... error fired when a request re
turns an error and the event bubbles up to the connection object.
IDBFactory.deleteDatabase() - Web APIs
the method re
turns an idbopendbrequest object immediately, and performs the deletion operation asynchronously.
... if the database is successfully deleted, then a success event is fired on the request object re
turned from this method, with its result set to undefined.
... if an error occurs while the database is being deleted, then an error event is fired on the request object that is re
turned from this method.
... 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.
IDBFactory.open() - Web APIs
the method re
turns an idbopendbrequest object immediately, and performs the open operation asynchronously.
... if the operation is successful, a success event is fired on the request object that is re
turned from this method, with its result attribute set to the new idbdatabase object for the connection.
... if an error occurs while the database connection is being opened, then an error event is fired on the request object re
turned from this method.
... re
turn value a idbopendbrequest object on which subsequent events related to this request are fired.
IDBIndex.count() - Web APIs
the count() method of the idbindex interface re
turns an idbrequest object, and in a separate thread, re
turns the number of records within a key range.
... re
turn value a idbrequest object on which subsequent events related to this operation are fired.
...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.
IDBIndex.openKeyCursor() - Web APIs
the openkeycursor() method of the idbindex interface re
turns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index.
... note: cursors re
turned by openkeycursor() do not make the referenced value available as idbindex.opencursor does.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
...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.
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.
... re
turn value a boolean.
... 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.
... 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.
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.
... the count() method with the same key, which will re
turn 1 if the row exists and 0 if it doesn't.
... count optional specifies the number of values to re
turn if more than one is found.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.put() - Web APIs
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.
...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.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
...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.error - Web APIs
the error read-only property of the idbrequest interface re
turns the error in the event of an unsuccessful request.
...in chrome 48+/firefox 58+ this property re
turns a domexception because domerror has been removed from the dom standard.
... the following error codes are re
turned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error.
...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.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.
... re
turn value an idbobjectstore object for accessing an object store.
IDBTransaction - Web APIs
idbtransaction.error read only re
turns a domexception indicating the type of error that occured when there is an unsuccessful transaction.
... idbtransaction.objectstorenames read only re
turns a domstringlist of the names of idbobjectstore objects associated with the transaction.
... idbtransaction.objectstore() re
turns an idbobjectstore object representing an object store that is part of the scope of this transaction.
... error fired when a request re
turns an error and the event bubbles up to the transaction object.
getVersion - Web APIs
getversion re
turns an object representing the version number from the client version registry for the specified component.
... 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.
IntersectionObserverEntry - Web APIs
properties intersectionobserverentry.boundingclientrect read only re
turns the bounds rectangle of the target element as a domrectreadonly.
... 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.rootbounds read only re
turns a domrectreadonly for the intersection observer's root.
KeyboardEvent.location - Web APIs
the keyboardevent.location read-only property re
turns an unsigned long representing the location of the key on the keyboard or other input device.
... 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.
... note: gecko always re
turns dom_key_location_mobile on android (prior to 18) and maemo.
LayoutShift - Web APIs
properties layoutshift.value re
turns the impact fraction (fraction of the viewport that was shifted) times the distance fraction (distance moved as a fraction of viewport).
... layoutshift.hadrecentinput re
turns true if there was a user input in the past 500 milliseconds.
... layoutshift.lastinputtime re
turns the time of the most recent user input.
... layoutshift.sources re
turns an array of layoutshiftattribution objects with information on the elements that were shifted.
MediaMetadata - Web APIs
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.
... 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.
MediaSettingsRange - Web APIs
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.
... const input = document.queryselector('input[type="range"]'); 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(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; re
turn imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error =...
Media Source API - Web APIs
re
turned by the htmlvideoelement.getvideoplaybackquality() method.
... 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.
MimeTypeArray - Web APIs
the mimetypearray interface re
turns an array of mimetype instances, each of which contains information about a supported browser plugins.
... this object is re
turned by navigatorplugins.mimetypes.
... methods mimetypearray.item() re
turns the mimetype object with the specified index.
... mimetypearray.nameditem() re
turns the mimetype object with the specified name.
NameList - Web APIs
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.
NamedNodeMap - Web APIs
namednodemap.length read only re
turns the amount of objects in the map.
... namednodemap.getnameditem() re
turns a attr, corresponding to the given name.
... namednodemap.item() re
turns the attr at the given index, or null if the index is higher or equal to the number of nodes.
... namednodemap.getnameditemns() re
turns a attr identified by a namespace and related local name.
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.
...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.
... re
turn value a promise that, when resolved, delivers a mediakeysystemaccess object to your fulfillment handler function.
... the fulfillment handler receives as input just one parameter: mediakeysystemaccess a mediakeysystemaccess object representing the media key system configuration described by keysystem and supportedconfigurations exceptions in case of an error, the re
turned promise is rejected with a domexception whose name indicates what kind of error occurred.
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.
...any whitespace will create a #text node, from a single space to multiple spaces, re
turns, tabs, and so on.
... 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.
Node.localName - Web APIs
the node.localname read-only property re
turns the local part of the qualified name of this node.
...for example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix: <ecomm:business id="soda_shop" type="brick_n_mortar" xmlns: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.
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).
...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.
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.
... 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.
NodeList.item() - Web APIs
re
turns a node from a nodelist by index.
...a value of null is re
turned if the index is out of range, and a typeerror is thrown if no argument is provided.
... 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.
NotificationEvent - Web APIs
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.
...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('/'); })); }); specifications specification status comment notifications apithe definition of 'notificationevent' in that specification.
Page Visibility API - Web APIs
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.
...ousel that shouldn't advance to the next slide unless the user is viewing the page an application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible a page wants to detect when it is being prerendered so it can keep accurate count of page views a site wants to switch off sounds when a device is in standby mode (user pushes power button to
turn screen off) developers have historically used imperfect proxies to detect this.
... the example, which pauses the video when you switch to another tab and plays again when you re
turn to its tab, was created with the following code: // set the name of the hidden property and the change event for visibility var hidden, visibilitychange; if (typeof document.hidden !== "undefined") { // opera 12.10 and firefox 18 and later support hidden = "hidden"; visibilitychange = "visibilitychange"; } else if (typeof document.mshidden !== "undefined") { hidden = "mshidden"; visibili...
... 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.
PaymentRequest.canMakePayment() - Web APIs
}) 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.
... note: if you call this too often, the browser may reject the re
turned promise with a domexception.
... 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.
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.
...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.
...=== request.id ); const newtotal = { currency: "usd", label: "total due", value: calculatenewtotal(shippingoption), }; ev.updatewith({ ...details, total: newtotal }); }; async function checkshipping(request) { try { const json = request.shippingaddress.tojson(); await ensurecanshipto(json); const { shippingoptions, total } = await calculateshipping(json); re
turn { ...details, shippingoptions, total }; } catch (err) { re
turn { ...details, error: `sorry!
performance.getEntriesByType() - Web APIs
the getentriesbytype() method re
turns a list of performanceentry objects for a given type.
... re
turn value entries a list of performanceentry objects that have the specified type.
...if no objects have the specified type, or no argument is provided, an empty list is re
turned.
...performance.mark not supported"); re
turn; } // create some performance entries via the mark() method performance.mark("begin"); dowork(50000); performance.mark("end"); performance.mark("begin"); dowork(100000); performance.mark("end"); dowork(200000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); checkperformanceentry(p[i]); } // use getentries(name, entrytype) to get specific entries p = performance.getentries({name : "begin", entrytype: "mark"}); for (var i=0; i < p.length; i...
PerformanceEventTiming - Web APIs
textmenu dblclick dragend dragenter dragleave dragover dragstart drop input keydown 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.
PerformanceFrameTiming - Web APIs
l="#4d4e53" text-anchor="middle" alignment-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.
PerformanceMark - Web APIs
amily="consolas,monaco,andale mono,monospace" 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".
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 timestamp).
PerformanceObserverEntryList.getEntries() - Web APIs
the getentries() method of the performanceobserverentrylist interface re
turns a list of explicitly observed performance entry objects for a given filter.
... re
turn value a list of explicitly observed performanceentry objects that meets the criteria of the filter.
...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.
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.
... 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.
...if no objects meet the specified criteria, an empty list is re
turned.
PerformancePaintTiming - Web APIs
l="#4d4e53" text-anchor="middle" alignment-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.
PerformanceResourceTiming.secureConnectionStart - Web APIs
the secureconnectionstart read-only property re
turns a timestamp immediately before the browser starts the handshake process to secure the current connection.
... if a secure connection is not used, the property re
turns zero.
... syntax resource.secureconnectionstart; re
turn value if the resource is fetched over a secure connection, a domhighrestimestamp immediately before the browser starts the handshake process to secure the current connection.
... if a secure connection is not used, this property re
turns zero.
Performance API - Web APIs
the now() method re
turns a domhighrestimestamp whose value that depends on the navigation start and scope.
... the tojson() method re
turns a serialization of the performance object, for those attributes that can be serialized.
...the timing property re
turns a performancetiming object containing latency-related performance information such as the start of navigation time, start and end times for redirects, start and end times for responses, etc.
... the navigation property re
turns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history, the page was navigated to by following a link, etc.
Performance Timeline - Web APIs
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.
...(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.
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.
... methods pluginarray.item re
turns the plugin at the specified index into the array.
... pluginarray.nameditem re
turns the plugin with the specified name.
... examples the following example function re
turns the version of the shockwave flash plugin.
PositionOptions - Web APIs
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 infinity the device must re
turn a cached position regardless of its age.
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 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.
RTCIceServer.credential - Web APIs
this value is used when the rtciceserver describes a
turn server.
... }; 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.
RTCIceServer.username - Web APIs
this value is used when the rtciceserver describes a
turn server.
... }; 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.
RTCIceServer - Web APIs
the rtciceserver dictionary defines how to connect to a single ice server (such as a stun or
turn 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.
... username optional if the rtciceserver is a
turn server, then this is the username to use during the authentication process.
RTCPeerConnection() - Web APIs
the rtcpeerconnection() constructor re
turns a newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.
... 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.
... re
turn value a newly-created rtcpeerconnection object, configured as described by configuration, if specified; otherwise, configured to appropriate basic defaults.
RTCPeerConnection.addTrack() - Web APIs
re
turn value the rtcrtpsender object which will be used to transmit the media data.
... 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.
... 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().
...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.
RTCPeerConnection.close() - Web APIs
syntax peerconnection.close(); this method has no parameters, and re
turns nothing.
...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.
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.
... syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to re
turn.
... // from: https://bugs.chromium.org/p/chromium/issues/detail?id=698163&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.setLocalDescription() - Web APIs
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.
...they're interchangeable: mypeerconnection.createoffer().then(function(offer) { re
turn mypeerconnection.setlocaldescription(offer); }); this is equivalent to: mypeerconnection.createoffer().then(function(offer) { re
turn mypeerconnection.setlocaldescription(new rtcsessiondescription(offer)); }); for this reason, the rtcsessiondescription() constructor is deprecated.
... re
turn value a promise which is fulfilled once the value of rtcpeerconnection.localdescription is successfully changed or rejected if the change cannot be applied (for example, if the specified description is incompatible with one or both of the peers on the connection).
... this deprecated form of the method re
turns instantaneously without waiting for the actual setting to be done: in case of success, the successcallback will be called; in case of failure, the errorcallback will be called.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
the findreportentry() function shown below examines an rtcstatsreport, re
turning the rtcstats-based statistics record which contains the specified key — and for which the key has the specified value.
... 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.
Reporting API - Web APIs
indicated by a report.body property with a deprecationreportbody re
turn value.
...indicated by a report.body property with a interventionreportbody re
turn value.
...indicated by a report.body property with a crashreportbody re
turn value.
...after the first time we call reportingobserver.takerecords(), which re
turns the first generated report and empties the queue.
SVGAnimationElement - Web APIs
if no target element is being animated (for example, because the href specifies an unknown element) the value re
turned is null.
... 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.
... 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.
SVGEllipseElement - Web APIs
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 property re
turns a svganimatedlength reflecting the ry attribute of the given <ellipse> element.
SVGLengthList - Web APIs
methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list.
...the re
turn value is the item inserted into the list.
... 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.
SVGLineElement - Web APIs
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.
SVGNumberList - Web APIs
methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list.
...the re
turn value is the item inserted into the list.
... 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.
SVGPointList - Web APIs
methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list.
...the re
turn value is the item inserted into the list.
... 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.
SVGStringList - Web APIs
methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list.
...the re
turn value is the item inserted into the list.
... 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.
ServiceWorker - Web APIs
serviceworker.scripturl read only re
turns the serviceworker serialized script url defined as part of serviceworkerregistration.
... 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.
...the code listens for any change in the serviceworker.state and re
turns its value.
ServiceWorkerGlobalScope.onfetch - Web APIs
when fired, the code re
turns a promise that resolves to the first matching request in the cache object.
...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.
... 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.
ServiceWorkerMessageEvent - Web APIs
serviceworkermessageevent.data read only re
turns the event's data.
... serviceworkermessageevent.origin read only re
turns the origin of the service worker's environment settings object.
... 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.
ServiceWorkerRegistration.getNotifications() - Web APIs
the getnotifications() method of the serviceworkerregistration interface re
turns a list of the notifications in the order that they were created from the current origin via the current service worker registration.
...}); parameters options optional an object containing options to filter the notifications re
turned.
...if specified, only notifications that have this tag will be re
turned.
... re
turn value a promise that resolves to a list of notification objects.
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.
... 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.
... example javascript function populatevoicelist() { if(typeof speechsynthesis === 'undefined') { re
turn; } var voices = speechsynthesis.getvoices(); for(var 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'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); document.getelementbyid("voiceselect").appendchild(option); } } populatevoicelist(); if (typeof speechsynthesis !== 'undefined' && speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } html <select id="voiceselect"></select> ...
SpeechSynthesisEvent - Web APIs
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.
Storage Access API - Web APIs
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.
... 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.
SubtleCrypto.deriveBits() - Web APIs
it re
turns a promise which will be fulfilled with an arraybuffer containing the derived bits.
... this method is very similar to subtlecrypto.derivekey(), except that derivekey() re
turns a cryptokey object rather than an arraybuffer.
... re
turn value result is a promise that fulfills with an arraybuffer containing the derived bits.
...*/ 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.
SubtleCrypto.digest() - Web APIs
it re
turns a promise which will be fulfilled with the digest.
... re
turn value digest is a promise that fulfills with an arraybuffer containing the digest.
...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.
...code(message); // encode as (utf-8) uint8array const hashbuffer = await crypto.subtle.digest('sha-256', msguint8); // hash the message const hasharray = array.from(new uint8array(hashbuffer)); // convert buffer to byte array const hashhex = hasharray.map(b => b.tostring(16).padstart(2, '0')).join(''); // convert bytes to hex string re
turn hashhex; } const digesthex = await digestmessage(text); console.log(digesthex); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.digest()' in that specification.
TouchEvent.targetTouches - Web APIs
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.
... 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 ?
Touch events - Web APIs
uch(touch) { var r = touch.identifier % 16; var g = math.floor(touch.identifier / 3) % 16; var b = math.floor(touch.identifier / 7) % 16; r = r.tostring(16); // make it a hex digit g = g.tostring(16); // make it a hex digit b = b.tostring(16); // make it a hex digit var color = "#" + r + g + b; console.log("color for touch with identifier " + touch.identifier + " = " + color); re
turn color; } the result from this function is a string that can be used when calling <canvas> functions to set drawing colors.
... 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) { 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.
...it is only intended as a guide.) function ontouch(evt) { evt.preventdefault(); if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0)) re
turn; var newevt = document.createevent("mouseevents"); var type = null; var touch = null; switch (evt.type) { case "touchstart": type = "mousedown"; touch = evt.changedtouches[0]; break; case "touchmove": type = "mousemove"; touch = evt.changedtouches[0]; break; case "touchend": type = "mouseup"; touch = evt.changedtouches[0]; ...
URLSearchParams.get() - Web APIs
the get() method of the urlsearchparams interface re
turns the first value associated to the given search parameter.
... 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.
...les if the url of your page is https://example.com/?name=jonathan&age=18 you could parse out the 'name' and 'age' parameters using: let params = new urlsearchparams(document.location.search.substring(1)); let name = params.get("name"); // is the string "jonathan" let age = parseint(params.get("age"), 10); // is the number 18 requesting a parameter that isn't present in the query string will re
turn null: let address = params.get("address"); // null specifications specification status comment urlthe definition of 'get()' in that specification.
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.
... 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.
URLUtilsReadOnly.hash - Web APIs
the urlutilsreadonly.hash read-only property re
turns a domstring containing a '#' followed by the fragment identifier of the url.
... syntax string = object.hash; examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.hash#example var result = window.self.hash; // re
turns:'#hash' specifications specification status comment urlthe definition of 'urlutilsreadonly.hash' in that specification.
... androidsafari on iossamsung internethash experimentalchrome no support noedge no support nofirefox full support 38 full support 38 no support 3.5 — 38notes notes before firefox 38, firefox re
turned the hash percent encoded.
... nowebview android no support nochrome android no support nofirefox android full support 38 full support 38 no support 4 — 38notes notes before firefox 38, firefox re
turned the hash percent encoded.
URLUtilsReadOnly - Web APIs
urlutilsreadonly.origin read only re
turns a domstring containing the canonical form of the origin of the specific location.
... urlutilsreadonly.tostring() re
turns a domstring containing the whole url.
...pport nohash experimentalchrome no support noedge no support nofirefox full support 38 full support 38 no support 3.5 — 38notes notes before firefox 38, firefox re
turned the hash percent encoded.
... nowebview android no support nochrome android no support nofirefox android full support 38 full support 38 no support 4 — 38notes notes before firefox 38, firefox re
turned the hash percent encoded.
USBEndpoint - Web APIs
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.
... usbendpoint.direction re
turns the direction in which this endpoint transfers data, one of: "in" - data is transferred from device to host.
... usbendpoint.type re
turns the type of this endpoint, one of: "bulk" - provides reliable data transfer for large payloads.
... usbendpoint.packetsize re
turns the size of the packets that data sent through this endpoint will be divided into.
USBInterface - Web APIs
properties usbinterface.interfacenumberread only re
turns the interface number of this interface.
... usbinterface.alternateread only re
turns the currently selected alternative configuration of this interface.
... 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().
VideoTrack.label - Web APIs
the read-only videotrack property label re
turns a string specifying the video track's human-readable label, if one is available; otherwise, it re
turns an empty string.
...otherwise, an empty string ("") is re
turned.
... example this example re
turns an array of track kinds and labels for potential use in a user interface to select video tracks for a specified media element.
... function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "commentary" ]; el.videotracks.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 video tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
WebGLRenderingContext.getBufferParameter() - Web APIs
the webglrenderingcontext.getbufferparameter() method of the webgl api re
turns information about the buffer.
...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.
... re
turn value depends on the requested information (as specified with pname).
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.
... examples given this <canvas> element <canvas id="canvas"></canvas> and given this webgl context var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getcontextattributes(); the getcontextattributes method re
turns an object that describes the attributes set on this context, for example: { alpha: true, antialias: true, depth: true, failifmajorperformancecaveat: false, powerpreference: "default", premultipliedalpha: true, preservedrawingbuffer: false, stencil: false, desynchronized: false } the context attributes can be set when creating the context using the htmlcanvaselement.getcontext() method: canvas.getcontext('webgl', { antialias: false, depth: false }); see getcontext() for more informatio...
WebGLRenderingContext.getError() - Web APIs
the webglrenderingcontext.geterror() method of the webgl api re
turns error information.
... re
turn value constant description gl.no_error no error has been recorded.
... 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.
WebGLRenderingContext.getTexParameter() - Web APIs
the webglrenderingcontext.gettexparameter() method of the webgl api re
turns information about the given texture.
...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.
... re
turn value re
turns the requested texture information (as specified with pname).
... if an error occurs, null is re
turned.
Using DTMF with WebRTC - Web APIs
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).
...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.
... function handlecallernegotiationneeded() { log("negotiating..."); callerpc.createoffer(offeroptions) .then(function(offer) { log("setting caller's local description: " + offer.sdp); re
turn callerpc.setlocaldescription(offer); }) .then(function() { log("setting receiver's remote description to the same as caller's local"); re
turn receiverpc.setremotedescription(callerpc.localdescription) }) .then(function() { log("creating answer"); re
turn receiverpc.createanswer(); }) .then(function(answer) { log("setting receiver's local description to " + answer.sd...
...p); re
turn receiverpc.setlocaldescription(answer); }) .then(function() { log("setting caller's remote description to match"); re
turn callerpc.setremotedescription(receiverpc.localdescription); }) .catch(err => log("error during negotiation: " + err.message)); } since the various methods involved in negotiating the connection re
turn promises, we can chain them together like this: call callerpc.createoffer() to get an offer.
WebRTC API - Web APIs
rtciceserver defines how to connect to a single ice server (such as a stun or
turn server).
...if no peer has yet been set and verified this interface re
turns null.
... 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.
...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...
WebXR Device API - Web APIs
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.
... 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.
...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.
Migrating from webkitAudioContext - Web APIs
var osc = context.createoscillator(); osc.start(1); osc.stop(1.5); var src = context.createbuffersource(); src.start(1, 0.25); src.stop(2); remove synchronous buffer creation in the old webkit implementation of web audio, there were two versions of createbuffer(), one which created an initially empty buffer, and one which took an existing arraybuffer containing encoded audio, decoded it and re
turned the result in the form of an audiobuffer.
...", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { context.decodeaudiodata(xhr.response, function onsuccess(decodedbuffer) { // decoding was successful, do something useful with the audio buffer }, function onfailure() { alert("decoding the audio buffer failed"); }); }; note that the decodeaudiodata() method is asynchronous, which means that it will re
turn immediately, and then when the decoding finishes, one of the success or failure callback functions will get called depending on whether the audio decoding was successful.
... 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...
... the units attribute as implemented in webkitaudiocontext implementations is unused, and always re
turns 0.
Using IIR filters - Web APIs
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.
...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.
...}, false); the toggle that
turns the iir filter on and off is set up in the similar way.
... // 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.
WheelEvent - Web APIs
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.
Window.getDefaultComputedStyle() - Web APIs
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.
... <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.
window.location - Web APIs
the window.location read-only property re
turns a location object with information about the current location of the document.
...ookmarks without changing the hash property: <!doctype html> <html> <head> <meta charset="utf-8"/> <title>mdn example</title> <script> function shownode (onode) { document.documentelement.scrolltop = onode.offsettop; document.documentelement.scrollleft = onode.offsetleft; } function showbookmark (sbookmark, busehash) { if (arguments.length === 1 || busehash) { location.hash = sbookmark; re
turn; } var obookmark = document.queryselector(sbookmark); if (obookmark) { shownode(obookmark); } } </script> <style> span.intlink { cursor: pointer; color: #0000ff; text-decoration: underline; } </style> </head> <body> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...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...
...lid > -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 / nframes)); } }; })(); specifications specification status comment html living standardthe definition of 'window.location' in that specifi...
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.
...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.
WorkerGlobalScope.performance - Web APIs
the performance read-only property of the workerglobalscope interface re
turns a performance object to be used on the worker.
... syntax var perfobj = self.performance; re
turn value a performance object.
...ker 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: 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.
XRInputSource.targetRaySpace - Web APIs
the read-only xrinputsource property targetrayspace re
turns an xrspace (typically an xrreferencespace) representing the position and orientation of the target ray in the 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.
...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.
... 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.
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.
... 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.
... values() re
turns an iterator you can use to go through all the values in the list.
XRReferenceSpace - Web APIs
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).
... 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..
... 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.
XRSystem - Web APIs
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.
... requestsession() re
turns a promise that resolves to a new xrsession with the specified xrsessionmode.
...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.
...when the re
turned promise resolves, we set xrsession to null to record the fact that we no longer have an ongoing session.
Architecture - Accessibility
ed object char: linkindex = iahypertext::getlinkindex(offset) iahyperlink*object = iahypertext::getlink(linkindex) iaccessible* accessible = qi/qs(object) (b) to get the offset in the parent text for a given embedded object: qi/qa to iahyperlink if not successful, then it is not embedded in text, so it's position in parent should be determined just by ia2::indexinparent, which will re
turn its child offset within the parent.
...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.
...therefore, as the user arrows up and down, if you use the accessibletext::caretoffset and retrieve the line with that offset, you may not get the line with the visual caret re
turned.
...not only can this save extra calls, but it will always re
turn the visual line of text when used with the gettext methods and line boundaries.
Operable - Accessibility
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.
... 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.
...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.
...live multiplayer games), and any other activity that requires a time limit and would be invalidated if it were
turned off.
<color> - CSS: Cascading Style Sheets
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.
...as an <angle>, it implicitly wraps around such that -120deg=240deg, 480deg=120deg, -1
turn=1
turn, etc.
... html <div></div> <hr> <label for="color">enter a valid color value:</label> <input type="text" id="color"> css div { width: 100%; height: 200px; } javascript const inputelem = document.queryselector('input'); const divelem = document.queryselector('div'); function validtextcolor(stringtotest) { if (stringtotest === "") { re
turn false; } if (stringtotest === "inherit") { re
turn false; } if (stringtotest === "transparent") { re
turn false; } const image = document.createelement("img"); image.style.color = "rgb(0, 0, 0)"; image.style.color = stringtotest; if (image.style.color !== "rgb(0, 0, 0)") { re
turn true; } image.style.color = "rgb(255, 255, 255)"; image.style.color = stringtotest; re
turn image.styl...
...*/ hsl(270,60%,70%) hsl(270, 60%, 70%) hsl(270 60% 70%) hsl(270deg, 60%, 70%) hsl(4.71239rad, 60%, 70%) hsl(.75
turn, 60%, 70%) /* these examples all specify the same color: a lavender that is 15% opaque.
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...
...e-in-out; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:4s; 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); specifications specification status comment css transitionsthe definition of 'transition-delay' in that specification.
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...
...n-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:4s; 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); specifications specification status comment css transitionsthe definition of 'transition-duration' in that specification.
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.
... 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.
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.
... 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.
... 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.
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.
... re
turns a node-set containing the nodes that are in nodeset1 but not in nodeset2.
Media buffering, seeking, and time ranges - Developer guides
it re
turns a timeranges object, which will tell us which chunks of media have been downloaded.
... ------------------------------------------------------ |=============| |===========| | ------------------------------------------------------ 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...
... seekable the seekable attribute re
turns a timeranges object and tells us which parts of the media can be played without delay; this is irrespective of whether that part has been downloaded or not.
...for example: var played = audio.played; // re
turns a timeranges object this could be useful for establishing the parts of your media that are most listened to or watched.
Making content editable - Developer guides
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>).
...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...
Parsing and serializing XML - Developer guides
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.
... resources into dom trees using xmlhttprequest here is sample code that reads and parses a url-addressable xml file into a dom tree: var xhr = new xmlhttprequest(); xhr.onload = function() { dump(xhr.responsexml.documentelement.nodename); } xhr.onerror = function() { dump("error while getting xml."); } xhr.open("get", "example.xml"); xhr.responsetype = "document"; xhr.send(); the value re
turned in the xhr object's responsexml field is a document constructed by parsing the xml.
... if the document is html, the code shown above will re
turn a document.
HTML attribute reference - HTML: Hypertext Markup Language
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.
... most of the time, idl attributes will re
turn their values as they are really used.
...however, the type idl attribute will re
turn the string "text".
...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.
<input type="search"> - HTML: Hypertext Markup Language
the text must not include carriage re
turns or line feeds.
... 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.
... 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).
... 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.
<input type="tel"> - HTML: Hypertext Markup Language
the text must not include carriage re
turns or line feeds.
... 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.
... 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.
...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.
<input type="text"> - HTML: Hypertext Markup Language
the text must not include carriage re
turns or line feeds.
... 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.
... 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.
... 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.
<video>: The Video Embed element - HTML: Hypertext Markup Language
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.
...if no media is present on the element, or the media is not valid, the re
turned value is nan.
...specifically, the image would raster at these dimensions and naturalwidth/naturalheight on images would re
turn the values specified in this attribute.
Range - HTTP
the range http request header indicates the part of a document that the server should re
turn.
...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.
... <suffix-length> an integer in the given unit indicating the number of units at the end of the file to re
turn.
HTTP response status codes - HTTP
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.
...the two mandatory methods, get and head, must never be disabled and should not re
turn this error code.
... 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.
...the only methods that servers are required to support (and therefore that must not re
turn this code) are get and head.
Enumerability and ownership of properties - JavaScript
detection can occur by simplepropertyretriever.thegetmethodyouwant(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: 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: function(obj) { re
turn this._getpropertynames(obj, true, true, this._enumerable); // or could use unfiltered for..in }, getownandprototypenonenumerables: function(obj) { re
turn this._getpropertynames(obj...
..., true, true, this._notenumerable); }, getownandprototypeenumerablesandnonenumerables: function(obj) { re
turn this._getpropertynames(obj, true, true, this._enumerableandnotenumerable); }, // private static property checker callbacks _enumerable: function(obj, prop) { re
turn obj.propertyisenumerable(prop); }, _notenumerable: function(obj, prop) { re
turn !obj.propertyisenumerable(prop); }, _enumerableandnotenumerable: function(obj, prop) { re
turn true; }, // inspired by http://stackoverflow.com/a/8024294/271577 _getpropertynames: function getallpropertynames(obj, iterateselfbool, iterateprototypebool, includepropcb) { var props = []; do { if (iterateselfbool) { object.geto...
...ropertynames(obj).foreach(function(prop) { if (props.indexof(prop) === -1 && includepropcb(obj, prop)) { props.push(prop); } }); } if (!iterateprototypebool) { break; } iterateselfbool = true; } while (obj = object.getprototypeof(obj)); re
turn props; } }; detection table in for..in obj.hasownproperty obj.propertyisenumerable object.keys object.getownpropertynames object.getownpropertydescriptors reflect.ownkeys() enumerable true true true true true true true true nonenumerable true false true false false true true true ...
Concurrency model and the event loop - JavaScript
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 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.
...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.
TypeError: 'x' is not iterable - JavaScript
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?
...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]() { re
turn [][symbol.iterator]() } } array.from(myemptyiterable); // [] ...
Array.prototype.concat() - JavaScript
this method does not change the existing arrays, but instead re
turns a new array.
...if all valuen parameters are omitted, concat re
turns a shallow copy of the existing array on which it is called.
... re
turn value a new array instance.
... 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.
Array.prototype.fill() - JavaScript
it re
turns the modified array.
... re
turn value the modified array, filled with value.
... fill is a mutator method: it will change the array itself and re
turn it, not a copy of it.
... 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.
Array.isArray() - JavaScript
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.
...given a typedarray instance, false is always re
turned.
... if (!array.isarray) { array.isarray = function(arg) { 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.is...
Array.prototype.join() - JavaScript
the join() method creates and re
turns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
... if the array has only one item, then that item will be re
turned without using the separator.
... re
turn value a string with all array elements joined.
... if arr.length is 0, the empty string is re
turned.
Array.prototype.pop() - JavaScript
the pop() method removes the last element from an array and re
turns that element.
... 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.
... if you call pop() on an empty array, it re
turns undefined.
Array.prototype.reverse() - JavaScript
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.
...the call to reverse() re
turns a reference to the reversed array a.
...the call to reverse() re
turns a reference to the reversed array-like object a.
Array.prototype.shift() - JavaScript
the shift() method removes the first element from an array and re
turns that removed element.
... 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.
Array.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the array.
... syntax arr.tosource() re
turn value a string representing the source code of the array.
... description the tosource method re
turns the following values: for the built-in array object, tosource re
turns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource re
turns a string representing the source code.
... examples examining the source code of an array to examine the source code of an array: var alpha = new array('a', 'b', 'c'); alpha.tosource(); //re
turns ['a', 'b', 'c'] specifications not part of any standard.
Array.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified array and its elements.
... syntax arr.tostring() re
turn value a string representing the elements of the array.
...for array objects, the tostring method joins the array and re
turns one string containing each array element separated by commas.
...object.prototype.tostring() will be called, and the resulting value will be re
turned.
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.
... 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.
...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.
Atomics.notify() - JavaScript
it will re
turn 0 on non-shared arraybuffer objects.
... re
turn value re
turns the number of woken up agents.
... re
turns 0, if a non-shared arraybuffer object is used.
...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).
BigInt.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string with a language-sensitive representation of this bigint.
...in implementations that ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation-dependent.
... re
turn value a string with a language-sensitive representation of the given bigint.
... examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is re
turned.
Date.prototype[@@toPrimitive] - JavaScript
syntax date()[symbol.toprimitive](hint); re
turn value the primitive value of the given date object.
... depending on the argument, the method can re
turn either a string or a number.
... description the [@@toprimitive]() method of the date object re
turns a primitive value, that is either of type number or of type string.
... 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+...
Date.UTC() - JavaScript
it re
turns the number of milliseconds since january 1, 1970, 00:00:00 utc.
... 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.
... date.utc() re
turns a time value as a number instead of creating a date object.
Date.prototype.getFullYear() - JavaScript
the getfullyear() method re
turns the year of the specified date according to local time.
... 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.
Date.prototype.getTimezoneOffset() - JavaScript
the gettimezoneoffset() method re
turns the time zone difference, in minutes, from current locale (host system settings) to utc.
... syntax dateobj.gettimezoneoffset() re
turn value a number representing the time-zone offset, in minutes, from the date based on current host system settings to utc.
...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.
Date.prototype.setMonth() - JavaScript
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.
...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.
Date.prototype.toISOString() - JavaScript
the toisostring() method re
turns a string in simplified extended iso format (iso 8601), which is always 24 or 27 characters long (yyyy-mm-ddthh:mm:ss.sssz or ±yyyyyy-mm-ddthh:mm:ss.sssz, respectively).
... syntax dateobj.toisostring() re
turn value a string representing the given date in the iso 8601 format according to universal time.
...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) { re
turn '0' + number; } re
turn number; } date.prototype.toisostring = function() { re
turn this.getutcfullyear() + '-' + pad(this.getutcmonth() + 1) + '-' + pad(this.getutcdate()) + 't' + pad(this.getutchours()) + ':' + pad(this.getutcminutes()) + ':' + pad(this.getutcseconds()) + '.' + (this.getutcmilliseconds() / 1000).tofixed(3).slice(2, 5) + 'z'; }; })(); } examples using toisostring() let today ...
...= new date('05 october 2011 14:48 utc') console.log(today.toisostring()) // re
turns 2011-10-05t14:48:00.000z the above example uses parsing of a non–standard string value that may not be correctly parsed in non–mozilla browsers.
Date.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified date object.
... syntax dateobj.tostring() re
turn value a string representing the given date.
...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 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.
Date.prototype.toUTCString() - JavaScript
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.
...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.
Function.caller - JavaScript
the function.caller property re
turns the function that invoked the specified function.
... it re
turns null for strict, async function and generator function callers.
... the special property __caller__, which re
turned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.
... 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.
Function.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the source code of the function.
... syntax function.tostring() re
turn value a string representing the source code of the function.
...for user-defined function objects, the tostring method re
turns a string containing the source text segment which was used to define the function.
... 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.
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.
... 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.
... value any javascript value re
turned by the iterator.
Intl.DateTimeFormat - JavaScript
static methods intl.datetimeformat.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.
... 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.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.
Intl.ListFormat - JavaScript
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.
...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.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.
...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.
Intl.NumberFormat - JavaScript
static methods 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.
... 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 and with default options is re
turned.
Intl.RelativeTimeFormat - JavaScript
static methods intl.relativetimeformat.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.
... 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.
...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.
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.
... 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.
...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.get() - JavaScript
the get() method re
turns a specified element from a map object.
... 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.
Math.abs() - JavaScript
the math.abs() function re
turns the absolute value of a number, that is math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{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.
... re
turn value the absolute value of the given number.
... 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.cos() - JavaScript
the math.cos() static function re
turns the cosine of the specified angle, which must be specified in radians.
... 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.
Math.imul() - JavaScript
the math.imul() function re
turns the result of the c-like 32-bit multiplication of the two parameters.
... re
turn value the result of the c-like 32-bit multiplication of the given arguments.
... 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.
...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.min() - JavaScript
the static function math.min() re
turns the lowest-valued number passed into it, or nan if any parameter isn't a number and can't be converted into one.
... 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.
Math.pow() - JavaScript
the math.pow() function re
turns the base to the exponent power, that is, baseexponent.
... 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.
...40816326530612 (1/49) math.pow(8, -1/3); // 0.5 // signed bases math.pow(-7, 2); // 49 (squares are positive) math.pow(-7, 3); // -343 (cubes can be negative) math.pow(-7, 0.5); // nan (negative numbers don't have a real square root) // due to "even" and "odd" roots laying close to each other, // and limits in the floating number precision, // negative bases with fractional exponents always re
turn nan math.pow(-7, 1/3); // nan specifications specification ecmascript (ecma-262)the definition of 'math.pow' in that specification.
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.
... 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.
Math.trunc() - JavaScript
the math.trunc() function re
turns the integer part of a number by removing any fractional digits.
... re
turn value the integer part of the given number.
... polyfill if (!math.trunc) { math.trunc = function(v) { v = +v; if (!isfinite(v)) re
turn v; re
turn (v - v % 1) || (v < 0 ?
...v : 0); // re
turns: // 0 -> 0 // -0 -> -0 // 0.2 -> 0 // -0.2 -> -0 // 0.7 -> 0 // -0.7 -> -0 // infinity -> infinity // -infinity -> -infinity // nan -> nan // null -> 0 }; } or: if (!math.trunc) { math.trunc = function (v) { re
turn v < 0 ?
Number.isNaN() - JavaScript
re
turn value true if the given value is nan and its type is number; otherwise, false.
...this also means that only values of the type number, that are also nan, re
turn true.
... 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 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.prototype.__lookupSetter__() - JavaScript
the __lookupsetter__ method re
turns the function bound as a setter to the specified property.
... syntax obj.__lookupsetter__(sprop) parameters sprop a string containing the name of the property whose setter should be re
turned.
... re
turn value the function bound as a setter to the specified property.
... description if a setter has been defined for an object's property, it was not possible to reference the setter function through that property, because that property refers to the re
turn value of that function.
Object.create() - JavaScript
re
turn value a new object with the specified prototype object and properties.
... be aware of, also, that using object.entries() on an object created via object.create() will result in an empty array being re
turned.
... throw new error("this browser's implementation of object.create is a shim and doesn't support 'null' as the first argument."); } if (typeof propertiesobject != 'undefined') { throw new error("this browser's implementation of object.create is a shim and doesn't support a second argument."); } function f() {} f.prototype = proto; re
turn new f(); }; } examples classical inheritance with object.create() below is an example of how to use object.create() to achieve classical inheritance.
...(note that the second parameter // maps keys to *property descriptors*.) o = object.create(object.prototype, { // foo is a regular 'value property' foo: { writable: true, configurable: true, value: 'hello' }, // bar is a getter-and-setter (accessor) property bar: { configurable: false, get: function() { re
turn 10; }, set: function(value) { console.log('setting `o.bar` to', value); } /* with es2015 accessors our code can look like this get() { re
turn 10; }, set(value) { console.log('setting `o.bar` to', value); } */ } }); function constructor() {} o = new constructor(); // is equivalent to: o = object.create(constructor.prototype); // of course, if there is actual ini...
Object.getOwnPropertySymbols() - JavaScript
the object.getownpropertysymbols() method re
turns an array of all symbol properties found directly upon a given object.
... 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.
... 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.
Object.getPrototypeOf() - JavaScript
the object.getprototypeof() method re
turns the prototype (i.e.
... 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.
Object.isSealed() - JavaScript
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.
...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.
Promise.prototype.finally() - JavaScript
the finally() method re
turns a promise.
... re
turn value re
turns a promise whose finally handler is set to the specified function, onfinally.
... note: a throw (or re
turning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw.
... examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { re
turn response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.error(error); /* this line can also throw, e.g.
handler.construct() - JavaScript
re
turn value the construct method must re
turn an object.
... 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.
... 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.getOwnPropertyDescriptor() - JavaScript
re
turn value the getownpropertydescriptor() method must re
turn an object or undefined.
... interceptions this trap can intercept these operations: object.getownpropertydescriptor() reflect.getownpropertydescriptor() invariants if the following invariants are violated, the proxy will throw a typeerror: getownpropertydescriptor() must re
turn an object or undefined.
... const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); 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
re
turn value the isextensible() method must re
turn a boolean value.
... 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).
... 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
re
turn value the preventextensions() method must re
turn a boolean value.
... 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.
... 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.
handler.setPrototypeOf() - JavaScript
re
turn value the setprototypeof() method re
turns true if the [[prototype]] was successfully changed, otherwise false.
... 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.
... 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.getPrototypeOf() - JavaScript
it re
turns the prototype (i.e.
... re
turn value the prototype of the given object.
... if there are no inherited properties, null is re
turned.
... description the reflect.getprototypeof method re
turns the prototype (i.e.
Reflect.ownKeys() - JavaScript
the static reflect.ownkeys() method re
turns an array of the target object's own property keys.
... re
turn value an array of the target object's own property keys.
... 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)).
RegExp.prototype[@@matchAll]() - JavaScript
the [@@matchall] method re
turns all matches of the regular expression against a string.
... re
turn value an iterator.
...for example, the following two examples re
turn same result.
... for example, to re
turn an array instead of an iterator: class myregexp extends regexp { [symbol.matchall](str) { const result = regexp.prototype[symbol.matchall].call(this, str); if (!result) { re
turn null; } else { re
turn array.from(result); } } } const re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); const str = '2016-01-02|2019-03-07'; const result = str.matchall(re); console.l...
RegExp.prototype[@@replace]() - JavaScript
the [@@replace]() method replaces some or all matches of a this pattern in a string by a replacement, and re
turns the result of the replacement as a new string.
... re
turn value a new string with some or all matches of a pattern replaced by a replacement.
... for example, following two examples re
turn same result.
... 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].
RegExp.prototype[@@search]() - JavaScript
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.
...for example, the following two examples re
turn the same result.
... 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].
get RegExp[@@species] - JavaScript
the regexp[@@species] accessor property re
turns the regexp constructor.
... description the species accessor property re
turns the default constructor for regexp objects.
... 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.
...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.exec() - JavaScript
re
turns a result array, or null.
... 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.toString() - JavaScript
the tostring() method re
turns a string representing the regular expression.
... syntax regexobj.tostring(); re
turn value a string representing the given object.
...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/' 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.
... 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.
...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.delete() - JavaScript
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.
...myset.delete('foo'); // re
turns true.
... myset.has('foo'); // re
turns false.
String.prototype.concat() - JavaScript
the concat() method concatenates the string arguments to the calling string and re
turns a new string.
... re
turn value a new string containing the combined text of the strings provided.
... description the concat() function concatenates the string arguments to the calling string and re
turns a new string.
... changes to the original string or the re
turned string don't affect the other.
String.prototype.includes() - JavaScript
the includes() method determines whether one string may be found within another string, re
turning true or false as appropriate.
...(defaults to 0.) re
turn value true if the search string is found anywhere within the given string; otherwise, false if not.
...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) { throw typeerror('first argument must not be a regexp'); } if (start === undefined) { start = 0; } re
turn this.indexof(search, start) !== -1; }; } examples using includes() const str = 'to be, or not to be, that is the question.' console.log(str.includes('to be')) // true console.log(str.includes('question')) // true console.log(str.includes('nonexistent')) // false console.log(str.includes('to be', 1)) // false console.log(str.includes('to be')) // false console.log(str.includes('')) // true specifications specification ...
String.prototype.link() - JavaScript
re
turn value a string containing an <a> html element.
...the re
turned string can then be added to the document via document.write() or element.innerhtml.
... 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.repeat() - JavaScript
the repeat() method constructs and re
turns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
... re
turn value a new string containing the specified number of copies of the given string.
... 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.
...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.substr() - JavaScript
the substr() method re
turns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
... syntax str.substr(start[, length]) parameters start the index of the first character to include in the re
turned substring.
... re
turn value a new string containing the specified part of the given string.
...to use this feature in jscript, you can use the following code: // only run when the substr() function is broken if ('ab'.substr(-1) != 'b') { /** * get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to re
turn * @re
turn {string} */ string.prototype.substr = function(substr) { re
turn function(start, length) { // call the original method re
turn substr.call(this, // did we get a negative start, calculate how much it is from the beginning of the string // adjust the start parameter for negative value start < 0 ?
String.prototype.toLocaleUpperCase() - JavaScript
the tolocaleuppercase() method re
turns the calling string value converted to upper case, according to any locale-specific case mappings.
... re
turn value a new string representing the calling string converted to upper case, according to any locale-specific case mappings.
... description the tolocaleuppercase() method re
turns the value of the string converted to upper case according to any locale-specific case mappings.
...the following can re
turn false: x.tolocalelowercase() === x.tolocaleuppercase().tolocalelowercase() examples using tolocaleuppercase() 'alphabet'.tolocaleuppercase(); // 'alphabet' 'gesäß'.tolocaleuppercase(); // 'gesÄss' 'i\u0307'.tolocaleuppercase('lt-lt'); // 'i' let locales = ['lt', 'lt', 'lt-lt', 'lt-u-co-phonebk', 'lt-x-lietuva']; 'i\u0307'.tolocaleuppercase(locales); // 'i' specifications spec...
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).
... syntax str.touppercase() re
turn value a new string representing the calling string converted to upper case.
... description the touppercase() method re
turns the value of the string converted to uppercase.
... 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'.
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.
... 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.
...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
re
turn true to keep the element, false otherwise.
... 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.
... 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.
TypedArray.prototype.reduce() - JavaScript
syntax typedarray.reduce(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously re
turned in the last invocation of the callback, or initialvalue, if supplied (see below).
... re
turn value the value that results from the reduction.
...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]).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.reduceRight() - JavaScript
syntax typedarray.reduceright(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously re
turned in the last invocation of the callback, or initialvalue, if supplied (see below).
... re
turn value the value that results from the reduction.
...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.
WeakRef - JavaScript
instance methods weakref.prototype.deref() re
turns the weakref object's target object, or undefined if the target object has been reclaimed.
...that is, you can only "see" an object get reclaimed between
turns of the event loop.
... 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(element); this.start(); } start() { if (this.timer) { re
turn; } this.count = 0; const tick = () => { // get the element from the weak reference, if it still exists const element = this.ref.deref(); if (element) { element.textcontent = ++this.count; } else { // the element doesn't exist anymore console.log("the element is gone."); this.stop(); this.ref = null; } }; tick(); this.timer = setinterval(tick, 1000); } stop() ...
WeakSet.prototype.delete() - JavaScript
re
turn value true if an element in the weakmap object has been removed successfully.
... examples using the delete method var ws = new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // re
turns false.
...ws.delete(window); // re
turns true.
... ws.has(window); // re
turns false.
WebAssembly.instantiate() - JavaScript
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.
... re
turn value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module.
... re
turn value a promise that resolves to an webassembly.instance object.
encodeURIComponent() - JavaScript
re
turn value a new string representing the provided string encoded as a uri component.
... to be more stringent in adhering to rfc 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized uri delimiting uses, the following can be safely used: function fixedencodeuricomponent(str) { re
turn encodeuricomponent(str).replace(/[!'()*]/g, function(c) { re
turn '%' + c.charcodeat(0).tostring(16); }); } examples encoding for content-disposition and link headers the following example provides the special encoding required within utf-8 content-disposition and link server response header parameters (e.g., utf-8 filenames): var filename = 'my file(2).txt'; var header = "content-dispo...
...sition: attachment; filename*=utf-8''" + encoderfc5987valuechars(filename); console.log(header); // logs "content-disposition: attachment; filename*=utf-8''my%20file%282%29.txt" function encoderfc5987valuechars(str) { re
turn encodeuricomponent(str).
... // the following are not required for percent-encoding per rfc5987, // so we can allow for a little better readability over the wire: |`^ replace(/%(?:7c|60|5e)/g, unescape); } // here is an alternative to the above function function encoderfc5987valuechars2(str) { re
turn encodeuricomponent(str).
Lexical grammar - JavaScript
\n u+000d carriage re
turn <cr> new line character in commodore and early mac systems.
... 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.
...ine 2` `string text ${expression} string text` tag `string text ${expression} string text` automatic semicolon insertion some javascript statements must be terminated with semicolons and are therefore affected by automatic semicolon insertion (asi): empty statement let, const, variable statement import, export, module declaration expression statement debugger continue, break, throw re
turn the ecmascript specification mentions three rules of semicolon insertion.
...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.
Optional chaining (?.) - JavaScript
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.
...if obj.first is null or undefined, the expression automatically short-circuits, re
turning undefined.
... 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 ?.
await - JavaScript
rv re
turns the fulfilled value of the promise, or the value itself if it's not a promise.
...after the await defers the 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.
new operator - JavaScript
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.
... 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.
try...catch - JavaScript
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.
... 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); 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.
Autoplay guide for media and Web Audio APIs - Web media technologies
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).
...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.
... 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.
Critical rendering path - Web Performance
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 server re
turns the html - response headers and data.
...the html response
turns into tokens which
turns into nodes which
turn into the dom tree.
Populating the page: how browsers work - Web Performance
your browser requests a dns lookup, which is eventually fielded by a name server, which in
turn responds with an ip address.
... congestion control as the server sends data in tcp packets, the user's client confirms delivery by re
turning acknowledgements, or acks.
...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.
... in our example, suppose the initial layout occurs before the image is re
turned.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
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 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.
... 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.
...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.
current - XPath
syntax current() re
turns a node-set containing only the current node.
... 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 .
...thus within all of the following three expressions the current function (not the entire expressions) re
turns the same node.
...re
turns the bar node, which may be different from the current node.
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.
...the re
turned node set is the nodes corresponding to those 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.
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.
...part of this string will be re
turned.
...everything after the first occurrence ofneedle inhaystack will be re
turned.
... re
turns a string.
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.
...part of this string will be re
turned.
...everything before the first occurrence ofneedle inhaystack will be re
turned.
... re
turns a string.
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.
...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.
Exported WebAssembly functions - WebAssembly
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.
...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.
...testfunc.tostring() re
turns an interesting result: function 0() { [native code] } this gives you more of an idea of its wrapper-type nature.
... 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.
Reddit Example - Archive of obsolete content
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.
... 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.
l10n - Archive of obsolete content
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.
... if this function can't find the string referenced by the identifier parameter, it re
turns the identifier itself.
... 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.
tabs - Archive of obsolete content
getthumbnail() re
turns thumbnail data uri of the page currently loaded in this tab.
...optional re
turns worker : the worker object can be used to communicate with the content script.
... re
turns the mime type that the document currently loaded in the tab is being rendered as.
console/traceback - Archive of obsolete content
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.
dev/panel - Archive of obsolete content
then(writetablist); }); function listtabs(root) { re
turn root.listtabs(); } function writetablist(tablist) { content.textcontent = tablist.tabs[tablist.selected].url; } we don't have detailed documentation for volcan.js, but it's coming soon.
... connecting volcan.js provides a global connect() function that takes a messageport connected to the debugger server, and re
turns a promise which is fulfilled with an object representing the root actor: volcan.connect(debuggee).then(gotroot); function gotroot(root) { // can use root actor here } actors actors in the remote debugging protocol are volcan.js objects.
... if a message is expected to get a reply, then the method re
turns a promise which is fulfilled with the reply.
event/target - Archive of obsolete content
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.
... re
turns eventtarget : re
turns the eventtarget instance removelistener(type, listener) removes an event listener for the given event type.
... re
turns eventtarget : re
turns the eventtarget instance off() an alias for removelistener.
io/byte-streams - Archive of obsolete content
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.
... re
turns string : a string containing the bytes read.
... if the stream is at the end, re
turns the empty string.
net/url - Archive of obsolete content
globals functions readuri(uri, options) reads a uri and re
turns a promise.
... options : object optional options: name type sync boolean if this option is set to true, the promise re
turned will be resolved synchronously.
... re
turns promise : the promise that will be resolved with the content of the url given.
places/favicon - Archive of obsolete content
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 platform service (moziasyncfavicons) retrieves favicon data stored from previously visited sites, and as such, will only re
turn favicon urls for visited sites.
... re
turns promise : a promise that resolves with the favicon url.
system/xul-app - Archive of obsolete content
re
turns boolean : true if the host application is name and false otherwise.
... re
turns boolean : true if the host application is one of the names and false otherwise.
... re
turns boolean : true if version falls in the given range and false otherwise.
util/deprecate - Archive of obsolete content
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.
... 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.
util/object - Archive of obsolete content
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.
... re
turns object : the new, merged object.
util/uuid - Archive of obsolete content
if this argument is supplied, it will be converted to an nsid and re
turned.
... otherwise a new nsid will be generated and re
turned.
... re
turns nsid : a uuid, represented as an nsid object.
Display a Popup - Archive of obsolete content
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.
...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.
...type some text and press "re
turn" and you should see the output in the console.
Localization - Archive of obsolete content
then it retrieves and re
turns the localization appropriate for the count you supplied.
... 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.
... then when the locale is "en-us", the system would fail to find a .properties file, and re
turn "hello!".
File I/O - Archive of obsolete content
it re
turns the user-specified file as nsifile.
... re
turn; } // the file data is contained within inputstream.
... re
turn; } // data has been written to the file.
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...
...endchild(this.otbody); }; function ondocclick (opssevt) { const oevt = opssevt || /* ie */ window.event; var boutside = true; for (var onode = oevt.target || /* ie */ oevt.srcelement; onode; onode = onode.parentnode) { if (onode.classname === sprefs + "-calendar" || onode.classname === sdpclass) { boutside = false; break; } } if (boutside) { re
turn; } ainstances[onode.id.replace(rbgnnan, "")].container.style.zindex = nzindex++; } function onheadclick () { const bismonth = rmonth.test(this.id), ndelta = rdecrease.test(this.id) ?
..."getmonth" : "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 u...
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 ...
... 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 lookupprefix only function _lookupnamespaceprefix (namespaceuri, originalelement) { var xmlnspattern = /^xmlns:(.*)$/; if (originalelement.namespaceuri && originalelement.namespaceuri === namespaceuri && originalelement.prefix && originalelement.lookupnamespaceuri(originalelement.prefix) === namespaceuri) { re
turn ...
...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; } ...
Delayed Execution - Archive of obsolete content
queuing a task in the main event loop when a task needs to be only briefly delayed, such that it runs after the current call chain re
turns, it can be added directly to the main thread's event queue rather than scheduled as a timeout: function executesoon(func) { services.tm.mainthread.dispatch(func, ci.nsithread.dispatch_normal); } using nsitimers to schedule tasks in instances where settimeout() and setinterval() are unavailable, or insufficient, tasks can be scheduled with delays using nsitimer instances.
... 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.
... let idx = delay.timers.push(timer) - 1; re
turn idx; } repeat.timers = []; // repeat a task every 1200ms repeat(1200, doathing); // do something 320ms from now delay(320, dosomething); ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
if not, re
turn immediately to the beginning of this article and don't come back til you have a functioning firefox.exe.
...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 __location__ re
turns the components/, and the parent of this is the extension directory.
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, ...
...} and then on shutdown of your bootstrapped addon make sure to destroy the factory: function shutdown(adata, areason) { if (areason == app_shutdown) { re
turn } // ...
Jetpack Processes - Archive of obsolete content
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.
...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.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
ssert.equals(calc.pop(), 3); } } listing 3: additional content for calc.js function rpncalc() { this.stack = 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.
...what if you attempt to run with nothing in the stack—what result will you re
turn then?
... listing 4: test_calc.js (adding sample test case) '2 1 -': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.minus(); assert.equals(calc.pop(), 1); }, listing 5: calc.js (implementing subtraction operation) minus: function() { this._letfunc(this._minus); }, _minus: function(a, b) { re
turn a - b; }, listing 6: calc.js (correcting mistake in implementation of subtraction) _letfunc: function(func) { // correct pop order b = this.pop(); a = this.pop(); this.push(func(a, b)); }, understanding source code in the open-source community, you can learn a lot about how software works by studying its source code; with a massive project like firefox, people typically use special source...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
<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 type="password" will
turn the textbox into a special password-entry field, in which characters are hidden as they're typed.
... key keycode name re
turn vk_re
turn enter vk_enter backspace vk_back_space delete vk_delete escape vk_escape ↑ vk_up ↓ vk_down ← vk_left → vk_right table 3: typical keycode names using modifier keys use the modifiers attribute with one or more of the following comma-delimited values: "control", "alt", "shift...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
closures will ensure the code is still valid, even if your outer function already re
turned from execution.
... addeventlistener("load", myaddon.init.bind(myaddon), true); settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() re
turns a new function.
... 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.
Connecting to Remote Content - Archive of obsolete content
following initialization, onload and onerror handlers are registered to a callback function to handle the response re
turned from the remote server.
...let's assume that the xml re
turned from remote server is this: <?xml version="1.0"?> <data> <shops> <shop> <name>apple</name> <code>a001</code> </shop> <shop> <name>orange</name> </shop> </shops> <total>2</total> </data> when a valid xml response comes back from the remote server, the xml document object can be manipulated using different dom methods, to display the data in the ui or st...
...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.
Adding preferences to an extension - Archive of obsolete content
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".
... that involves
turning each function into a member of the stockwatcher class.
... 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.
Creating a dynamic status bar extension - Archive of obsolete content
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).
...finally, we send the request to the server and re
turn.
...we then fetch the result re
turned by the web server into the variable output from the xmlhttprequest.responsetext property.
Dehydra Function Reference - Archive of obsolete content
it also re
turns the current values of these flags.
...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.
...read_file(filename) read a file a re
turn it as a string.
Drag and Drop Example - Archive of obsolete content
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); } ...
... } } the getsupportedflavours function needs only to re
turn a list of flavours that the stack can accept to be dropped on it.
... </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); } ...
Drag and Drop - Archive of obsolete content
the function re
turns an object that implements nsidragsession.
...the second argument, index, should be the index of the item to re
turn.
... isdataflavorsupported(flavor) re
turns true if the data being dragged contains data of the specified flavor.
Building Firefox with Rust code - Archive of obsolete content
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 your crate has optional features that aren't normally
turned on, you are strongly encouraged to remove dependencies for those features when importing code so the build system doesn't require that (unused) code to live in-tree.
... if this
turns out to be a serious problem in practice, we can look into ways of relaxing that check.
Introducing the Audio API extension - Archive of obsolete content
the function re
turns the number of samples written, which is useful for the next writing.
...to do this start writing the data in small portions and wait for the value re
turned by mozcurrentsampleoffset() to be greater than 0.
...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> ...
Frequently Asked Questions - Archive of obsolete content
the native svg support must be
turned off before mozilla will look to see if there's an svg plugin installed.
...when you double click on the pref you will see its value change to and from true/false,
turning the native support on/off.
...tim is working on implementing <filter> and working on items that need to be done before
turning on svg by default.
Anonymous Content - Archive of obsolete content
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.
...it is a focusable element that in
turn is made up of two focusable anonymous elements: a textfield and a button.
Elements - Archive of obsolete content
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.
...the re
turn value of the script represents the value of the property that will be re
turned to the requestor.
Using XPInstall to Install Plugins - Archive of obsolete content
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 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.
...c:\winnt\system32\ directory var windirectory = getfolder("win system"); // create the folder c:\winnt\system32\myplugin var dllwin32folder = getfolder("file:///", windirectory+"\\myplugin\\"); //install dll to c:\windows folder copyerr = addfile("", version, plugin_file, dllwin32folder, null); if (copyerr != 0) { logcomment("first install:"+copyerr); re
turn copyerr; } // install the xpt file to c:\winnt\system32\myplugin folder var xptwin32folder = getfolder("file:///", windirectory+"\\myplugin\\"); copyerr = addfile("", version, component_file, xptwin32folder, null); if (copyerr != 0) { logcomment("first install:"+copyerr); re
turn copyerr; } once the secondary installation has taken place, the win32 registry keys hav...
Windows Install - Archive of obsolete content
spaceavailable = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spacerequired + " k"); logcomment(" available: " + spaceavailable + " k"); re
turn(false); } re
turn(true); } function updatewinreg4ren8dot3() { var fprogram = getfolder("program"); var ftemp = getfolder("temporary"); //notes: // can't use a double backslash before subkey // - windows already puts it in.
...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...
...ogram, // 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 ...
dirGetParent - Archive of obsolete content
dirgetparent re
turns an object representing the parent directory of the current directory or file.
... 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" ...
windowsGetShortName - Archive of obsolete content
summary re
turns a path that conforms to the windows 8.3 file naming convention.
... re
turns a string with the windows shortname.
... if the path already conforms to 8.3, the re
turn value is null.
getString - Archive of obsolete content
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.
...unlike that function, this method does not support using a null key to re
turn a list of keys in a section.
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.
... example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey ( winreg.hkey_local_machine ); if(winreg.iskeywritable("software")) { //iskeywritable re
turned true } else { //iskeywritable re
turned false } ...
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.
... example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.keyexists("software\\mozilla")) { //keyexists re
turned true } else { //keyexists re
turned false } } ...
valueExists - Archive of obsolete content
valueexists re
turns whether a value for the given key exists.
... re
turns boolean value: true if the key exists and the user has read access to it, otherwise false.
... example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.valueexists("software\\mozilla", "value name")) { //valueexists re
turned true } else { //valueexists re
turned false } } ...
Methods - Archive of obsolete content
iskeywritable re
turns whether the given key is writable.
... keyexists re
turns whether the given key exists or is readable.
... valueexists re
turns whether the given value exists.
Dynamically modifying XUL-based user interface - Archive of obsolete content
the most well known dom method is probably document.getelementbyid(), which re
turns an element, given its id.
... 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: // 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.
Introduction to XUL - Archive of obsolete content
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 ?
... getelementsbyattribute re
turns a list of elements for which the named attribute has the given value.
... interface xulelement : element { nodelist getelementsbyattribute(in domstring name, in domstring value); }; getelementsbyattribute functions as does its namesake in xuldocument, though this version re
turns only those elements which match the criteria and are descendants (in css selector terminology) of the given element.
appendNotification - Archive of obsolete content
« xul reference home appendnotification( label , value , image , priority , buttons, eventcallback ) re
turn type: element create a new notification and display it.
... if the re
turn value from this function is not true, then the notification is closed.
... .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.
... <script language="javascript"> function removeselecteditem(){ var mylistbox = document.getelementbyid('mylistbox'); if(mylistbox.selectedindex == -1){ re
turn; // no item selected so re
turn }else{ mylistbox.removeitemat(mylistbox.selectedindex); } } function removeallitems(){ var mylistbox = document.getelementbyid('mylistbox'); var count = mylistbox.itemcount; while(count-- > 0){ mylistbox.removeitemat(0); } } </script> <button label="remove selected item" oncommand="removeselecteditem()"/> <button label="remove all items" oncommand="removeallitems()"/> <listbox id="mylistbox"> <listitem label="alpha"/> <listitem label="beta"/> <listitem label="oscar"/> <listitem label="foxtrot"/> </listbox> see also removeallit...
MenuModification - Archive of obsolete content
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.
... <script> function addsubmenu() { var popup = document.getelementbyid("file-popup"); if (popup.haschildnodes()) re
turn; 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.
PopupEvents - Archive of obsolete content
when calling either the openpopup or openpopupatscreen methods, the popup will not actually be open before that method re
turns.
...<script> function openfilemenu() { var filemenu = document.getelementbyid("file-menu"); filemenu.addeventlistener("popupshown", filemenuopened, false); filemenu.open = true; } function filemenuopened(event) { if (event.target != document.getelementbyid("file-menupopup")) re
turn; var filemenu = document.getelementbyid("file-menu"); filemenu.removeeventlistener("popupshown", filemenuopened, false); var openmenu = document.getelementbyid("open-menu"); openmenu.open = true; } </script> <menu id="file-menu" label="file"> <menupopup id="file-menupopup"> <menu id="open-menu" label="open"> <menupopup> <menuitem label="file..."/> <menuitem ...
...the filemenuopened function first checks that the target of the event is the right popup and re
turns early if not.
textbox.label - Archive of obsolete content
otherwise it re
turns the value of the associated label element, if applicable.
... otherwise it re
turns the placeholder or emptytext property.
... 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.
Rule Compilation - Archive of obsolete content
this will re
turn a table of result records which are then used to generate output.
...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.
XML Templates - Archive of obsolete content
just place an expr attribute on the query element containing an xpath expression re
turns the set of results to output.
...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.
Adding Methods to XBL-defined Elements - Archive of obsolete content
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.
...the function re
turns an array of elements, which is the anonymous content.
...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.
Custom Tree Views - Archive of obsolete content
getcelltext( row , column ) this method should re
turn the text contents at the specified row and column.
... here is an example of defining such as object, which can be called whatever you want: //moz 1.8 var treeview = { rowcount : 10000, getcelltext : function(row,column){ if (column.id == "namecol") re
turn "row "+row; else re
turn "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ re
turn false; }, isseparator: function(row){ re
turn false; }, issorted: function(){ re
turn false; }, getlevel: function(row){ re
turn 0; }, getimagesrc: function(row,col){ re
turn null; }, getrowproperties: function(row,props){}, getc...
... example custom tree source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window title="tree example" id="tree-window" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="setview();"> <script> //moz 1.8 var treeview = { rowcount : 10000, getcelltext : function(row,column){ if (column.id == "namecol") re
turn "row "+row; else re
turn "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ re
turn false; }, isseparator: function(row){ re
turn false; }, issorted: function(){ re
turn false; }, getlevel: function(row){ re
turn 0; }, getimagesrc: function(row,col){ re
turn null; }, getrowproperties: function(row,props){}, getc...
RDF Datasources - Archive of obsolete content
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.
...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.
...this causes only the descendants of this list to be re
turned.
Tree Selection - Archive of obsolete content
the first function re
turns the number of selection ranges there are.
...then, we iterate over the set of ranges, the number of which is re
turned by the getrangecount() function.
...it takes a row index as an argument and re
turns true if that row is selected.
Trees - Archive of obsolete content
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.
...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.
...inside the body are individual rows, which may in
turn contain other rows.
XUL accessibility guidelines - Archive of obsolete content
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.
...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.
...provide a mechanism for
turning media and movement on and off.
arrowscrollbox - Archive of obsolete content
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.
... scrollbyindex( lines ) re
turn type: no re
turn value scrolls the contents of the arrowscrollbox by a certain number of lines.
... scrollbypixels( pixels ) re
turn type: no re
turn value scrolls the contents of the arrowscrollbox by a certain number of pixels.
editor - Archive of obsolete content
methods geteditor( window ) re
turn type: nsieditor re
turns the editing interface for the editor which contains numerous methods for manipulating the document.
... gethtmleditor( window ) re
turn type: nsihtmleditor re
turns the html editing interface for the editor which contains methods for manipulating an html document.
... makeeditable( editortype, waitforload ) re
turn type: no re
turn value this function enables editing for an editor.
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.
...re
turns -1 if no items are selected selectedpanel type: element holds a reference to the currently selected panel within a <tabbox> element.
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); }, ...
... 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(acompmgr, acid, aiid) { if (acid.equals(class_id)) re
turn apphandler.queryinterface(aiid); throw components.results.ns_error_failure; }, registerself : function...
... 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); ...
Mozilla release FAQ - Archive of obsolete content
in re
turn for this, netscape (aol) contributes developers to work on the project.
.../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.
...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.
NPN_Evaluate - Archive of obsolete content
result on re
turn, contains the value re
turned by the script.
... re
turns true if the script was evaluated successfully, otherwise false.
... note: the caller must call npn_releasevariantvalue() to release the re
turned value when it's no longer needed.
NPN_GetProperty - Archive of obsolete content
<tt>result</tt> on re
turn, contains the value of the specified property.
... re
turns true if the value was retrieved successfully, otherwise false.
... note: the caller must call npn_releasevariantvalue() to release the re
turned value when it's no longer needed.
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>.
NPN_MemFlush - Archive of obsolete content
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.
...to request that the browser free as much memory as possible, call npn_memflush() repeatedly until it re
turns 0.
NPN_PluginThreadAsyncCall - Archive of obsolete content
re
turns nothing.
...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.
NPN_PostURL - Archive of obsolete content
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.
...npn_posturl is typically asynchronous: it re
turns immediately and only later handles the request.
NPN_Write - Archive of obsolete content
re
turns if successful, the function re
turns a positive integer representing the number of bytes written (consumed by the browser).
... if unsuccessful, the plug-in re
turns a negative integer.
...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.
NPP_New - Archive of obsolete content
re
turns if successful, the function re
turns nperr_no_error.
... if unsuccessful, the function re
turns an error code.
... 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.
NPP_WriteReady - Archive of obsolete content
re
turns re
turns the maximum number of bytes that an instance is prepared to accept from the stream.
...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.
...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.
NP_GetValue - Archive of obsolete content
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.
Using IO Timeout And Interrupt On NT - Archive of obsolete content
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>.
...a possible solution is to add a <tt>pr_disableinterrupt()</tt> function to
turn off interrupts when accessing such file descriptors.
ArrayBuffer.transfer() - Archive of obsolete content
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.
... re
turn value a new arraybuffer object.
... if (!arraybuffer.transfer) { arraybuffer.transfer = 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 ...
Date.prototype.toLocaleFormat() - Archive of obsolete content
re
turn value a string representing the given date using the specified formatting.
... 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".
... 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.lbound - Archive of obsolete content
the vbarray.lbound method re
turns the lowest index value used in the specified dimension of a vbarray.
... syntax safearray.lbound(dimension) remarks if the vbarray is empty, the lbound method re
turns undefined.
...to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba){ var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } re
turn (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> 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 internet explorer 10 standards.
VBArray.ubound - Archive of obsolete content
the vbarray.ubound method re
turns the highest index value used in the specified dimension of the vbarray.
... remarks if the vbarray is empty, the ubound method re
turns undefined.
...o 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } re
turn (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> 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 internet explorer 10 standards.
Object.prototype.__noSuchMethod__ - Archive of obsolete content
// doesn't work with multiple inheritance objects as parents function nomethod(name, args) { var parents = this.__parents_; // go through all parents for (var i = 0; i < parents.length; i++) { // if we find a function on the parent, we call it if (typeof parents[i][name] == 'function') { re
turn parents[i][name].apply(this, args); } } // if we get here, the method hasn't been found throw new typeerror; } // used to add a parent for multiple inheritance function 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)...
... // 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, namedthing.prototype); namedthing.call(this, name); addparent(this, agedthing.prototype); agedthing.call(this, age); this.address = address; } person.prototype = { getaddr: function() { re
turn this.address; }, setaddr: function(addr) { this.address = addr; } } var bob = new person('bob', 25, 'new york'); console.log('getage is ' + (('getage' in bob) ?
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.
... re
turn value an iterator with the enumerable own and inherited properties of the target object.
... description the reflect.enumerate method re
turns an iterator with the enumerable own and inherited properties of the target object.
JavaObject - Archive of obsolete content
created by any java method which re
turns an object type.
... var thestring = new java.lang.string("hello, world"); 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.
... var thestring = new java.lang.string("hello, world"); thestring.getclass(); // re
turns java.lang.string see also javaarray, javaclass, javapackage, packages ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
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.
... listing 5 - demonstration of server-proxy <script runat="server"> function notexposed() { // runs on the server, hidden from the browser re
turn "can't see me!"; } function exposed() { // runs on the server, callable from the browser re
turn "exposed to the browser"; } exposed.proxy = true; // tell jaxer this function is ok to be called from the browser </script> <script runat="client" type="text/javascript"> alert( exposed() ); //works like a charm alert( notexposed() ); //produces an object not found error since it server-side only <...
...the function defined within this file checks the form to make sure it is complete, re
turning a boolean.
Reference - Archive of obsolete content
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.
...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...
... 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 ?
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...
...parser">null</field> <property name="domparser" readonly="true"> <getter> if (!this._domparser) this._domparser = new domparser(); re
turn this._domparser; </getter> </property> <method name="refresh"> <body> // get new value, parse, and import it.
... 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, "anonid", "content"); if (content.firstchild) { content.removechild(content.firstchild); } content.appendchild(impnode); re
turn true; </body> </method> </implementation> </binding> ...
Troubleshooting XForms Forms - Archive of obsolete content
instance(...) not working be aware that the instance(...) re
turns an element node, and not the document node.
... submission not working if you are trying to replace="instance" make sure that the document being re
turned is xml.
...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.
Building up a basic demo with PlayCanvas editor - Game development
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.
...ates a new boxanimation instance var boxanimation = function (entity) { this.entity = entity; }; boxanimation.prototype = { // called once after all resources are loaded and before the first update initialize: function () { }, // called every frame, dt is time in seconds since last update update: function (dt) { } }; re
turn boxanimation; }); the most interesting part is the update() function, which is where we can put any code that we want repeated on every frame.
... save the changes using the save button in the top right of the code editor, then re
turn to the main editor tab.
Audio for Web games - Game development
nst trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); re
turn audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing.
... let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); re
turn track; } let's also create a playtrack() function, which we can call once a file has been fetched.
... let offset = 0; function playtrack(audiobuffer) { const tracksource = audioctx.createbuffersource(); tracksource.buffer = audiobuffer; tracksource.connect(audioctx.destination) if (offset == 0) { tracksource.start(); offset = audioctx.currenttime; } else { tracksource.start(0, audioctx.currenttime - offset); } re
turn tracksource; } finally, let's loop over our <li> elements, grab the correct file for each one and then allow playback by hiding the "loading" text and displaying the play button: trackels.foreach((el, i) => { // get children const anchor = el.queryselector('a'); const loadtext = el.queryselector('p'); const playbutton = el.queryselector('button'); // load file loadfile(anchor.hre...
Efficient animation for web games - Game development
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.
...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).
Square tilemaps implementation: Static maps - Game development
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].
...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.
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... learn moreedit general knowledge newline on wikipedia carriage re
turn on wikipedia ...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... re
turn execution to the line that invoked sayhi() and continue executing the rest of the greeting() function.
... 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.
Function - MDN Web Docs Glossary: Definitions of Web-related terms
when a function is called, arguments are passed to the function as input, and the function can optionally re
turn a value.
...an outer function is a function containing a function (addsquares in this case): function addsquares(a,b) { function square(x) { re
turn x * x; } re
turn square(a) + square(b); }; //using ecmascript 2015 arrow notation const addsquares = (a,b) => { const square = x => x*x; re
turn square(a) + square(b); }; a recursive function is a function that calls itself.
... function loop(x) { if (x >= 10) re
turn; loop(x + 1); }; //using ecmascript 2015 arrow notation const loop = x => { if (x >= 10) re
turn; loop(x + 1); }; an immediately invoked function expressions (iife) is a function that is called directly after the function is loaded into the browser’s compiler.
CSS and JavaScript accessibility best practices - Learn web development
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).
... 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 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.
WAI-ARIA basics - Learn web development
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).
...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).
...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).
Cascade and inheritance - Learn web development
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.
...effectively, this "
turns on inheritance".
...we'd advise that you re
turn to this article a few times as you continue through the course, and keep thinking about it.
How do I start to design my website? - Learn web development
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?
... now that you know what you want to accomplish, it's time to
turn those goals into actionable steps.
...usually there
turn out to be more questions than we originally thought.
Other form controls - Learn web development
pressing re
turn) that will be included when the data is submitted.
...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.
...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.
The web and web standards - Learn web development
you wouldn't want a single company suddenly deciding to put the entire web behind a paywall, or releasing a new version of html that everyone has to buy to continue making web sites, or worse still, just deciding they aren't interested any more and just
turning it off.
...old web sites will still continue to work), and forwards compatible (future technologies in
turn will be compatible with what we currently have).
...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.
Creating hyperlinks - Learn web development
example that includes a cc, bcc, subject and body: <a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=the%20subject%20of%20the%20email&body=the%20body%20of%20the%20email"> send mail with cc, bcc, subject and body </a> note: the values of each field must be url-encoded, that is with non-printing characters (invisible characters like tabs, carriage re
turns, and page breaks) and spaces percent-escaped.
...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.
Responsive images - Learn web development
re
turning to our original not-responsive.html example, we have an image that badly needs art direction: <img src="elva-800w.jpg" alt="chris standing up holding his daughter elva"> let's fix this, with <picture>!
...x)" srcset="elva-480w-close-portrait.jpg"> <source media="(min-width: 800px)" srcset="elva-800w.jpg"> <img src="elva-800w.jpg" alt="chris standing up holding his daughter elva"> </picture> the <source> elements include a media attribute that contains a media condition — as with the first srcset example, these conditions are tests that decide which image is shown — the first one that re
turns true will be displayed.
...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.
Drawing graphics - Learn web development
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.
...the re
turned object is the same type as that which is re
turned when you grab a reference to an existing <img> element).
... now add the following code to the bottom of the javascript: function degtorad(degrees) { re
turn degrees * math.pi / 180; }; function rand(min, max) { re
turn math.floor(math.random() * (max-min+1)) + (min); } let length = 250; let moveoffset = 20; for(var i = 0; i < length; i++) { } here we are implementing the same degtorad() function we saw in the triangle example above, a rand() function that re
turns a random number between given lower and upper bounds, length and moveoffset vari...
What is JavaScript? - Learn web development
for example, let's re
turn to the block of javascript we saw in our first example: const para = document.queryselector('p'); para.addeventlistener('click', updatename); function updatename() { let name = prompt('enter a new name'); para.textcontent = 'player 1: ' + name; } here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the upda...
... 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.
...in interpreted languages, the code is run from top to bottom and the result of running the code is immediately re
turned.
Object-oriented JavaScript for beginners - Learn web development
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.
...i\'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?
...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.
Ember interactivity: Events, classes and state - Learn web development
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 re
turned by the service’s all() getter: {{#each this.todos.all as |todo|}} <todo @todo={{todo}} /> {{/each}} another way to look at this: this — the rendering context / component instance.
... all — a getter on the todo-data service that re
turns all the todos.
Introduction to client-side frameworks - Learn web development
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.
...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.
...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.
Componentizing our Svelte app - Learn web development
this will re
turn a dispatch() function that will allow us to emit custom events.
...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.
...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.
Strategies for carrying out testing - Learn web development
they can be easily
turned into sets of instructions for user groups to follow when carrying out tests (e.g.
...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.
... next we'll
turn our attention to the actual code issues your testing might uncover, starting with html and css.
Adding a new event
virtual internalfooevent* asfooevent() moz_override this method should just re
turn this.
...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 your event cannot be fired easy, you should add the test but canrun should re
turn false and call todo().
Adding phishing protection data providers
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.
... browser.safebrowsing.provider.idnum.keyurl an url that re
turns a private key to be used for encrypting of other requests.
...this request must be encrypted using the private key re
turned by the keyurl request.
Experimental features in Firefox
nightly 78 yes developer edition 78 yes beta 78 yes release 78 no preference name network.preload css display stray control characters in css as hex boxes this feature renders control characters (unicode category cc) other than tab (u+0009), line feed (u+000a), form feed (u+000c), and carriage re
turn (u+000d) as a hexbox when they are not expected.
... 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.
... 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.
Limitations of chrome scripts
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.
...in this case, the shim will re
turn a javascript object that looks somewhat like a window or a document for about:blank.
...it will re
turn a dummy nsiloadcontext when asked, but any attempt to get a window out of it will fail.
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...
... if(resultlist.every((r) => r == true)) re
turn ci.nsicontentpolicy.accept; re
turn ci.nsicontentpolicy.reject_request; } }); // more boilerplate code here this example is a (somewhat condensed) content policy which gets triggered for every network request in a child process to either allow or deny the request.
... 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.
HTMLIFrameElement.getScreenshot()
syntax var instanceofdomrequest = instanceofhtmliframeelement.getscreenshot(maxwidth, maxheight, mimetype); re
turns a domrequest for handling the screenshot request.
... 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.
HTMLIFrameElement.getStructuredData()
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.
...ument.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getstructureddata(); request.onsuccess = function() { console.log(request.result); } }); running this code in a browser api app and then loading up a page that contains microdata (such as the website of british alt-country band salter cane) will result in a json object being re
turned, along the lines of: { "items": [ { "type":["http://microformats.org/profile/hcard"], "properties":{"fn":["chris askew"], "n":[ { "properties": { "given-name":["chris"], "family-name":["askew"], ...
mozbrowseractivitydone
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.
... 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).
mozbrowserfindchange
details the details property re
turns an anonymous javascript object with the following properties: active a boolean indicating whether a search is currently active (true), or not (false.) searchstring a domstring representing the string that is currently being searched for.
... searchlimit a number indicating the maximum number of searches that can be re
turned.
... numberofmatches a number indicating the number of matches re
turned by the search.
IPDL Best Practices
es one-shot protocols like this) actor::recv__delete__ - cleanup, ipdl calls still valid but ill-advised actor::actordestroy - non-ipdl cleanup manager::deallocpprotocol - deallocation one construct to avoid: class protocolparent { public: ~protocolparent() { send__delete__(this); } }; class protocolmanagerparent { public: pprotocolparent* allocpprotocol() { re
turn new protocolparent(); } bool deallocpprotocol() { re
turn true; } }; nsautoptr<pprotocolparent> parent = manager->sendpprotocolconstructor(); while this may look appealing as the ipdl logic is stuffed away in a sensible place, it breaks under error conditions.
... 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.
Introduction to Layout in Mozilla
creates a parser, re
turned as nsistreamlistener back to the docshell creates a content sink, which is linked to the parser and the document creates a documentviewerimpl object, which is re
turned as nsicontentviewer back to the docshell documentviewerimpl creates pres context and pres shell content model construction content arrives from network via nsistreamlistener::ondataavailable ...
...notifications passes these to the style set object, who in
turn passes to the frame constructor frame constructor creates frames constructframeinternal recursively walks content tree, resolves style and creates frames either created by tag (<select>) or by display type (<p>) frame manager maintains mapping from content to frame style resolution compute stylistic information based on the style rules that apply for the frame�...
...yle context object is a placeholder for partially computed stylistic data style data is computed lazily, as it is asked for reflow recursively compute geometry (x, y, w, h) for frames, views, and widgets given w & h constraints of “root frame” compute (x, y, w, h) for all children constraints propagated “down” via nshtmlreflowstate desired size re
turned “up” via nshtmlreflowmetrics basic pattern parent frame initializes child reflow state (available w, h); places child frame (x, y); invokes child’s reflow method child frame computes desired (w, h), re
turns via reflow metrics parent frame sizes child frame and view based on child’s metrics n.b.
InstallListener
a listener may re
turn false to cancel the download.
...a listener may re
turn false to cancel the download.
...a listener may re
turn false to cancel the install.
Add-on Manager
many functions in the add-on manager interface operate asynchronously re
turning results through callbacks passed to the functions.
...the callback may well only be called after the api function re
turns.
...any available update is re
turned as an addoninstall which is ready to be downloaded and installed.
FxAccountsProfileClient.jsm
constructor fxaccountsprofileclient() creates and re
turns a new fxaccountsprofileclient object.
... re
turn value a newly created fxaccountsprofileclient object implementing the methods described in this article.
...parameters none re
turn value promise resolves: object - successful response from the '/profile' endpoint.
OS.File.Info
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.
...(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.
...on unix systems it was re
turning the last modified date and thus it was deprecated.
PerfMeasurement.jsm
re
turn value a new perfmeasurement object configured to record the specified event types.
...re
turn value if even one of the event types can be recorded, this will re
turn true.
... otherwise, it re
turns false.
Localization formats
$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.
... <h1><?php echo ___("getting started")?></h1> function ___($str) { re
turn $array[$str]; } advantage to .lang simple work-flow allowing the web developer to place the file in svn and it can appear on the staging server .lang syntax is like simplified .po, which many localizers who are familiar with linux and other projects understand mozilla has a basic tool called main.lang checker, which can show any untranslated files to the localizer no need to compile to .mo file so a localizer can see his/her changes more quickly creating simple diffs .lang files will be cached which will reduce any slowness effect disadvantage to .lang no plural forms no context for localizers unless you provide good comments no styling by localizers if it is needed may be...
...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.
JS::PerfMeasurement
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.
... it will re
turn null if javascript passed in something with the wrong dynamic type.
NSPR's Position On Abrupt Thread Termination
all threads must unwind and re
turn from their root function.
...this process continues until the thread either recovers from the malady or re
turns from the root function.
...the definition of the language c is such that re
turning from main() is a perfectly fine thing to do.
PL_HashTableRemove
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.
... remark this function should re
turn prstatus.
PRLinger
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.
... 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 to change this default as follows: if polarity is set to pr_false, pr_close re
turns immediately, but if there are any data remaining in the socket send buffer, the runtime attempts to deliver the data to the peer.
PR_AtomicSet
atomically sets a 32-bit value and re
turn its previous contents.
... re
turns the function re
turns the prior value of the referenced variable.
...the re
turned value is the value that was readbefore memory was updated.
PR_CEnterMonitor
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.
...in the former case, the entry count is simply incremented and the function re
turns.
PR_CreateIOLayerStub
re
turns a new file descriptor for the specified layer.
...the file descriptor re
turned contains the pointer to the i/o methods table provided.
... the caller should override appropriate contents of the file descriptor re
turned before pushing it onto the protocol stack.
PR_CreatePipe
on re
turn, this parameter contains the file descriptor for the read end of the pipe.
...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.
PR_CreateThread
re
turning from this function is the only way to terminate a thread.
... 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.
PR_DELETE
syntax #include <prmem.h> void pr_delete(_ptr); parameter _ptr the address of memory to be re
turned to the heap.
... re
turns nothing.
... description this macro re
turns allocated memory to the heap from the specified location and sets _ptr to null.
PR_FREEIF
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.
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_GMTParameters
re
turns the time zone offset information that maps the specified prexplodedtime to gmt.
... re
turns a time parameters structure that expresses the time zone offsets at the specified time.
... this is a trivial function; for any input, it re
turns a prtimeparameters structure with both fields set to zero.
PR_GetConnectStatus
re
turns the function re
turns one of these values: if successful, pr_success.
... 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.
...when pr_poll re
turns, call pr_getconnectstatus on the socket to determine whether the nonblocking connect has succeeded or failed.
PR_GetNameForIdentity
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.
...the string is copied by the runtime, and pr_getnameforidentity re
turns a pointer to that copy.
PR_GetProtoByName
buffer a pointer to a scratch buffer for the runtime to re
turn result.
...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.
PR_GetProtoByNumber
buffer a pointer to a scratch buffer for the runtime to re
turn result.
...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.
PR_GetSpecialFD
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_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
re
turns the function re
turns one of the following values: if the specified thread is currently blocked, pr_success.
... 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.
...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).
PR_IntervalNow
re
turns the value of nspr's free-running interval timer.
... syntax #include <prinrval.h> printervaltime pr_intervalnow(void); re
turns a printervaltime object.
... description you can use the value re
turned by pr_intervalnow() to establish epochs and to determine intervals (that is, compute the difference between two times).
PR_JoinThread
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.
...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.
PR_LIST_HEAD
re
turns the head of a circular 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.
... re
turns a pointer to a list element.
... description pr_list_tail re
turns the tail of the specified circular list.
PR_NEW
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_NEXT_LINK
re
turns the next element in a list.
... re
turns a pointer to a list element.
... description pr_next_link re
turns a pointer to the element following the specified element.
PR_NormalizeTime
re
turns nothing; the time parameter is altered by the callback function.
...on re
turn, tm_wday (and tm_yday) are set for you.
...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_OpenDir
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.
PR_PREV_LINK
re
turns the preceding element in a list.
... re
turns a pointer to a list element.
... description pr_prev_link re
turns a pointer to the element preceding the specified element.
PR_TicksPerSecond
re
turns the number of ticks per second currently used to determine the value of printervaltime.
... syntax #include <prinrval.h> pruint32 pr_tickspersecond(void); re
turns an integer between 1000 and 100000 indicating the number of ticks per second counted by printervaltime on the current platform.
... description the value re
turned by pr_tickspersecond() lies between pr_interval_min and pr_interval_max.
PR_UnloadLibrary
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.
...after calling this function, future references to the library using its identity as re
turned by pr_loadlibrary will be invalid.
PR_Write
re
turns one of the following values: a positive number indicates the number of bytes successfully written.
...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.
NSS_3.12.1_release_notes.html
re
turns a string that must be freed with port_free().
...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.
...ct list element count in pkix_list_appenditem function bug 442618: eliminate dead function cert_certpackagetype bug 443755: extra semicolon in pkm_tlskeyandmacderive makes conditional code unconditional bug 443760: extra semicolon in seqdatabase makes static analysis tool suspicious bug 448323: certutil -k doesn't report the token and slot names for found keys bug 448324: ocsp checker re
turns incorrect error code on request with invalid signing cert bug 449146: remove dead libsec function declarations bug 453227: installation of pem-encoded certificate without trailing newline fails documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation.
NSS 3.15 release notes
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.
... bugs fixed in nss 3.15 this bugzilla query re
turns all the bugs fixed in nss 3.15: https://bugzilla.mozilla.org/buglist.cgi?list_id=6278317&resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.15 ...
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...
...c: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.
... sha1 fingerprint: cb:a1:c5:f8:b0:e3:5e:b8:b9:45:12:d3:f9:34:a2:e9:06:10:d3:36
turned off websites trust bit (change requested by ca) cn = netlock uzleti (class b) tanusitvanykiado sha1 fingerprint: 87:9f:4b:ee:05:df:98:58:3b:e3:60:d6:33:e7:0d:3f:fe:98:71:af
turned off websites and code signing trust bits (1024-bit root) cn = netlock expressz (class c) tanusitvanykiado sha1 fingerprint: e3:92:51:2f:0a:cf:f5:05:df:f6:de:06:7f:75:37:e1:65:ea:57:4b
turned off websites and code signing trust bits (1024-bit root) bugs fixed in nss 3.16.3 this bugzilla query re
turns all the bugs fixed in nss 3.16.3: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&t...
NSS 3.32 release notes
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.
...(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.
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 ...
...string bug 1564727 - use a pss spki when possible for delegated credentials bug 1493916 - fix ppc64 inline assembler for clang bug 1561588 - remove -wmaybe-uninitialized warning in p7env.c bug 1561548 - remove -wmaybe-uninitialized warning in pkix_pl_ldapdefaultclient.c bug 1512605 - incorrect alert description after unencrypted finished msg bug 1564715 - read /proc/cpuinfo when at_hwcap2 re
turns 0 bug 1532194 - remove or fix -ddebug_$user from make builds bug 1565577 - visual studio's cl.exe -?
...n checks bug 1568803 - more tests for client certificate authentication bug 1564284 - support profile mobility across windows and linux bug 1573942 - gtest for pkcs11.txt with different breaking line formats bug 1575968 - add strsclnt option to enforce the use of either ipv4 or ipv6 bug 1549847 - fix nss builds on ios bug 1485533 - enable nss_ssl_tests on taskcluster this bugzilla query re
turns all the bugs fixed in nss 3.46: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.46 compatibility nss 3.46 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS Sample Code sample2
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.
...
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.
PKCS11 FAQ
if you do not actually do the operation specified by that function, you can re
turn ckr_function_not_supported.
... when do nss applications spawn threads off the main thread, which in
turn opens up a new pkcs #11 session?
... it's perfectly valid to reject the password change request with a re
turn value such as ckr_function_not_supported.
FC_DigestFinal
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.
... re
turn value examples see also fc_digestinit, nsc_digestfinal ...
FC_Finalize
re
turn value fc_finalize always re
turns ckr_ok.
... fc_finalize should check the preserved argument and re
turn ckr_arguments_bad if preserved is not null.
... fc_finalize should re
turn ckr_cryptoki_not_initialized if the library is not initialized.
FC_FindObjects
pusobjectcount [out] pointer to location to receive the number of re
turned handles.
... description fc_findobjects re
turns the next set of object handles matching the criteria set up by the previous call to fc_findobjectsinit and sets the object count variable to their number or to zero if there are none.
... re
turn value examples see also fc_findobjectsinit, nsc_findobjects ...
FC_GetSessionInfo
pinfo [out] pointer to the ck_session_info structure to be re
turned.
...if the nss cryptographic module is in the error state, fc_getsessioninfo re
turns ckr_device_error.
... re
turn value examples see also fc_closesession, nsc_opensession ...
FC_SignFinal
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.
... re
turn value examples see also fc_signupdate, nsc_signfinal ...
NSS Key Functions
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.
...seckeykeydbhandle re
turns a handle to the key database opened by nss_init.
NSS tools : pk12util
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.
... re
turn codes o 0 - no error o 1 - user cancelled o 2 - usage error o 6 - nls init error o 8 - certificate db open error o 9 - key db open error o 10 - file initialization error o 11 - unicode conversion error o 12 - temporary file creation error o 13 - pkcs11 get slot error o 14 - pkcs12 decoder start error o 15 - error read from import file o 16 - pkcs12 decode error o 17 - pkcs12 decoder verify error o 18 - pkcs12 decoder validate bags error o 19 - pkcs12 decoder import bags error o 20 - key db conversion version 3 to version 2 error o 21 - cert db conversion version 7 to version 5 error o...
...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.
sslkey.html
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.
...seckeykeydbhandle re
turns a handle to the key database opened by nss_init.
NSS tools : pk12util
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.
... re
turn codes o 0 - no error o 1 - user cancelled o 2 - usage error o 6 - nls init error o 8 - certificate db open error o 9 - key db open error o 10 - file initialization error o 11 - unicode conversion error o 12 - temporary file creation error o 13 - pkcs11 get slot error o 14 - pkcs12 decoder start error o 15 - error read from import file o 16 - pkcs12 decode error o 17 - pkcs12 decoder verify error o 18 - pkcs12 decoder validate bags error o 19 - pkcs12 decoder import bags error o 20 - key db conversion version 3 to version 2 error o 21 - cert db conversion version 7 to version 5 error o 22 - cert and key dbs patch error o 23 - get default cert db error o 24 - fin...
...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.
Proxies in Necko
it checks whether the passed-in uri should use a proxy, and re
turns an nsiproxyinfo if so.
...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.
Rhino serialization
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.
...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 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.
SpiderMonkey Internals
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.
...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.
...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.
JS::CloneFunctionObject
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.
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.
... 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.
JS::HandleValueArray
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.
JS::IsCallable
this article covers features introduced in spidermonkey 38 re
turn whether the given function object is callable/a valid constructor.
... 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.
JS::ToString
description js::tostring re
turns a string representation of a javascript value.
... on success, js::tostring re
turns a jsstring instance.
... on error or exception, it re
turns nullptr.
JSExtendedClass
re
turn the current outer object.
...re
turn the current inner object.
...creates and re
turns a new iterator.
JSExtendedClass.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.
...if it re
turns null or obj, then the js engine treats the object as though it were not a wrapper.
JSNewEnumerateOp
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.
...re
turn the next jsid in the iteration using *idp.
... the re
turn value is used to indicate success, with a value of false indicating failure.
JS_AddArgumentFormatter
on success, it re
turns js_true.
... otherwise it re
turns js_false.
... 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.
JS_AliasElement
if the alias is successfully created and associated with the property, js_aliaselement re
turns js_true.
...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.
JS_AliasProperty
if the alias is successfully created and associated with the property, js_aliasproperty re
turns js_true.
...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.
JS_AlreadyHasOwnProperty
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.
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.
...it re
turns the thread id of the last thread to be associated with this context.
JS_CloneFunctionObject
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.
JS_ConvertArguments
if argc is less than the number of arguments required by format, js_convertargument reports an error and re
turns false.
... on success, js_convertargument re
turns true.
... if any argument conversion fails or there are not enough arguments, it re
turns false.
JS_DecompileFunctionBody
indent unsigned if it's not js_dont_pretty_print, js_decompilefunction re
turns pretty printed source code of the function.
...if successful, js_decompilefunctionbody re
turns a string containing the source code of the function body.
... otherwise, it re
turns null.
JS_DeleteElement
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.
JS_DeleteElement2
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.
... for javascript 1.2 and earlier, if deletion fails because the property is permanent, js_deleteelement2 reports the error and re
turns false.
JS_DeleteProperty2
if the hook re
turns false, the error is propagated.
... 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.
JS_EnterCompartment
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.
JS_Enumerate
on success, js_enumerate re
turns a pointer to the first element of an array of property ids.
...on error or exception, js_enumerate re
turns null.
... the property ids in the re
turned jsidarray are subject to garbage collection.
JS_ErrorFromException
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.
JS_FlattenString
description js_flattenstring flattens a string str and re
turns a pointer to jsflatstring.
... to catch errors, an opaque jsflatstring type is re
turned.
...example: // in a fallible situation jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) re
turn false; js_assert(fstr == js_assert_string_is_flat(str)); // in an infallible situation, for the same 'str' const jschar *chars = js_getflatstringchars(fstr) js_assert(chars); see also mxr id search for js_flattenstring js_assert_string_is_flat js_forget_string_flatness bug 609440 ...
JS_GetConstructor
obj js::handle<jsobject*> the object whose constructor is to be re
turned.
...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.
JS_GetContextThread
re
turns the id of the associated thread for a context.
... 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.
JS_GetElement
find a specified numeric property of an object and re
turn its 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.
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.
JS_GetGlobalForObject
re
turns the global object for the given object.
... description js_getglobalforobject re
turns the last non-null object on the parent chain of the input object.
...for example, if the function refers to a global variable foo, then foo is a property of the object re
turned by js_getglobalforobject.
JS_GetNaNValue
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.
JS_GetPropertyAttributes
if an error occurs, the re
turn value is js_false, and the values left in *attrsp and *foundp are 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.
JS_GetSecurityCallbacks
subsumes jssubsumesop a pointe to the function which re
turns whether the first principal subsumes the second.
... js_getsecuritycallbacks re
turns the runtime's current security callbacks.
... if the callbacks are default value, it re
turns null see also mxr id search for js_getsecuritycallbacks mxr id search for js_setsecuritycallbacks jsprincipals jscspevalchecker jssubsumesop bug 957688 - removed checkobjectaccess bug 924905 - added subsumes bug 728250 - added -js_getsecuritycallbacks and js_setsecuritycallbacks, removed js_setcontextsecuritycallbacks, js_getruntimesecuritycallbacks, and js_setruntimesecuritycallbacks ...
JS_GetStringCharAt
this article covers features introduced in spidermonkey 38 re
turn a specified character from a string.
... 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.
JS_GetStringChars
description js_getstringchars obsolete since javascript 1.8.5 re
turns a pointer to the first element of an array of jschars.
... 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.
JS_HasArrayLength
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 may re
turn js_false without having reported any error or exception.
JS_HasInstance
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.
...otherwise js_hasinstance re
turns false.
JS_HasOwnProperty
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.
JS_HasProperty
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.
JS_InitClass
instead it must create a new object and re
turn it.
...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.
JS_IsConstructing
js_isconstructing re
turns js_true if the native was defined with jsfun_constructor (js_initclass automatically sets that flag when defining a constructor) and it was called as a constructor, either from javascript, using the new keyword, or from c/c++ using a jsapi function such as js_constructobject.
... otherwise it re
turns js_false.
... ordinary non-constructor jsnatives have no need to call this; it always re
turns js_false for such functions.
JS_IsConstructor
this article covers features introduced in spidermonkey 24 re
turn whether the given function is a valid constructor.
...if so, js_isconstructor re
turns true.
... otherwise it re
turns false.
JS_IsExceptionPending
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.
...*/ pending = js_isexceptionpending(cx); if (pending) { if (!js_getpendingexception(cx, &exception)) re
turn false; js_clearpendingexception(cx); } /* ...
JS_IsNativeFunction
this article covers features introduced in spidermonkey 17 re
turn whether the given function object equals the specified native function.
...if so, js_isnativefunction re
turns true.
... otherwise it re
turns false.
JS_LookupElement
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_LookupProperty
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.
JS_NewArrayObject
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.
...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.
JS_NewDouble
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.
JS_NewGlobalObject
on success, js_newglobalobject re
turns a pointer to the new object.
... otherwise it re
turns null.
... 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.
JS_NewRuntime
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.
JS_NewUCString
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.
...on success, js_newstring and js_newucstring re
turn a pointer to the new string.
... on error or exception, they re
turn null.
JS_NewStringCopyZ
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_NextProperty
iterobj js::handleobject the opaque iterator object re
turned by a previous call to js_newpropertyiterator.
... 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.
JS_PushArguments
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).
...on error or exception, js_pusharguments re
turns null.
JS_PutEscapedString
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.
JS_SetOptions
this function re
turns a uint32 value containing the previous values of the flags.
... to
turn individual options on or off, use js_setoptions with js_getoptions: //
turn on warnings for dubious practices js_setoptions(cx, js_getoptions(cx) | jsoption_extra_warnings); //
turn off those extra warnings js_setoptions(cx, js_getoptions(cx) & ~jsoption_extra_warnings); the options parameter and the re
turn value are the logical or of zero or more constants from the following table: option description jsoption_extra_warnings warn on dubious practice.
... mxr id search for jsoption_native_branch_callback jsoption_dont_report_uncaught when re
turning from the outermost api call, prevent uncaught exceptions from being converted to error reports.
JS_SuspendRequest
savedepth jsrefcount (only in js_resumerequest) the valued re
turned by the matching js_suspendrequest call.
...the re
turn value is the number of nested requests that were suspended.
...the savedepth argument must be the value re
turned by the matching js_suspendrequest call.
JS_ValueToNumber
js_valuetonumber always succeeds in this case, re
turning js_true.
... 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.
JS_ValueToString
if that method re
turns a primitive value, the value is converted to a string as described above and conversion succeeds.
... on success, js_valuetostring re
turns a pointer to a string.
... on error or exception, it re
turns null.
SpiderMonkey 1.8
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.
... a new gc parameter, jsgc_stackpool_lifespan, controls how eagerly spidermonkey re
turns unused memory back to the system.
Using the Places favicon service
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.
...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.
...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.
extIApplication
boolean quit() re
turn value boolean value indicating whether the shutdown was successful.
... boolean restart() re
turn value boolean value indicating whether the restart was successful.
... void getextensions(extiextensionscallback acallback) re
turn value none.
Setting up the Gecko SDK
specialthing.cpp #include "cspecialthing.h" ns_impl_isupports1(cspecialthing, ispecialthing) cspecialthing::cspecialthing() { /* member initializers and constructor code */ mname.assign(l"default name"); } cspecialthing::~cspecialthing() { /* destructor code */ } /* attribute astring name; */ ns_imethodimp cspecialthing::getname(nsastring & aname) { aname.assign(mname); re
turn ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & aname) { mname.assign(aname); re
turn ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::add(print32 a, print32 b, print32 *_retval) { *_retval = a + b; re
turn ns_ok; } this is generally your code.
... also, if you notice, this
turns on "xp_win" and "xp_win32" definitions, this allows xp and onward support.
...s) $< %.o: %.cpp makefile $(cxx) -c $(cppflags) $(cxxflags) $(gecko_config_include) $(gecko_defines) $(gecko_includes) $< $(module).so: $(xpidlsrcs:%.idl=%.h) $(xpidlsrcs:%.idl=%.xpt) $(cppsrcs:%.cpp=%.o) $(cxx) -o $@ -wl,-soname=$(module).so $(cppsrcs:%.cpp=%.o) $(gecko_ldflags) chmod +x $@ build: $(module).so clean: rm $(module).so « previousnext » copyright (c) 2003 by doug
turner and ian oeschger.
Components.classes
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.
... a new xpcom component instance can be created from the re
turned class object as follows: var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(components.interfaces.nsisupportsarray); which is a shortcut to var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(); obj.queryinterface(components.interfaces.nsisupportsarray); if you don't provide a specific interface t...
...o createinstance(), it will re
turn an xpconnect wrapper for the component, which only exposes the methods of the nsisupports interface (and under certain circumstances the special wrappedjsobject property).
Components.utils.import
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.
... 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.
Components.utils
createarrayin() removed in gecko 31 re
turns an array created in specified compartment.
... getglobalforobject() re
turns the global object with which a given object is associated (through its prototype chain at birth, for example).
... nondeterministicgetweakmapkeys() re
turn the keys in a weak map.
Components.utils.waiveXrays
the result of waivexrays is just like 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.
... 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.
Core XPCOM functions
ns_allocinfallibly allocates a block of memory using the xpcom memory manager.ns_freefrees a block of memory using the xpcom memory manager.ns_getcomponentmanagerthe ns_getcomponentmanager function re
turns a reference to the xpcom component manager.ns_getcomponentregistrarthe ns_getcomponentregistrar function re
turns a reference to the xpcom component registrar.ns_getmemorymanagerthe ns_getmemorymanager function re
turns a reference to the xpcom memory manager.ns_getservicemanagerthe ns_getservicemanager function re
turns a reference to the xpcom service manager.ns_initxpcom2the ns_initxpcom2 functi...
...ativelocalfilethe ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_reallocreallocates a block of memory using the xpcom memory manager.ns_shutdownxpcomthe ns_shutdownxpcom function terminates use of xpcom in the calling process.nsresultthe 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.
operator=
re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
operator+=
re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
nsACString
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).
operator=
re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
... re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining.
nsAString
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).
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.
imgILoader
channelpolicy re
turn value loadimagewithchannel() start the load and decode of an image.
... re
turn value supportimagewithmimetype() checks if a decoder for the an image with the given mime type is available.
... re
turn value true if a decoder is available, false otherwise.
mozISpellCheckingEngine
this will be either element from the array re
turned by getdictionarylist() or an empty string if no dictionary is selected.
...if the dictionary was set to "no dictionary" (that is, by specifying an empty string), the observer may select another dictionary before re
turning.
... re
turn value re
turns true if word is spelled correctly according to the dictionary attribute, and re
turns false if word is misspelled.
nsIAccessNode
re
turn value the nth nsiaccessnode child.
... re
turn value the nsidomcssprimitivevalue computed style value.
... re
turn value the computed style value.
nsIAccessibleEvent
may re
turn null if no accessible is available.
...may re
turn null if accessible for event has been shut down.
... 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.
nsIAccessibleHyperText
re
turn value an nsiaccessiblehyperlink object.
... re
turn value the index of the link if it's presented on the given character index, otherwise -1.
... re
turn value missing description exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree.
nsIAccessibleStateChangeEvent
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean isenabled(); boolean isextrastate(); attributes attribute type description state unsigned long re
turns the state of accessible (see constants declared in nsiaccessiblestates).
...re
turn value re
turns true if the state is
turned on.
...re
turn value re
turns true if the state is extra state.
nsIAccessibleTextChangeEvent
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean isinserted(); attributes attribute type description length unsigned long re
turns length of changed text.
... start long re
turns offset of changed text in accessible.
...re
turn value true if text was inserted, otherwise false.
nsIArray
if the interface in question had intended the array to be modified, it would have re
turned an nsimutablearray!
...re
turn value a new enumerator positioned at the start of the array.
... re
turn value a number >= startindex which is the position of the element in the array.
nsIAsyncInputStream
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.
...while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsiinputstream.isnonblocking() re
turn true.
...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.
nsIAsyncOutputStream
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.
...while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsioutputstream.isnonblocking() re
turn true.
...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.
nsIAuthInformation
on re
turn, this parameter should contain the domain entered by the user.
...on re
turn, this parameter should contain the password entered by the user.
...on re
turn, this parameter should contain the username entered by the user.
nsIAuthPrompt
re
turn value true for ok, false for cancel.
... re
turn value true for ok, false for cancel.
... re
turn value true for ok, false for cancel.
nsIBlocklistService
re
turn value the blocklist state of the add-on, one of the constants.
... re
turn value the blocklist state of the plugin, one of the constants.
... re
turn value true if the item is blocklisted, otherwise false.
nsICRLManager
reschedulecrlautoupdate(); boolean updatecrlfromurl(in wstring url, in wstring key); constants constant value description type_autoupdate_time_based 1 type_autoupdate_freq_based 2 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.
...re
turn value importcrl() import a crl into the certificate database.
...boolean updatecrlfromurl( in wstring url, in wstring key ); parameters url key re
turn value ...
nsICache
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 is validated, then a descriptor for that entry will be created and re
turned.
nsIContentSecurityPolicy
re
turn value true if the frame's ancestors are all permitted by policy.
...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.
...short shouldprocess( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetype, in nsisupports aextra ); parameters acontenttype acontentlocation arequestorigin acontext amimetype aextra re
turn value ...
nsIContentViewManager
methods getcontentviewsin() re
turns an array of nsicontentview objects representing all of the content views that intersect with the specified rectangle in the browser.
... 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.
nsICookiePermission
re
turn value one of the nscookieaccess values: access_default, access_allow, or access_deny.
... re
turn value true if the cookie can be set.
... re
turn value the originating uri.
nsICryptoHMAC
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.
nsIDOMFontFaceList
methods item() re
turns the nsidomfontface object at the specified index into the list.
... nsidomfontface item( in unsigned long index ); parameters index the index into the array of the font face object to re
turn.
... re
turn value an nsidomfontface object representing a single font face.
nsIDOMHTMLAudioElement
re
turns the current offset of the audio stream, specified as the number of samples that have played since the beginning of the stream.
...re
turn value an unsigned 64-bit value indicating how many audio samples have been played since the stream began playing.
... re
turn value the actual number of bytes written to the stream.
nsIDOMXPathEvaluator
re
turn value an xpath expression, as an nsidomxpathexpression object.
... re
turn value a name space resolver.
... re
turn value an xpath result.
nsIDirectoryServiceProvider
persistent true if the re
turned file will be cached by directory service.
... re
turn value the nsifile represented by the property.
... __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.
nsIEditor
re
turns true if the document has no *meaningful* content.
...re
turns true if the document is modifed and needs saving.
...re
turns true if we have a document that is not marked read-only.
nsIEditorMailSupport
re
turn value an nsisupportsarray containing the img and object tags of the current document.
...(vs plaintext) re
turn value the nsidomnode which was inserted.
... re
turn value the nsidomnode which was inserted.
nsIExternalHelperAppService
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.
...the caller should pump data into the re
turned stream listener.
... re
turn value a nsistreamlistener which the caller should pump the data into.
nsIMessageListener
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.
nsIMimeConverter
re
turn value the value of the property.
... re
turn value the value of the property.
... re
turn value the value of the property.
nsIMsgSearchCustomTerm
* * @re
turn true if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailable /** * is this custom term available?
... * * @re
turn true if available */ boolean getavailable(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailableoperators /** * list the valid operators for this term.
... * * @param scope search scope (nsmsgsearchscope) * @param length object to hold array length * * @re
turn array of operators */ void getavailableoperators(in nsmsgsearchscopevalue scope, out unsigned long length, [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 */ boolea...
nsIPrinterEnumerator
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.
nsIRadioInterfaceLayer
void dial( in domstring number ); parameters number missing description exceptions thrown missing exception missing description enumeratecalls() will continue calling callback.enumeratecallstate until the callback re
turns false.
...exceptions thrown missing exception missing description getnumberofmessagesfortext() re
turns the number of multi-part sms needed for a given text (160 characters for one sms).
... re
turn value unsigned short.
nsIScreen
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.
... getrect() re
turns a rectangle indicating the entire screen's coordinate space.
nsIScrollable
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.
... example var nsiscr = gbrowser.selectedbrowser.docshell.queryinterface(components.interfaces.nsiscrollable); var v={}; var h={}; nsiscr.getscrollbarvisibility(v,h); v.value //re
turns true if the vertical scrollbar is displayed h.value //re
turns true if the horizontal scrollbar is displayed ...
nsIServerSocket
attributes attribute type description port long re
turns the port of this server socket.
... native code only!getaddress re
turns the address to which this server socket is bound.
... re
turn value the network address to which the socket is bound.
nsISmsService
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).
... boolean hassupport(); re
turn value boolean.
nsIStructuredCloneContainer
methods deserializetovariant() deserialize the object this container holds, re
turning it wrapped as an nsivariant.
...re
turn value an nsivariant.
...re
turn value a base-64-encoded string.
nsISupports
re
turn value an integer value that is generally ignored.
... note: the interface pointer, aresult, re
turned by queryinterface must be released by a call to release() when it is no longer needed.
...re
turn value an integer value that is generally ignored.
nsISyncMessageSender
re
turns an array containing re
turn values from each listener invoked.
... 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.
... 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.
nsITextInputProcessorCallback
break; case "request-to-cancel": atip.cancelcomposition(); break; case "notify-focus": this._hasfocus = true; break; case "notify-blur": this._hasfocus = false; break; case "notify-detached": this._hasfocus = false; this._hasrightstocompose = false; break; } re
turn true; } catch (e) { re
turn false; } }, setcomposition: function simpleime_setcomposition(atext, aclauses, acaret) { if (!this._tip) { this._tip = components.classes["@mozilla.org/text-input-processor;1"].
... createinstance(components.interfaces.nsitextinputprocessor); } if (!this._tip.begininputtransaction(window, this._callback)) { re
turn false; } ...
... re
turn value if this handles the notification normally or does nothing, it should re
turn true.
nsITraceableChannel
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.
... re
turn value the previous listener for the channel.
... 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(...
nsITransaction
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.
...this method re
turns a boolean value that indicates the merge result.
... re
turn value missing description redotransaction() executes the transaction again.
nsITreeColumn
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.
...re
turn value the next nsitreecolumn in the nsitreecolumns.
...re
turn value the previous nsitreecolumn in the nsitreecolumns.
nsITreeContentView
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.
...nsidomelement getitematindex( in long index ); parameters index the row index for which to get the item re
turn value the nsidomelement item.
nsIURLFormatter
re
turn value the formatted url.
...if the preference value cannot be retrieved, a fatal error is reported and the "about:blank" url is re
turned.
... re
turn value the formatted url re
turned by formaturl(), or "about:blank".
nsIWebBrowserChrome
void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to re
turn from showasmodal().
...re
turn value true if it's a modal window.
...re
turn value note: the function error code re
turned by this corresponds to the status value specified in exitmodaleventloop.
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.
...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.
... re
turn value an nsiworker object representing the new chromeworker.
nsIXULTemplateResult
re
turn value the value for the variable or a null string if it has no value.
...this method may re
turn null for a variable, even if getbindingfor() re
turns a non-null value for the same variable.
... re
turn value the value for the variable or null if it has no value.
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..
... int i = 3; ns_ensure_true(i == 3, ns_error_failure); re
turn ns_ok; } char* mozmyclass::dostuff() { char* bar = new char[321]; ns_ensure_true(bar, nsnull); re
turn bar; } ...
NS_CStringCloneData
« xpcom api reference summary the ns_cstringclonedata function re
turns a null-terminated, heap allocated copy of the string's internal buffer.
... re
turn values the ns_cstringcutdata function re
turns a pointer to a null-terminated, heap allocated buffer on success.
... on failure it re
turns nsnull.
NS_CStringContainerInit2
re
turn values the ns_cstringcontainerinit function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
...this is significant as it allows the programmer to be certain that ns_cstringgetdata will re
turn a null-terminated character array.
NS_CStringCopy
re
turn values the ns_cstringcopy function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
... 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.
NS_StringCloneData
« xpcom api reference summary the ns_stringclonedata function re
turns a null-terminated, heap allocated copy of the string's internal buffer.
... re
turn values the ns_stringcutdata function re
turns a pointer to a null-terminated, heap allocated buffer on success.
... on failure it re
turns nsnull.
NS_StringCopy
re
turn values the ns_stringcopy function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
... 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.
XPCOM reference
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.
...this causes compile-time errors to occur when improper values are re
turned as nsresult values, thereby making it easier to catch many bugs.
Frequently Asked Questions
nscomptr<nsifoo> foo( do_queryinterface(abar, &rv) ); if ( foo ) foo->dosomefoothing(); // |foo| goes out of scope, and so |release|s its referent, here } // ...tons of stuff here, during which i don't need an |nsifoo| re
turn rv; } editors note: move this discussion to the efficiency section, and link to it from here.
... any xpcom function that re
turns an interface pointer, i.e., a `getter', must have already addrefed that pointer.
...if the getter re
turns the new pointer as its function result, no worries, general does nscomptr bloat the code?
Using nsIDirectoryService
c++ nscomptr<nsifile> dir; ns_getspecialdirectory(prop, getter_addrefs(dir)); if (!dir) re
turn ns_error_failure; javascript: var file = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); (the example is taken from the code snippets section of this site.) adding a location: there are currently two ways to add a file location to the directory serv...
...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.
...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.
Creating a Custom Column
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!
...though they sound similar you may not want to re
turn the same value from both.
...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, ...
Declaring types
every type is represented by a ctype object, which, in
turn, provides a constructor method you can call to define values of those 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.
... 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.
Working with ArrayBuffers
this example is based on the fact that the imagedata re
turned from canvasrenderingcontext2d.getimagedata is a uint8clampedarray view for an arraybuffer.
...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).
...ctypes.winapi_abi : ctypes.default_abi, ctypes.void_t, // re
turn ctypes.void_t.ptr, // *dest ctypes.void_t.ptr, // *src ctypes.size_t // count ); } catch (ex) { throw new error('i dont know where to memcpy is defined on your operating system, "' + os.constants.sys.name + '"'); lib.close() } memcpy(myimgdat.data, pixelbuffer, myimgdat.data.length); // myimgdat.data.length is imgwidth * imgheight *4 because per pixel there is...
Search - Firefox Developer Tools
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.
... 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.
Index - Firefox Developer Tools
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.
...as you step through code, the debugger will watch the expression and re
turn any results.
...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.
Intensive JavaScript - Firefox Developer Tools
mes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { 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); } } re
turn primes; } function dopointlesscomputationswithblocking() { var primes = calculateprimes(iterations, multiplier); pointlesscomputationsbutton.disabled = false; console.log(primes); } we're just running a (very inefficient) primality test 50 times, for some quite large numbers.
... it's pretty simple to split up calculateprimes(): we will just calculate primality for each number in a separate function: function dopointlesscomputationswithrequestanimationframe() { function testcandidate(index) { // finishing condition if (index == iterations) { console.log(primes); pointlesscomputationsbutton.disabled = false; re
turn; } // test this number var candidate = index * (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); } // schedule the next var testfunction = testcandidate.
...mes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { 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); } } re
turn primes; } in the worker, we have to listen for a message telling us to start, and send a "done" message back when we are done.
Waterfall - Firefox Developer Tools
mes = []; for (var i = 0; i < iterations; i++) { 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; } the waterfall's output will look something like this: the marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.
... 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.
...= 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: ...
Accelerometer - Web APIs
properties accelerometer.x read only re
turns a double containing the acceleration of the device along the device's x axis.
... accelerometer.y read only re
turns a double containing the acceleration of the device along the device's y axis.
... accelerometer.z read only re
turns a double containing the acceleration of the device along the device's z axis.
AnalyserNode.getFloatFrequencyData() - Web APIs
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.
... 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.
AudioNode - Web APIs
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.
... audionode.numberofoutputs read only re
turns the number of outputs coming out of the node.
AudioParam.value - Web APIs
setting value has the same effect as calling audioparam.setvalueattime with the time re
turned by the audiocontext's currenttime property..
...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.
...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.
AudioParamDescriptor - Web APIs
if the underlying audioworkletprocessor has a parameterdescriptors static getter, then the re
turned array of objects based on this dictionary is used internally by audioworkletnode constructor to populate its parameters property accordingly.
... // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { re
turn [{ name: 'customgain', defaultvalue: 1, minvalue: 0, maxvalue: 1, automationrate: 'a-rate' }] } 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) * (parameters['customgain'].length > 1 ?
... } }) 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.
AudioTrack.language - Web APIs
the read-only audiotrack property language re
turns a string identifying the language used in the audio track.
... 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.
... 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.
AudioTrackList.getTrackById() - Web APIs
the audiotracklist method gettrackbyid() re
turns the first audiotrack object from the track list whose id matches the specified string.
... 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.
AudioWorkletGlobalScope.registerProcessor - Web APIs
re
turn value undefined exceptions notsupportederror the name is an empty string, or a constructor under the given name is already registered.
... 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.
... // 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.
AudioWorkletNode.parameters - Web APIs
the read-only parameters property of the audioworkletnode interface re
turns the associated audioparammap — that is, a map-like collection of audioparam objects.
... // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { re
turn [{ name: 'customgain', defaultvalue: 1, minvalue: 0, maxvalue: 1, automationrate: 'a-rate' }] } 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) * (parameters['customgain'].length > 1 ?
... } }) 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.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
the read-only parameterdescriptors property of an audioworkletprocessor-derived class is a static getter, which re
turns an iterable of audioparamdescriptor-based objects.
... // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { re
turn [{ name: 'customgain', defaultvalue: 1, minvalue: 0, maxvalue: 1, automationrate: 'a-rate' }] } 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) * (parameters['customgain'].length > 1 ?
... } }) 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.
Using the Beacon API - Web APIs
if the browser successfully queues the request for delivery, the method re
turns true and re
turns false otherwise.
... window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) re
turn; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data and result console.log("sendbeacon: url = ", url, "; data = ", data, "; status = ", status); }; the following example creates a submit handler and when that event is fired, the handler calls sendbeacon().
...ent.data; // log worker's send status console.log("worker reply: sendbeacon() status = " + msg); }; } this code snippet is for the worker (worker-using.js): onmessage = function(event) { var msg = event.data; // split the url and data from the message var url = msg[0]; var data = msg[1]; // if the browser supports worker sendbeacon(), then send the beacon; otherwise // re
turn failure message to the global context if (self.navigator.sendbeacon) { var status = self.navigator.sendbeacon(url, data); postmessage(status ?
BeforeInstallPromptEvent - Web APIs
beforeinstallpromptevent.platforms read only re
turns an array of domstring items containing the platforms on which the event was dispatched.
... beforeinstallpromptevent.userchoice read only re
turns a promise that resolves to a domstring containing either "accepted" or "dismissed".
...this method re
turns a promise.
BeforeUnloadEvent - Web APIs
when a non-empty string is assigned to the re
turnvalue event property, a dialog box appears, asking the users for confirmation to leave the page (see example below).
...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.
... 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.
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.
... re
turns a promise that resolves with an arraybuffer that contains the blob's data in binary form.
... 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.
Blob.slice() - Web APIs
the blob interface's slice() method creates and re
turns a new blob object which contains data from a subset of the blob on which it's called.
...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.
... re
turn value a new blob object containing the specified subset of the data contained within the blob on which this method was called.
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.
... re
turns a promise that resolves with a usvstring which contains the blob's data as a text string.
...there are two key differences: blob.text() re
turns a promise, whereas filereader.readastext() is an event based api.
Bluetooth.requestDevice() - Web APIs
the bluetooth.requestdevice() method of the bluetooth interface re
turns a promise to a bluetoothdevice object with the specified options.
... if there is no chooser ui, this method re
turns the first device matching the criteria.
...}) re
turns a promise to a bluetoothdevice object.
BluetoothRemoteGATTServer - Web APIs
device; readonly attribute boolean connected; promise<bluetoothremotegattserver> connect(); void disconnect(); promise<bluetoothremotegattservice> getprimaryservice(bluetoothserviceuuid service); promise<sequence<bluetoothremotegattservice>> getprimaryservices(optional bluetoothserviceuuid service); }; properties bluetoothremotegattserver.connectedread only a boolean value that re
turns true while this script execution environment is connected to 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.
Body.text() - Web APIs
it re
turns a promise that resolves with a usvstring object (text).
... re
turn value a promise that resolves with a usvstring.
...ticle'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++) { mylinks[i].onclick = function(e) { e.preventdefault(); let linkdata = e.target.getattribute('data-page'); getdata(linkdata); } }; function getdata(pageid) { console.log(pageid); var myrequest = new request(pageid + '.txt'); fetch(myrequest).then(function(response) { re
turn response.text().then(function(text) { myarticle.innerhtml = text; }); }); } specifications specification status comment fetchthe definition of 'text()' in that specification.
BudgetService - Web APIs
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.
CSSNamespaceRule.prefix - Web APIs
the cssnamespacerule.prefix read-only property re
turns a domstring with the name of the prefix associated to this namespace.
... if there is no such prefix, re
turns null.
... syntax var prefix = cssnamespacerule.prefix re
turns a domstring containing the prefix associated to this namespace.
CSSNamespaceRule - Web APIs
it has some specific properties: cssnamespacerule.namespaceuri re
turns a domstring containing the text of the uri of the given namespace.
... cssnamespacerule.prefix re
turns a domstring with the name of the prefix associated to this namespace.
... if there is no such prefix, re
turns null.
CSSNumericValue.equals() - Web APIs
the equals() method of the cssnumericvalue interface re
turns a boolean indicating whether the passed value are strictly equal.
... to re
turn a value of true, all passed values must be of the same type and value and must be in the same order.
... re
turn value a boolean.
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.
... re
turn value a cssnumerictype object.
... 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.
CSSPositionValue - Web APIs
properties csspositionvalue.x re
turns the item's position along the web page's horizontal axis.
... csspositionvalue.y re
turns the item's position along the vertical axis.
... 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.
CSSStyleDeclaration.getPropertyPriority() - Web APIs
the cssstyledeclaration.getpropertypriority() method interface re
turns a domstring that provides all explicitly set priorities on the css property.
... re
turn value priority is a domstring that represents the priority (e.g.
...if none exists, re
turns the empty string.
CSSStyleDeclaration.getPropertyValue() - Web APIs
the cssstyledeclaration.getpropertyvalue() method interface re
turns a domstring containing the value of a specified css property.
... re
turn value value is a domstring containing the value of the property.
... if not set, re
turns the empty string.
CSSStyleRule - Web APIs
properties cssstylerule.selectortext re
turns the textual representation of the selector for this rule, e.g.
... 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.
CSSStyleSheet.insertRule() - Web APIs
see browser compatibility for details.) re
turn value the newly inserted rule's index within the stylesheet's rule-list.
... /*else*/ re
turn originalinsertrule.call( this, // the sheet to be changed selectorandrule.substring(0, openbracketpos), // the selector selectorandrule.substring(closebracketpos), // the rule arguments[3] // the insert index ); } // works by if the char code is a backslash, then isescaped // gets flipped (xor-ed by 1), and if it i...
...s not a backslash // then isescaped gets xored by itself, zeroing it isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } // else, there is no unescaped bracket re
turn originalinsertrule.call(this, selectorandrule, "", arguments[2]); }; } })(cssstylesheet.prototype); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.insertrule' in that specification.
CSSStyleSheet.ownerRule - Web APIs
the read-only cssstylesheet property ownerrule re
turns the cssimportrule corresponding to the @import at-rule which imported the stylesheet into the document.
... if the stylesheet wasn't imported into the document using @import, the re
turned value is null.
...if the stylesheet wasn't imported into the document using @import, the re
turned value is null.
CSSStyleSheet - Web APIs
cssrules read only re
turns a live cssrulelist which maintains an up-to-date list of the cssrule objects that comprise the stylesheet.
... 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.
... 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.
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.
... re
turn value a cssstylevalue object containing the first supplied value.
...the second code block shows the structure of the re
turned object as it would be rendered in a developer tools console.
CSSUnitValue.CSSUnitValue() - Web APIs
the cssunitvalue() constructor creates a new cssunitvalue object which re
turns a new cssunitvalue object which represents values that contain a single unit type.
... syntax var cssunitvalue = new cssunitvalue() parameters value re
turns a double indicating the number of units.
... unit re
turns a usvstring indicating the type of unit.
CSSUnparsedValue.entries() - Web APIs
the cssunparsedvalue.entries() method 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).
... syntax cssunparsedvalue.entries(obj) parameters obj the cssunparsedvalue whose enumerable own property [key, value] pairs are to be re
turned.
... re
turn value an array of the given cssunparsedvalue object's own enumerable property [key, value] pairs.
Cache.addAll() - Web APIs
re
turn value a promise that resolves with undefined.
... 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.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { re
turn cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); }); specifications specification status comment service workersthe definition of 'cache: addall' in that specification.
CacheStorage.has() - Web APIs
the has() method of the cachestorage interface re
turns a promise that resolves to true if a cache object matches the cachename.
... re
turn value a promise that resolves to true if the cache exists or false if not.
... 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.
CanvasRenderingContext2D.getImageData() - Web APIs
the canvasrenderingcontext2d method getimagedata() of the canvas 2d api re
turns an imagedata object representing the underlying pixel data for a specified portion of the canvas.
...if the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are transparent black in the re
turned imagedata object.
... re
turn value an imagedata object containing the image data for the rectangle of the canvas specified.
CanvasRenderingContext2D.setLineDash() - Web APIs
note: to re
turn to using solid lines, set the line dash list to an empty array.
...if the array is empty, the line dash list is cleared and line strokes re
turn to being solid.
... re
turn value undefined.
Applying styles and colors - Web APIs
getlinedash() re
turns the current line dash pattern array containing an even number of non-negative numbers.
...25 : -25; ctx.lineto(math.pow(i, 1.5) * 2, 75 + dy); } ctx.stroke(); re
turn false; } <table> <tr> <td><canvas id="canvas" width="150" height="150"></canvas></td> <td>change the <code>miterlimit</code> by entering a new value below and clicking the redraw button.<br><br> <form onsubmit="re
turn draw();"> <label>miter limit</label> <input type="number" size="3" id="miterlimit"/> <input type="submit" value="redraw"/> </form> ...
... createpattern(image, type) creates and re
turns a new canvas pattern object.
Transformations - Web APIs
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.
...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.
...in each loop, the canvas is translated, the rectangle is drawn, and the canvas is re
turned back to its original state.
Client.postMessage() - Web APIs
re
turn value undefined.
... if (!event.clientid) re
turn; // get the client.
... if (!client) re
turn; // send a message to the client.
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.
CloseEvent - Web APIs
closeevent.code read only re
turns an unsigned short containing the close code sent by the server.
... closeevent.reason read only re
turns a domstring indicating the reason the server closed the connection.
... closeevent.wasclean read only re
turns a boolean that indicates whether or not the connection was cleanly closed.
ContentIndex - Web APIs
contentindex.getall re
turns a promise that resolves with an iterable list of content index entries.
...lat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { re
turn; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.
... 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.
Content Index API - Web APIs
serviceworkerregistration.index read only re
turns a reference to the contentindex interface for indexing cached pages.
...lat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { re
turn; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.
... 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.
CustomEvent.detail - Web APIs
the detail readonly property of the customevent interface re
turns any data passed when initializing the event.
... 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.
DOMException() - Web APIs
the domexception() constructor re
turns a domexception object with a specified message and name.
... 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.
DOMImplementationList - Web APIs
re
turned by domimplementationsource.getdomimplementationlist() and domimplementationregistry.getdomimplementationlist() .
... properties domimplementationlist.length read only re
turns an integer.
... methods domimplementationlist.item() re
turns the pos item.
DOMRect - Web APIs
the type of box represented by the domrect is specified by the method or property that re
turned it.
... 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.l...
...eft 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.
DataTransfer.mozGetDataAt() - Web APIs
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.
... re
turn value nsivariant the data item requested.
... if the specified item does not exist, null is re
turned.
DataTransfer.mozSourceNode - Web APIs
for external drags or if the calling function cannot reach the node, null is re
turned.
... 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.
DataTransferItem.getAsFile() - Web APIs
if the item is a file, the datatransferitem.getasfile() method re
turns the drag data item's file object.
... if the item is not a file, this method re
turns null.
... re
turn value file if the drag data item is a file, a file object is re
turned; otherwise null is re
turned.
DataTransferItemList.add() - Web APIs
if the item is successfully added to the list, the newly-created datatransferitem object is re
turned.
... 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.
DirectoryReaderSync - Web APIs
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 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.
DisplayMediaStreamConstraints.audio - Web APIs
if a boolean is specified, a value of true indicates that an audio track should be included in the stream re
turned by getdisplaymedia(), if an appropriate audio source exists and the user agent supports audio on display media.
... if a mediatrackconstraints object is given, and an audio source is available, an audio track matching the settings given in the constraints object is included in the mediastream re
turned by getdisplaymedia().
... if no audio source is available, or the user agent doesn't support audio tracks with getdisplaymedia(), the re
turned mediastream has no audio track, but no error occurs.
DisplayMediaStreamConstraints.video - Web APIs
the displaymediastreamconstraints dictionary's video property is used to configure the video track in the stream re
turned by getdisplaymedia().
... 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.
... 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.
Document.createNodeIterator() - Web APIs
re
turns a new nodeiterator object.
...the method should re
turn one of nodefilter.filter_accept, nodefilter.filter_reject, or nodefilter.filter_skip.
... example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode(node) { re
turn node.nodename.tolowercase() === 'p' ?
Document.createTreeWalker() - Web APIs
the document.createtreewalker() creator method re
turns a newly created treewalker object.
... re
turn value a new treewalker object.
... 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.
Document.doctype - Web APIs
re
turns the document type declaration (dtd) associated with current document.
... the re
turned object implements the documenttype interface.
... 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.
Document.evaluate() - Web APIs
re
turns an xpathresult based on an xpath expression and other given parameters.
... 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.
... resulttype is an integer that corresponds to the type of result xpathresult to re
turn.
Document.getElementsByClassName() - Web APIs
the getelementsbyclassname method of document interface re
turns an array-like object of all child elements which have all of the given class name(s).
...you may also call getelementsbyclassname() on any element; it will re
turn only elements which are descendants of the specified root element with the given class name(s).
...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.
Document.getElementsByTagName() - Web APIs
the getelementsbytagname method of document interface re
turns an htmlcollection of elements with the given tag name.
...the re
turned htmlcollection is live, meaning that it updates itself automatically to stay in sync with the dom tree without having to call document.getelementsbytagname() again.
... the latest w3c specification says elements is an htmlcollection; however, this method re
turns a nodelist in webkit browsers.
Document.lastStyleSheetSet - Web APIs
the document.laststylesheetset property re
turns the last enabled style sheet set.
... syntax var laststylesheetset = document.laststylesheetset on re
turn, laststylesheetset indicates the style sheet set that was most recently set.
... if the current style sheet set has not been changed by setting document.selectedstylesheetset, the re
turned value is null.
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.
... if there isn't a preferred style sheet set defined by the author, the empty string ("") is re
turned.
Document.queryCommandEnabled() - Web APIs
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.
Document.requestStorageAccess() - Web APIs
the requeststorageaccess() method of the document interface re
turns a promise that resolves if the access to first-party storage was granted, and rejects if access was denied.
...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().
... re
turn value a promise that fulfills with undefined if the access to first-party storage was granted, and rejects if access was denied.
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.
... 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.
EXT_disjoint_timer_query.getQueryEXT() - Web APIs
the ext_disjoint_timer_query.getqueryext() method of the webgl api re
turns information about a query target.
... pname a glenum specifying which information to re
turn.
... re
turn value depends on pname: if pname is ext.current_query_ext: a webglquery object, which is the currently active query for the given target.
EXT_disjoint_timer_query - Web APIs
ext.isqueryext() re
turns true if a given object is a webglquery.
... ext.getqueryext() re
turns information about a query target.
... ext.getqueryobjectext() re
turn the state of a query object.
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.
... re
turn value a stylepropertymapreadonly interface.
... <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().
Element.currentStyle - Web APIs
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.
... * 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.
Element.getAttributeNames() - Web APIs
the getattributenames() method of the element interface re
turns the attribute names of the element as an array of strings.
... if the element has no attributes it re
turns an empty array.
...s()) { let value = element.getattribute(name); console.log(name, value); } polyfill if (element.prototype.getattributenames == undefined) { element.prototype.getattributenames = function () { var attributes = this.attributes; var length = attributes.length; var result = new array(length); for (var i = 0; i < length; i++) { result[i] = attributes[i].name; } re
turn result; }; } specifications specification status comment domthe definition of 'element.getattributenames' in that specification.
Element.getElementsByTagName() - Web APIs
the element.getelementsbytagname() method re
turns a live htmlcollection of elements with the given tag name.
...the re
turned list is live, which means it updates itself with the dom tree automatically.
... 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.
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.
... example var foo = document.getelementbyid("foo"); if (foo.hasattribute("bar")) { // do something } polyfill ;(function(prototype) { prototype.hasattribute = prototype.hasattribute || function(name) { re
turn !!(this.attributes[name] && this.attributes[name].specified); } })(element.prototype); notes 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 namespace-aware methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) get...
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.
Element.innerHTML - Web APIs
note: if a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerhtml re
turns these characters as the html entities "&", "<" and ">" respectively.
...the resulting string is re
turned.
... 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.
Element: mousewheel event - Web APIs
wheeldelta, wheeldeltax and wheeldeltay value the wheeldelta attribute value is an abstract value which indicates how far the wheel
turned.
... 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.
... 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).
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.
...most other types of events are not composed, and so will re
turn false.
... the composed property re
turns true beause the click event is always able to propagate across shadow boundaries.
Event.composedPath() - Web APIs
the composedpath() method of the event interface re
turns the event’s path which is an array of the objects on which listeners will be invoked.
... re
turn value an array of eventtarget objects representing the objects on which an event listener will be invoked.
...first, the composed property re
turns true beause the click event is always able to propagate across shadow boundaries.
EventTarget.dispatchEvent() - Web APIs
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.
...all applicable event handlers will execute and re
turn before the code continues on after the call to dispatchevent().
FeaturePolicy.allowedFeatures() - Web APIs
the allowedfeatures() method of the featurepolicy interface re
turns a list of directive names of all features allowed by the feature policy.enables introspection of individual directives of the feature policy it is run on.
... as such, allowedfeatures() method re
turns a subset of directives re
turned by features().
... re
turn value an array of strings representing the feature policy directive names that are allowed by the feature policy this method is called on.
FetchEvent.preloadResponse - Web APIs
the preloadresponse read-only property of the fetchevent interface re
turns a promise that resolves to the navigation preload response if navigation preload was triggered or undefined otherwise.
... 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.
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.
... 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.
FileEntrySync - Web APIs
re
turns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
... file() re
turns a file that represents the current state of the file that this fileentry represents.
... re
turns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
FileList - Web APIs
an object of this type is re
turned by the files property of the html <input> element; this lets you access the list of files selected with the <input type="file"> element.
... methods item() re
turns a file object representing the file at the specified index in the file list.
... re
turn value the file representing the requested file.
FileReader - Web APIs
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.
... constructor filereader() re
turns a newly constructed filereader.
...upon re
turn, the readystate will be done.
FileSystemDirectoryEntry - Web APIs
if you try creating a directory using a full path that includes parent directories that do not exist yet, an error is re
turned.
... 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.
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.
... 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.
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).
... 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.
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.
... 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()).
...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".
Introduction to the File and Directory Entries API - Web APIs
it was built on the file writer api, which, in
turn, was built on file api.
...the asynchronous api doesn't give you data by re
turning values; instead, you have to pass a callback function.
...in contrast, the synchronous api does not use callbacks because the api methods re
turn values.
File and Directory Entries API - Web APIs
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.
... 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.
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.
... 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.
FormData.has() - Web APIs
the has() method of the formdata interface re
turns a boolean stating whether a formdata object contains a certain key.
... 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.
GeolocationPositionError - Web APIs
geolocationpositionerror.code read only secure context re
turns an unsigned short representing the error code.
... 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position re
turned an internal error.
... geolocationpositionerror.message read only secure context re
turns a human-readable domstring describing the details of the error.
GlobalEventHandlers.onkeypress - Web APIs
html <label>enter numbers only: <input> </label> javascript function numbersonly(event) { re
turn event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.queryselector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exi...
... 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) ?
...*/ alert("yesss!!!"); location.assign("https://developer.mozilla.org/"); } re
turn true; }; })(); note: a more complete framework for capturing the typing of hidden words is available on github.
Gyroscope - Web APIs
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.
HTMLAnchorElement - Web APIs
htmlhyperlinkelementutils.origin read only re
turns a usvstring containing the origin of the url, that is its scheme, its domain and its port.
... htmlanchorelement.rellist read only re
turns a domtokenlist that reflects the rel html attribute, as a list of tokens.
... htmlhyperlinkelementutils.tostring() re
turns a usvstring containing the whole url.
HTMLAreaElement - Web APIs
htmlhyperlinkelementutils.origin read only re
turns a usvstring containing the origin of the url, that is its scheme, its domain and its port.
... 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.tostring() re
turns a usvstring containing the whole url of the script executed in the worker.
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.
... 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.
HTMLAudioElement - Web APIs
"_top"><rect x="131" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="211" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlaudioelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audio() creates and re
turns a new htmlaudioelement object, optionally starting the process of loading an audio file into it if the file url is given.
... mozcurrentsampleoffset() re
turns the number of samples form the beginning of the stream that have been written so far into the audio stream created by calling mozwriteaudio().
... mozwriteaudio() writes a batch of audio frames to the stream at the current offset, re
turning the number of bytes actually written to the stream.
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.
...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.
HTMLCanvasElement.toBlob() - Web APIs
re
turn value none.
... 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 a = document.createelement('a'); a.textcontent = 'download'; document.body.appendchild(a); a.style.display = 'block'; a.download = iconname + '.ico'; a.href = window.url.createobjecturl(b); } } canvas.toblob(blobcallback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); save toblob to disk with os.fi...
... 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.
HTMLDialogElement - Web APIs
htmldialogelement.re
turnvalue a domstring that sets or re
turns the re
turn value for the dialog.
...an optional domstring may be passed as an argument, updating the re
turnvalue of the the dialog.
...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.offsetTop - Web APIs
the htmlelement.offsettop read-only property re
turns the distance of the current element relative to the top of the offsetparent node.
... 4opera android full support 10.1safari ios full support 1samsung internet android full support 1.0legend full support full support in compliance with the specification, this property will re
turn null on webkit if the element is hidden (the style.display of this element or any ancestor is "none") or if the style.position of the element itself is set to "fixed".
... this property will re
turn null on internet explorer (9) if the style.position of the element itself is set to "fixed".
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.
... 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.
HTMLFormElement.length - Web APIs
the htmlformelement.length read-only property re
turns the number of controls in the <form> element.
... 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.
...this is the same as the number of the elements in the htmlformcontrolscollection re
turned by the elements property.
HTMLFormElement.reportValidity() - Web APIs
the htmlformelement.reportvalidity() method 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.
... syntax htmlformelement.reportvalidity() re
turn value boolean example document.forms['myform'].addeventlistener('submit', function() { document.forms['myform'].reportvalidity(); }, false); specifications specification status comment html living standardthe definition of 'htmlformelement.reportvalidity()' in that specification.
HTMLHyperlinkElementUtils - Web APIs
htmlhyperlinkelementutils.href this a stringifier property that re
turns a usvstring containing the whole url, and allows the href to be updated.
... htmlhyperlinkelementutils.origin read only this re
turns a usvstring containing the origin of the url (that is its scheme, its domain and its port).
... htmlhyperlinkelementutils.tostring() this re
turns a usvstring containing the whole url.
HTMLIFrameElement - Web APIs
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.featurepolicy read only re
turns the featurepolicy interface which provides a simple api for introspecting the feature policies applied to a specific document.
HTMLImageElement.naturalWidth - Web APIs
the htmlimageelement interface's read-only naturalwidth property re
turns the intrinsic (natural), density-corrected width of the image in css pixels.
... the corresponding naturalheight method re
turns the natural height of the image.
... 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.
HTMLMediaElement.seekToNextFrame() - Web APIs
this method re
turns immediately, re
turning a promise, whose fulfillment handler is called when the seek operation is complete.
... 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.
HTMLMediaElement.sinkId - Web APIs
the htmlmediaelement.sinkid read-only property re
turns a domstring that is the unique id of the audio device delivering output.
... if it is using the user agent default, it re
turns an empty string.
... this id should be one of the mediadeviceinfo.deviceid values re
turned from mediadevices.enumeratedevices(), id-multimedia, or id-communications.
HTMLProgressElement - Web APIs
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.
HTMLSelectElement.form - Web APIs
the htmlselectelement.form read-only property re
turns a htmlformelement representing the form that this element is associated with.
... if the element is not associated with of a <form> element, then it re
turns null.
... syntax edit aform = aselectelement.form.selectname; example html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" re
turns the type of the calling form element.
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.
... 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.
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.
... 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.
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.
... syntax htmltableelement = table.createcaption(); re
turn value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one.
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.
... 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.
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.
... 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.
HTMLTableElement.tBodies - Web APIs
the htmltableelement.tbodies read-only property re
turns a live htmlcollection of the bodies in a <table>.
... although the property is read-only, the re
turned object is live and allows the modification of its content.
... the collection re
turned includes implicit <tbody> elements.
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
the htmlvideoelement method getvideoplaybackquality() creates and re
turns a videoplaybackquality object containing metrics including how many frames have been lost.
... the data re
turned can be used to evaluate the quality of the video stream.
... syntax videopq = videoelement.getvideoplaybackquality(); re
turn value a videoplaybackquality object providing information about the video element's current playback quality.
The HTML DOM API - Web APIs
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).
...the htmlelement class, in
turn, implements node, so every element is also a node (but not the other way around).
...the corresponding types, htmlaudioelement and htmlvideoelement, are both based upon the common type htmlmediaelement, which in
turn is based upon htmlelement and so forth.
Headers.append() - Web APIs
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 exists and accepts multiple values, append() will append the new value to the end of the value set: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.get('accept-encoding'); // re
turns 'deflate, gzip' to overwrite the old value with a new one, use headers.set.
Headers.has() - Web APIs
the has() method of the headers interface re
turns a boolean stating whether a headers object contains a certain header.
... 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.
History - Web APIs
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.
... state read only re
turns an any value representing the state at the top of the history stack.
IDBFactorySync - Web APIs
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.
... re
turns idbdatabasesync an object to access the open database.
IDBIndex.keyPath - Web APIs
the keypath property of the idbindex interface re
turns the key path of the current index.
...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.
IDBIndex.multiEntry - Web APIs
the multientry read-only property of the idbindex interface re
turns a boolean value that affects how the index behaves when the result of evaluating the index's key path yields an array.
...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.
IDBIndex.objectStore - Web APIs
the objectstore property of the idbindex interface re
turns the name of the object store referenced by the current index.
...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.
IDBIndex.openCursor() - Web APIs
the opencursor() method of the idbindex interface re
turns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
...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.
IDBIndex.unique - Web APIs
the unique read-only property re
turns a boolean that states whether the index allows duplicate keys.
...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.
IDBKeyRange - Web APIs
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.
... instance methods idbkeyrange.includes() re
turns a boolean indicating whether a specified key is inside the key range.
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.
...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.
... re
turns an idbrequest object on which subsequent events related to this operation are fired.
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.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.getAllKeys() - Web APIs
the getallkeys() method of the idbobjectstore interface re
turns an idbrequest object retrieves record keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given.
... count optional specifies the number of values to re
turn if more than one is found.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
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.
... re
turn value an idbindex object for accessing the index.
...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.
IDBRequest.source - Web APIs
the source read-only property of the idbrequest interface re
turns the source of the request, such as an index or an object store.
... if no source exists (such as when calling indexeddb.open), it re
turns null.
...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 ...
IDBRequest.transaction - Web APIs
the transaction read-only property of the idbrequest interface re
turns the transaction for the request, that is, the transaction the request is being made inside.
... this property can be null for requests not made within transactions, such as for requests re
turned from idbfactory.open — in this case you're just connecting to a database, so there is no transaction to re
turn.
...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...
IDBTransaction.db - Web APIs
the db read-only property of the idbtransaction interface re
turns the database connection with which this transaction is associated.
...at the end, we re
turn the associated database connection using db.
...ore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // re
turn the database (idbdatabase) connection with which this transaction is associated transaction.db; }; specification specification status comment indexed database api 2.0the definition of 'db' in that specification.
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.
...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.
... re
turns idbversionchangerequest the request to change the version of a database.
ImageCapture.getPhotoCapabilities() - Web APIs
the getphotocapabilities() method of the imagecapture interface re
turns a promise that resolves with a photocapabilities object containing the ranges of available configuration options.
... syntax const capabilitiespromise = imagecaptureobj.getphotocapabilities() re
turn value a promise that resolves with a photocapabilities object.
... const input = document.queryselector('input[type="range"]'); 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(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; re
turn imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error =...
ImageCapture.getPhotoSettings() - Web APIs
the getphotosettings() method of the imagecapture interface re
turns a promise that resolves with a photosettings object containing the current photo configuration settings.
... syntax const settingspromise = imagecapture.getphotosettings() re
turn value a promise that resolves with a photosettings object containing the following properties: filllightmode: the flash setting of the capture device, one of "auto", "off", or "on".
... const input = document.queryselector('input[type="range"]'); 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(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; re
turn imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error =...
ImageCapture.grabFrame() - Web APIs
the grabframe() method of the imagecapture interface takes a snapshot of the live video in a mediastreamtrack and re
turns a promise that resolves with a imagebitmap containing the snapshot.
... syntax const bitmappromise = imagecapture.grabframe() re
turn value a promise that resolves to an imagebitmap object.
...it shows how to use the promise re
turned by grabframe() to copy the re
turned frame to a <canvas> element.
ImageCapture.takePhoto() - Web APIs
the takephoto() method of the imagecapture interface 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.
... re
turn value a promise that resolves with a blob.
...it shows how to use the promise re
turned by takephoto() to copy the re
turned blob to an <img> element.
Checking when a deadline is due - Web APIs
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.
...here we fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (getdate() is needed for this, as getday() re
turns the day of the week, 1-7), month (re
turns a number from 0-11, see below), and year (getfullyear() is needed; getyear() is deprecated, and re
turns a weird value that is not much use to anyone!) var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { n...
...n this particular data object, so the // notification won't be set off on it again // first open up a tranaction 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 request = objectstore.get(title); request.onsuccess = function() { // grab the data object re
turned as the result var data = request.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 requestupdate = objectstore.put(data); // when this new request succeeds, run the displaydata() function again to update the display requestupdate.onsuccess = fu...
IntersectionObserver - Web APIs
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.
... intersectionobserver.takerecords() re
turns an array of intersectionobserverentry objects for all observed targets.
... 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.
Intersection Observer API - Web APIs
otherwise, the root intersection rectangle is the intersection root's bounding client rectangle (as re
turned by calling getboundingclientrect() on it).
...we then call observe() on the re
turned observer, passing into it the desired target element.
... 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.
Keyboard - Web APIs
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.
KeyboardLayoutMap.get() - Web APIs
the get() method of the keyboardlayoutmap interface re
turns the element with the given key.
... syntax var value = keyboardlayoutmap.get(key) parameters key the key of the item to re
turn from the map.
... re
turn value the value of the specified key.
KeyframeEffect.getKeyframes() - Web APIs
the getkeyframes() method of a keyframeeffect re
turns an array of the computed keyframes that make up this animation along with their computed offsets.
... re
turn value re
turns a sequence of objects with the following format: property value pairs as many property value pairs as are contained in each keyframe of the animation.
... 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.
KeyframeEffect - Web APIs
constructor keyframeeffect() re
turns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance.
... 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.
LargestContentfulPaint - Web APIs
largestcontentfulpaint.size the intrinsic size of the element re
turned as the area (width * height).
...this property re
turns an empty string when there is no id.
... methods largestcontentfulpaint.tojson() re
turns the above properties as json.
LayoutShiftAttribution - Web APIs
properties layoutshiftattribution.node re
turns the element that has shifted (null if it has been removed).
... layoutshiftattribution.previousrect re
turns a domrect representing the position of the element before the shift.
... layoutshiftattribution.currentrect re
turns a domrect representing the position of the element after the shift.
LinearAccelerationSensor - Web APIs
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.
Location - Web APIs
location.href is a stringifier that re
turns a usvstring containing the entire url.
... location.origin read only re
turns a usvstring containing the canonical form of the origin of the specific location.
... location.tostring() re
turns a usvstring containing the whole url.
Lock - Web APIs
properties lock.mode read only re
turns the access mode passed to lockmanager.request() when the lock was requested.
... lock.name read only re
turns the name passed to lockmanager.request() when the lock was requested.
...lockmanager is the object re
turned by navigator.locks.
MSGraphicsTrust - Web APIs
the msgraphicstrust() constructor re
turns an object that provides properties for info on protected video playback.
... 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.
Magnetometer - Web APIs
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.
MediaDevices.enumerateDevices() - Web APIs
the re
turned promise is resolved with a mediadeviceinfo array describing the devices.
... syntax var enumeratorpromise = navigator.mediadevices.enumeratedevices(); re
turn value a promise that receives an array of mediadeviceinfo objects when the promise is fulfilled.
... if (!navigator.mediadevices || !navigator.mediadevices.enumeratedevices) { console.log("enumeratedevices() not supported."); re
turn; } // list cameras and microphones.
MediaDevices.ondevicechange - Web APIs
> (" + direction + ")"; if (type === "audio") { audiolist.appendchild(elem); } else if (type === "video") { videolist.appendchild(elem); } }); }); } updatedevicelist() consists entirely of a call to the function enumeratedevices() on the mediadevices object referenced in the navigator.mediadevices property, as well as the code that's run when the promise re
turned by enumeratedevices() is fulfilled.
...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.
...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.
MediaDevices - Web APIs
getsupportedconstraints() re
turns an object conforming to mediatracksupportedconstraints indicating which constrainable properties are supported on the mediastreamtrack interface.
...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.
MediaKeyStatusMap.get() - Web APIs
the get property of the mediakeystatusmap interface re
turns the value associated with the given key, or undefined if there is none.
... syntax var value = mediakeystatusmap.get(key); parameters key the key whose value you want re
turned.
... re
turns the value associated with the given key, or undefined.
MediaKeySystemAccess - Web APIs
properties mediakeysystemaccess.keysystem read only re
turns a domstring identifying the key system being used.
... methods mediakeysystemaccess.createmediakeys() re
turns a promise that resolves to a new mediakeys object.
... mediakeysystemaccess.getconfiguration() re
turns a mediakeysystemconfiguration object with the supported combination of configuration options.
MediaKeySystemConfiguration - Web APIs
properties mediakeysystemconfiguration.initdatatypes read only re
turns a list of supported initialization data type names.
... mediakeysystemconfiguration.audiocapabilities read only re
turns a list of supported audio type and capability pairs.
... mediakeysystemconfiguration.videocapabilities read only re
turns a list of supported video type and capability pairs.
MediaList - Web APIs
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.
... 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.
MediaRecorder.mimeType - Web APIs
the mimetype read-only property re
turns the mime media type that was specified when creating the mediarecorder object, or, if none was specified, which was chosen by the browser.
... var constraints = { audio: true, video: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var options = { audiobitspersecond: 128000, videobitspersecond: 2500000, mimetype: 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; m.mimetype; // would re
turn 'video/mp4' ...
... 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".
MediaRecorder.onerror - Web APIs
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.
... security " + "restrictions."); break; default: shownotification("a problem occurred while trying " + "to record the video."); break; } }; /* this would be a good place to create a worker to handle writing the buffers to disk periodically */ recorder.start(100); /* 100ms time slices per buffer */ re
turn recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecorder.onerror' in that specification.
MediaSource.isTypeSupported() - Web APIs
the mediasource.istypesupported() static method re
turns a boolean value which is true if the given mime type is likely to be supported by the current user agent.
...if the re
turned value is false, then the user agent is certain that it cannot access media of the specified format.
... re
turn value a boolean which is true if the browser feels that it can probably play media of the specified type.
MediaSource.setLiveSeekableRange() - Web APIs
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.
...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.
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.
... re
turn value an array of mediastreamtrack objects, one for each audio track contained in the stream.
... 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.
MediaStream.getVideoTracks() - Web APIs
the getvideotracks() method of the mediastream interface re
turns a sequence of mediastreamtrack objects representing the video tracks in this stream.
... re
turn value an array of mediastreamtrack objects, one for each video track contained in the media stream.
... 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.
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().
... 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.
...unction() { navigator.mediadevices.getusermedia({ audio: true }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which uses getusermedia() to obtain an audio-only stream with no specific constraints, then attaches the resulting stream to an <audio> element once the stream is re
turned.
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().
... 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.
...unction() { navigator.mediadevices.getusermedia({ video: true }).then(stream => videoelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which uses getusermedia() to obtain a video-only stream with no specific constraints, then attaches the resulting stream to a <video> element once the stream is re
turned.
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.
... 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.
... video either a boolean (which indicates whether or not a video track is requested) or a mediatrackconstraints object providing the constraints which must be met by the video track included in the re
turned mediastream.
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.
... 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.
MediaStream Image Capture API - Web APIs
this method re
turns a promise that resolves with a mediastream object.
...this re
turns an array of mediastreamtrack objects.
...if(!capabilities.zoom) { re
turn; } track.applyconstraints({ advanced : [{ zoom: zoom.value }] }); finally, pass the mediastreamtrack object to the imagecapture() constructor.
MediaTrackConstraints.cursor - Web APIs
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().
... 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 mediastream re
turned by the call to getdisplaymedia().
... 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.
Using the Media Capabilities API - Web APIs
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.
... var promise = navigator.mediacapabilities.decodinginfo(videoconfiguration); the decodinginfo() and encodinginfo() methods both re
turn promises.
... handling the response instead of the assigning the promise to a variable, we can output the values re
turned by the promise to the console: navigator.mediacapabilities.decodinginfo(videoconfiguration).then(result => { console.log('this configuration is ' + (result.supported ?
MessageChannel - Web APIs
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.
MouseEvent.region - Web APIs
the mouseevent.region read-only property re
turns the id of the canvas hit region affected by the event.
... if no hit region is affected, null is re
turned.
... syntax var hitregion = instanceofmouseevent.region re
turn value a domstring representing the id of the hit region.
Navigation Timing API - Web APIs
interfaces performance the window.performance property re
turns a performance object.
... 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.
... 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).
Navigator.cookieEnabled - Web APIs
navigator.cookieenabled re
turns a boolean value that indicates whether cookies are enabled or not.
... 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.
Navigator.getBattery() - Web APIs
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.
... 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.
Navigator.productSub - Web APIs
the navigator.productsub read-only property re
turns the build number of the current browser.
... 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.
NavigatorID.appVersion - Web APIs
re
turns either "4.0" or a string representing version information about the browser.
... note: do not rely on this property to re
turn the correct browser version.
...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.
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.
... 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.
NavigatorLanguage.languages - Web APIs
the navigatorlanguage.languages read-only property re
turns an array of domstrings representing the user's preferred languages.
...in the re
turned array they are ordered by preference with the most preferred language first.
... the value of navigator.language is the first element of the re
turned array.
NavigatorLanguage - Web APIs
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.
NavigatorPlugins - Web APIs
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.
... navigatorplugins.javaenabled() read only re
turns a boolean flag indicating whether the host browser is java-enabled or not.
Node.compareDocumentPosition() - Web APIs
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.
... 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.
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.
...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) ?
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.
... example let foo = document.getelementbyid('foo'); if (foo.haschildnodes()) { // do something with 'foo.childnodes' } polyfill here is one possible polyfill: ;(function(prototype) { prototype.haschildnodes = prototype.haschildnodes || function() { re
turn !!this.firstchild; } })(node.prototype); there are various ways to determine whether the node has a child node: node.haschildnodes() node.firstchild != null (or just node.firstchild) node.childnodes && node.childnodes.length (or node.childnodes.length > 0) specifications specification status comment domthe definition of 'node: haschildnodes' in that specification.
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.
...if the namespaceuri re
turns the xul namespace and the localname re
turns "browser", then the node is understood to be a xul <browser/>.
Node.nodeName - Web APIs
the nodename read-only property re
turns the name of the current node as a string.
...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.
...bear in mind, however, that nodename will re
turn "#text" for text nodes while tagname will re
turn undefined.
Node.parentNode - Web APIs
the node.parentnode read-only property re
turns the parent of the specified node in the dom tree.
... 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.
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.
...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.
... syntax nodefilter = nodeiterator.filter; example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); nodefilter = nodeiterator.filter; specifications specification status comment domthe definition of 'nodeiterator.filter' in that specification.
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.
... 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.
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.
...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...
...e, 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.
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.
...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...
...rable: 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.
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.
... re
turns a domstring object.
NotificationEvent.notification - Web APIs
the notification read-only property of the notificationevent interface re
turns the instance of the notification that was clicked to fire the event.
... re
turns a notification object.
...ole.log('notification data:', event.notification.data); 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('/'); })); }); specifications specification status comment notifications apithe definition of 'notification' in that specification.
Using the Notifications API - Web APIs
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.
OffscreenCanvas.getContext() - Web APIs
the offscreencanvas.getcontext() method re
turns a drawing context for an offscreen canvas, or null if the context identifier is not supported.
... 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.
OffscreenCanvas - Web APIs
methods offscreencanvas.getcontext() re
turns a rendering context for the offscreen canvas.
...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.
... // 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.
OverconstrainedError - Web APIs
properties overconstrainederror.constraint read only re
turns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied.
... overconstrainederror.message read only re
turns the text supplied in the constructor.
... overconstrainederror.name read only will always re
turn overconstrainederror.
ParentNode.append() - Web APIs
parentnode.append() has no re
turn value, whereas node.appendchild() re
turns the appended node object.
... syntax // [throws, unscopable] parentnode.append(...nodesordomstrings) // re
turns undefined parameters nodes a set of node or domstring objects to insert.
...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.
... syntax var count = node.childelementcount; count the re
turn value, which is an unsigned long (simply an integer) type.
... ;(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.
ParentNode.children - Web APIs
the parentnode property children is a read-only property that re
turns a live htmlcollection which contains all of the child elements of the node upon which it was called.
...// re
turns array instead of htmlcollection.
...onstructor) { 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) { children.push(node); } } re
turn children; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.children' in that specification.
ParentNode.lastElementChild - Web APIs
the parentnode.lastelementchild read-only property re
turns the object's last child element or null if there are no child elements.
...// 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) { re
turn node; } } re
turn null; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.lastelementchild' in that specification.
ParentNode.querySelector() - Web APIs
the parentnode mixin defines the queryselector() method as re
turning an element representing the first element matching the specified group of selectors which are descendants of the object on which the method was called.
... 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.
PaymentRequest: merchantvalidation event - Web APIs
request.addeventlistener("merchantvalidation", 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()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation and payment method documentation.
... the content delivered by the validation server is forwarded to the merchant server and is then re
turned from the fetch() call's fulfillment handler to the complete() method on the event.
... you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; re
turn await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
PaymentRequest: paymentmethodchange event - Web APIs
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.
...t.updatewith(detailsupdate); }, false); this begins by looking at the event's methodname property; if that indicates that the user is trying to use apple pay, we pass the methoddetails into a function 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.
PaymentRequest - Web APIs
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.
... paymentrequest.shippingoption read only secure context re
turns the identifier of the selected shipping option.
... paymentrequest.shippingtype read only secure context re
turns the type of shipping used to fulfill the transaction.
PaymentResponse.complete() - Web APIs
this method must be called after the user accepts the payment request and the promise re
turned by the paymentrequest.show() method is resolved.
... 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.
PaymentResponse.details - Web APIs
the details read-only property of the paymentresponse interface re
turns a json-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine a successful funds transfer.
... this data is re
turned by the payment app that satisfies the payment request, and must conform to the structure defined in the basiccardresponse dictionary.
... syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise re
turned from paymentrequest.show().
performance.getEntries() - Web APIs
the getentries() method re
turns a list of all performanceentry objects for the page.
... syntax general syntax: entries = window.performance.getentries(); re
turn value entries an array of performanceentry objects.
...performance.mark not supported"); re
turn; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); performance.mark("begin"); do_work(100000); performance.mark("end"); do_work(200000); performance.mark("end"); // use getentries() to iterate through the each entry let p = performance.getentries(); for (var i=0; i < p.length; i++) { console.log("entry[" + i + "]"); check_performanceentry(p[i]); } // use getentriesbytype() to get all "mark" entries p ...
PerformanceEntry.entryType - Web APIs
the entrytype property re
turns a domstring representing the type of performance metric such as, for example, "mark".
... syntax var type = entry.entrytype; re
turn value the re
turn value depends on the subtype of the performanceentry object and affects the value of the performanceentry.name property as shown by the table below.
... function run_performanceentry() { // check for feature support before continuing if (performance.mark === undefined) { console.log("performance.mark not supported"); re
turn; } // create a performance entry named "begin" via the mark() method performance.mark("begin"); // check the entrytype of all the "begin" entries var entriesnamedbegin = performance.getentriesbyname("begin"); for (var i=0; i < entriesnamedbegin.length; i++) { var typeofentry = entriesnamedbegin[i].entrytype; console.log("entry is type: " + typeofentry); } } specifica...
PerformanceEntry.name - Web APIs
the name property of the performanceentry interface re
turns a value that further specifies the value re
turned by the performanceentry.entrytype property.
... syntax var name = entry.name; re
turn value the re
turn value depends on the subtype of the performanceentry object and the value of performanceentry.entrytype, as shown by the table below.
...performance.mark not supported"); re
turn; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["n...
PerformanceEntry.toJSON() - Web APIs
the tojson() method is a serializer; it re
turns a json representation of the performance entry object.
... syntax json = perfentry.tojson(); arguments none re
turn value json a json object that is the serialization of the performanceentry object.
...performance.mark not supported"); re
turn; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype", "starttime", "duration"]; var methods = ["tojson"]; for (var i=0; i < properties.length; i++) { // check each property var suppo...
PerformanceNavigationTiming.unloadEventStart - Web APIs
the unloadeventstart read-only property re
turns a timestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document.
... if there is no previous document, this property re
turns 0.
... syntax perfentry.unloadeventstart; re
turn value a timestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document.
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.
... re
turn value a list of explicitly observed performanceentry objects that have the specified type.
...if no objects have the specified type, or no argument is provided, an empty list is re
turned.
PerformanceObserverEntryList - Web APIs
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.
PerformanceResourceTiming.decodedBodySize - Web APIs
the decodedbodysize read-only property re
turns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings.
... if the resource is retrieved from an application cache or local resources, it re
turns the size of the payload after removing any applied content-codings.
... syntax resource.decodedbodysize; re
turn value the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings.
PerformanceResourceTiming.nextHopProtocol - Web APIs
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.
... 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).
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.
... syntax resource.redirectend; re
turn value a timestamp immediately after receiving the last byte of the response of the last redirect.
PerformanceResourceTiming.redirectStart - Web APIs
the redirectstart read-only property re
turns a timestamp representing the start time of the fetch which that initiates the redirect.
... if there are http redirects when fetching the resource and if any of the redirects are not from the same origin as the current document, but the timing allow check algorithm passes for each redirected resource, this property re
turns the starting time of the fetch that initiates the redirect; otherwise, zero is re
turned.
... syntax resource.redirectstart; re
turn value a timestamp representing the start time of the fetch which initiates the redirect.
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.
... 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.
Using Performance Timeline - Web APIs
performance.mark not supported"); re
turn; } // create some performance entries via the mark() and measure() methods performance.mark("begin"); do_work(50000); performance.mark("end"); do_work(50000); performance.measure("measure1", "begin", "end"); // use getentries() to iterate all entries var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("all entry[" + i + "]"); print_perf_entry(p[i...
..." + properties[j] + " = not supported"); } } } } this interface also includes a tojson() method that re
turns the serialization of the performanceentry object.
... 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 ("performanceentry.tojson() is not supported"); re
turn; } // print the performanceentry object var json = pe.tojson(); var s = json.stringify(json); log("performanceentry.tojson = " + s); } 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 cal...
Permissions.query() - Web APIs
the permissions.query() method of the permissions interface re
turns the state of a user permission on the global scope.
...by the user, in the relevant permissions dialog), navigator.permissions.query() will re
turn true for both notifications and push.
... re
turns a promise that resolves to a permissionstatus object.
Using Pointer Events - Web APIs
n colorfortouch(touch) { var r = touch.pointerid % 16; var g = math.floor(touch.pointerid / 3) % 16; var b = math.floor(touch.pointerid / 7) % 16; r = r.tostring(16); // make it a hex digit g = g.tostring(16); // make it a hex digit b = b.tostring(16); // make it a hex digit var color = "#" + r + g + b; log("color for touch with identifier " + touch.pointerid + " = " + color); re
turn color; } the result from this function is a string that can be used when calling <canvas> functions to set drawing colors.
... 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 = 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.
PushManager.getSubscription() - Web APIs
it re
turns a promise that resolves to a pushsubscription object containing details of an existing subscription.
... re
turns a promise that resolves to a pushsubscription object or null.
... var pushbutton = document.queryselector('.js-push-button'); pushbutton.disabled = false; if (!subscription) { // we aren’t subscribed to push, so set ui // to allow the user to enable push re
turn; } // keep your server in sync with the latest subscriptionid sendsubscriptiontoserver(subscription); showcurlcommand(subscription); // set your ui to show they have subscribed for // push messages pushbutton.textcontent = 'disable push messages'; ispushenabled = true; }) .catch(function(err) { window.demo.debu...
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.
...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.
... re
turns a promise that resolves to a domstring with a value of 'prompt', 'denied', or 'granted'.
PushManager.subscribe() - Web APIs
it re
turns a promise that resolves to a pushsubscription object containing details of a push subscription.
...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.
... re
turns a promise that resolves to a pushsubscription object.
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.
... re
turns an arraybuffer.
... subbtn.disabled = false; if (!subscription) { console.log('not yet subscribed to push') // we aren't subscribed to push, so set ui // to allow the user to enable push re
turn; } // set your ui to show they have subscribed for // push messages subbtn.textcontent = 'unsubscribe from push messaging'; ispushenabled = true; // initialize status, which includes setting ui elements for subscribed status // and updating subscribers list via push var endpoint = subscription.endpoint; var key = subscription.getkey('p256dh'); var auth = subscription.getkey('auth'); ...
PushSubscription - Web APIs
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.
RTCDtlsTransport - Web APIs
you can, in
turn, identify the rtcdtlstransport used to securely encapsulate the data channels' sctp communications by looking at the rtcsctptransport object's transport property.
...the function re
turns an object containing properties whose values indicate how many of the senders are in each state.
...) { case "new": case "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; case "failed": results.failed++; break; default: results.unknown++; break; } } }); re
turn results; } note that in this code, the new and connecting states are being treated as a single connectionpending status in the re
turned object.
RTCIceCandidateStats - Web APIs
for
turn candidates, the
turn allocation is no longer active for deleted candidates.
... relayprotocol optional a string identifying the protocol used by the endpoint for communicating with the
turn server; valid values are tcp, udp, and tls.
... 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 wo...
RTCIceServer.credentialType - Web APIs
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.
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.
... 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.
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.
... 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.
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.
... 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.
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.
... re
turn value a rtcicecandidatepair object describing the configurations of the currently-selected candidate pair's two endpoints.
... the re
turn value is null if no pair of candidates has been selected yet.
RTCPeerConnection.addIceCandidate() - Web APIs
this function receives no input parameters and doesn't re
turn a value.
... 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.
... exceptions when an error occurs while attempting to add the ice candidate, the promise re
turned by this method is rejected, re
turning one of the errors below as the name attribute in the specified domexception object passed to the rejection handler.
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.
... re
turn value an rtcconfiguration object describing the rtcpeerconnection's current configuration.
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.
... 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.
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 order of the re
turned rtcrtpreceiver instances is not defined by the specification, and may change from one call to getreceivers() to the next.
RTCPeerConnection.getSenders() - Web APIs
the rtcpeerconnection method getsenders() re
turns an array of rtcrtpsender objects, each of which represents the rtp sender responsible for transmitting one track's data.
... syntax var senders = rtcpeerconnection.getsenders(); re
turn value an array of rtcrtpsender objects, one for each track on the connection.
... the order of the re
turned rtcrtpsenders is not defined by the specification, and may change from one call to getsenders() to the next.
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.
... 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).
...when the problem resolves, the connection may re
turn to the "connected" state.
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.
... 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.
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.
... 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.
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.
... 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.
RTCPeerConnection.setConfiguration() - Web APIs
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).
... var restartconfig = { iceservers: [{ urls: "
turn:asia.my
turnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { re
turn mypeerconnection.setlocaldescription(offer); }) .then(function() { // send the offer to the oth...
...from there, we handle the process as usual, by setting the local description to the re
turned offer and then sending that offer to the other peer.
RTCPeerConnectionIceEvent() - Web APIs
"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.
... re
turn value a newly-created rtcpeerconnectioniceevent, configured as specified in the provided options.
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.
... re
turn value an rtcrtpreceiveparameters object indicating the current configuration of the receiver.
... 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.
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 re
turned statistics include those from all streams which are coming in through the rtcrtpreceiver, as well as any of their dependencies.
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.
... re
turn value an rtcrtpsendparameters object indicating the current configuration of the sender.
... 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.
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 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.
RTCRtpSender.replaceTrack() - Web APIs
re
turn value a promise which is fulfilled once the track has been successfully replaced.
... 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.
...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...
RTCRtpSender - Web APIs
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.
... static methods rtcrtpsender.getcapabilities() re
turns an rtcrtpcapabilities object describing the system's capabilities for sending a specified kind of media data.
Range.compareNode() - Web APIs
the range.comparenode() re
turns a constant indicating the position of the node.
...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.getelementsbytagname("p").item(0)); notes this method is obsolete; you should use the w3c dom range.compareboundarypoints() method.
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.
... syntax re
turnvalue = range.comparepoint(referencenode, offset) parameters referencenode the node to compare with the range.
... 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.
ReadableStream.cancel() - Web APIs
re
turn value a promise, which fulfills with the value given in the reason parameter.
...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?
...dat === -1) { buffer = buffer.slice(-buffersize); } else if (buffer.slice(matchfoundat + tomatch.length).length >= contextafter) { console.log("here's the match:") console.log(buffer.slice( math.max(0, matchfoundat - contextbefore), matchfoundat + tomatch.length + contextafter )); console.log("cancelling fetch"); reader.cancel(); re
turn; } else { console.log('found match, but need more context…'); } // keep reading re
turn reader.read().then(process); }); }).catch(err => { console.log("something went wrong.
ReadableStreamBYOBReader - Web APIs
constructor readablestreambyobreader() creates and re
turns a readablestreambyobreader object instance.
...re
turns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors.
... readablestreambyobreader.read() re
turns a promise providing access to the next chunk in the stream's internal queue.
Report.body - Web APIs
the body read-only property of the report interface re
turns the body of the report, which is a reportbody object containing the detailed report information.
... syntax let reportbody = reportinstance.body re
turns a reportbody object containing the detailed report information.
... depending on what type the report is, the object re
turned will actually be a deprecationreportbody, interventionreportbody, crashreportbody, or featurepolicyviolationreportbody.
ResizeObserver - Web APIs
constructor resizeobserver() creates and re
turns a new resizeobserver object.
... 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.
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.
... 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.
Response.error() - Web APIs
the error() method of the response interface re
turns a new response object associated with a network error.
... note: this is mainly relevant to serviceworkers; the error method is used to re
turn an error if you so wish it.
... re
turn value a response object.
SVGGradientElement - Web APIs
svggradientelement.gradientunits read only re
turns an svganimatedenumeration corresponding to the gradientunits attribute on the given element.
... 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.
getBBox() - Web APIs
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.
... 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.
SVGGraphicsElement - Web APIs
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.
SVGPathSegList - Web APIs
the re
turn value is the item inserted into the list.
... getitem(in unsigned long index) svgpathseg re
turns the specified item from the list.
... the re
turned item is the item itself and not a copy.
Screen.orientation - Web APIs
the orientation read-only property of the screen interface re
turns the current orientation of the screen.
... syntax var orientation = window.screen.orientation; re
turn value an instance of screenorientation representing the orientation of the screen.
... note that older, prefixed versions re
turned a domstring equivalent to screenorientation.type.
ScreenOrientation - Web APIs
properties screenorientation.typeread only re
turns the document's current orientation type, one of "portrait-primary", "portrait-secondary", "landscape-primary", or "landscape-secondary".
... screenorientation.angleread only re
turns the document's current orientation angle.
... methods screenorientation.lock() locks the orientation of the containing document to its default orientation and re
turns a promise.
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.
... re
turn value the specified range object.
Selection.toString() - Web APIs
the selection.tostring() method re
turns a string currently being represented by the selection object, i.e.
... syntax sel.tostring() re
turn value a string representing the selection.
... description this method re
turns the currently selected text.
Sensor - Web APIs
accelerometer ambientlightsensor gyroscope linearaccelerationsensor magnetometer orientationsensor properties sensor.activated read only re
turns a boolean indicating whether the sensor is active.
... sensor.hasreading read only re
turns a boolean indicating whether the sensor has a reading.
... sensor.timestamp read only re
turns the time stamp of the latest sensor reading.
Sensor APIs - Web APIs
for example, the accelerometer interface re
turns the acceleration of the device along all three axes at the time it is read.
... 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.
... ambientlightsensorsecure context re
turns the current light level or illuminance of the ambient light around the hosting device.
ServiceWorkerContainer.getRegistration() - Web APIs
the method re
turns a promise that resolves to a serviceworkerregistration or undefined.
...}); parameters scope optional a unique identifier for a service worker registration — the scope url of the registration object you want to re
turn.
... re
turn value a promise that resolves to a serviceworkerregistration object or undefined.
SourceBuffer - Web APIs
sourcebuffer.buffered read only re
turns the time ranges that are currently buffered in the sourcebuffer.
...re
turns a promise which is fulfilled once the buffer has been appended.
...re
turns a promise which is fulfilled once all matching segments have been removed.
SourceBufferList: indexed property getter - Web APIs
[].) syntax var mysourcebuffer = sourcebufferlist[index]; parameters index the index position of the sourcebuffer object you want to re
turn.
... re
turn value a sourcebuffer object.
... exceptions no specific exceptions are thrown, but if the supplied index is great than or equal to sourcebufferlist.length, the operation will re
turn undefined.
SpeechGrammar - Web APIs
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.
...| orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should re
turn the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should re
turn 1 - the same as the weight set in line 4.
SpeechRecognitionEvent.interpretation - Web APIs
the interpretation read-only property of the speechrecognitionevent interface re
turns the semantic meaning of what the user said.
... this might be determined, for instance, through the sisr specification of semantics in a grammar (see semantic interpretation for speech recognition (sisr) version 1.0 for specification and examples.) syntax var myinterpretation = event.interpretation; value the re
turned value can be of any type.
... if no semantic interpretation has been re
turned by the speec recognition system, null will be re
turned.
SpeechSynthesisVoice - Web APIs
properties speechsynthesisvoice.default read only a boolean indicating whether the voice is the default voice for the current app language (true), or not (false.) speechsynthesisvoice.lang read only re
turns a bcp 47 language tag indicating the language of the voice.
... speechsynthesisvoice.localservice read only a boolean indicating whether the voice is supplied by a local speech synthesizer service (true), or a remote speech synthesizer service (false.) speechsynthesisvoice.name read only re
turns a human-readable name that represents the voice.
... speechsynthesisvoice.voiceuri read only re
turns the type of uri and location of the speech synthesis service for this voice.
Storage.getItem() - Web APIs
the getitem() method of the storage interface, when passed a key name, will re
turn that key's value, or null if the key does not exist, in the given storage object.
... re
turn value a domstring containing the value of the key.
... if the key does not exist, null is re
turned.
Storage.key() - Web APIs
the key() method of the storage interface, when passed a number n, re
turns the name of the nth key in a given storage object.
... re
turn value a domstring containing the name of the key.
... if the index does not exist, null is re
turned.
Storage.length - Web APIs
the length read-only property of the storage interface re
turns the number of data items stored in a given storage object.
... syntax length = storage.length; re
turn value the number of items stored in the storage object.
... example the following function adds three data items to the local storage for the current domain, then re
turns the number of items in the storage: function populatestorage() { localstorage.setitem('bgcolor', 'yellow'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'cats.png'); re
turn localstorage.length; // should re
turn 3 } note: for a real world example, see our web storage demo.
Storage - Web APIs
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.
StorageManager.estimate() - Web APIs
this method operates asynchronously, so it re
turns a promise which resolves once the information is available.
... re
turn value a promise that resolves to an object which conforms to the storageestimate dictionary.
... the re
turned values are not exact; between compression, deduplication, and obfuscation for security reasons, they will be imprecise.
StorageManager - Web APIs
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.
StorageQuota - Web APIs
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.
Using the Storage Access API - Web APIs
this is particularly true for document.cookie access, as browsers will often re
turn an empty cookie jar when third-party cookies are blocked.
...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.
... document.hasstorageaccess().then(hasaccess => { if (!hasaccess) { re
turn document.requeststorageaccess(); } }).then(_ => { // now we have first-party storage access!
Using writable streams - Web APIs
the constructor call in our example looks like this: 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(); }); }, ...
...ablestream); the sendmessage() definition looks like so: 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.
...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.
Streams API - Web APIs
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.
... 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.
... grayscale a png: this example shows how a readablestream of a png can be
turned into grayscale.
StylePropertyMapReadOnly.get() - Web APIs
the get() method of the stylepropertymapreadonly interface re
turns a cssstylevalue object for the first value of the specified property.
... re
turn value a cssstylevalue object.
... creating a link inside a paragraph in our html, and adding a definition list which we will populate with javascript: <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a bit of css, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } we use the element's computedstylemap() to re
turn a stylepropertymapreadonly object.
SubtleCrypto.exportKey() - Web APIs
re
turn value result is a promise.
... /* 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.
... /* 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.
Text.wholeText - Web APIs
the text.wholetext read-only property re
turns the full text of all text nodes logically adjacent to the node.
... however, "); wholetext is just a property of text nodes that re
turns the string of data making up all the adjacent (i.e.
... now let’s re
turn to our original problem.
getTrackById() - Web APIs
the texttracklist method gettrackbyid() re
turns the first texttrack object from the track list whose id matches the specified string.
... 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.
TimeRanges - Web APIs
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.
Touch.force - Web APIs
the touch.force read-only property re
turns the amount of pressure the user is applying to the touch surface for a touch point.
... syntax touchitem.force; re
turn value a float that represents the amount of pressure the user is applying to the touch surface.
...a value of 0.0 is re
turned if no value is known (for example the touch device does not support this property).
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.
... 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.
...</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'.
TouchList.item() - Web APIs
the item() method re
turns the touch object at the specified index in the touchlist.
... re
turn value touchpoint the requested touch object from the touchlist.
... re
turns null if the index is not less than the length of the list.
TrackDefaultList.TrackDefault() - Web APIs
[].) syntax var mytrackdefault = trackdefaultlist[index]; parameters index the index position of the trackdefault object you want to re
turn.
... re
turns a trackdefault object.
... errors no specific errors are re
turned, but if the supplied index is great than or equal to trackdefaultlist.length, the operation will re
turn undefined.
TransformStream - Web APIs
constructor transformstream() creates and re
turns a transform stream object from the given handlers.
... const tes = { start(){this.encoder = new textencoder()}, transform(chunk, controller) { controller.enqueue(this.encoder.encode(chunk)) } } let _jstes_wm = new weakmap(); /* info holder */ class jstextencoderstream extends transformstream { constructor() { let t = {...tes} super(t) _jstes_wm.set(this, t) } get encoding() {re
turn _jstes_wm.get(this).encoder.encoding} } similarly, textdecoderstream can be written as such: const tes = { start(){ this.decoder = new textdecoder(this.encoding, this.options) }, transform(chunk, controller) { controller.enqueue(this.decoder.decode(chunk)) } } let _jstds_wm = new weakmap(); /* info holder */ class jstextdecoderstream extends transformstream { constructor(enco...
...ding = 'utf-8', {...options} = {}) { let t = {...tds, encoding, options} super(t) _jstes_wm.set(this, t) } get encoding() {re
turn _jstds_wm.get(this).decoder.encoding} get fatal() {re
turn _jstds_wm.get(this).decoder.fatal} get ignorebom() {re
turn _jstds_wm.get(this).decoder.ignorebom} } chaining multiple readablestreams together this is a useful one, where multiple streams can be conjoined.
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.
...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.
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.
...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.
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.
...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.
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.
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.
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.
...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.
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.
TypeInfo - Web APIs
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.
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().
... 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.
URL.toString() - Web APIs
the url.tostring() stringifier method re
turns a usvstring containing the whole url.
... 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.
URLSearchParams.getAll() - Web APIs
the getall() method of the urlsearchparams interface re
turns all the values associated with a given search parameter as an array.
... syntax urlsearchparams.getall(name) parameters name the name of the parameter to re
turn.
... re
turn value an array of usvstrings.
USBConfiguration - Web APIs
properties usbconfiguration.configurationvalueread only re
turns the configuration value of this configuration.
... usbconfiguration.configurationnameread only re
turns the name provided by the device to describe this configuration.
... usbconfiguration.interfacesread only re
turns an array containing instances of the usbinterface describing each interface supported by this configuration.
getTrackById - Web APIs
the videotracklist method gettrackbyid() re
turns the first videotrack object from the track list whose id matches the specified string.
... re
turn value a videotrack object indicating the first track found within the videotracklist whose id matches the specified string.
... if no match is found, this method re
turns null.
WebGL2RenderingContext.getInternalformatParameter() - Web APIs
the webgl2renderingcontext.getinternalformatparameter() method of the webgl 2 api re
turns information about implementation-dependent support for internal formats.
...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).
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.
...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.
WebGLRenderingContext.getAttribLocation() - Web APIs
the webglrenderingcontext.getattriblocation() method of the webgl api re
turns the location of an attribute variable in a given webglprogram.
... re
turn value a glint number indicating the location of the variable name if found.
... re
turns -1 otherwise.
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
the webglrenderingcontext.getframebufferattachmentparameter() method of the webgl api re
turns information about a framebuffer's attachment.
... re
turn value depends on the requested information (as specified with pname).
... pname parameter re
turn value gl.framebuffer_attachment_object_type a glenum indicating the type of the texture.
WebGLRenderingContext.scissor() - Web APIs
re
turn value none.
... //
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.
Boilerplate 1 - Web APIs
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.
...xt() { 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 get webgl context." + "your browser or device may not support webgl."; re
turn null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); re
turn gl; } the source code of this example is also available on github.
Clearing with colors - Web APIs
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.
...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).
..." + "your browser or device may not support webgl."; re
turn; } paragraph.innerhtml = "congratulations!
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)...
..." + "error log: " + linkerrlog; re
turn; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer);...
...xt() { 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 get webgl context." + "your browser or device may not support webgl."; re
turn null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); re
turn gl; } })(); the source code of this example is also available on github.
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)...
..." + "error log: " + linkerrlog; re
turn; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); document.queryselector("canvas").addeventlistener("click", function (evt) { var clickxrelativtocanvas = evt.pagex - evt.target.offsetleft; var clickxinwebglcoords = 2.0 * (clickxrelativtocanvas- gl.drawingbufferwidth/2) / gl.drawingbufferwidth; gl.buff...
...xt() { 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 get webgl context." + "your browser or device may not support webgl."; re
turn null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); re
turn gl; } })(); the source code of this example is also available on github.
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 ...
...get webgl context." + "your browser or device may not support webgl."; re
turn null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); re
turn gl; } })(); the source code of this example is also available on github.
Scissor animation - Web APIs
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.
... position = [ math.random()*(gl.drawingbufferwidth - size[0]), gl.drawingbufferheight ]; // random velocity between 1.0 and 7.0 velocity = 1.0 + 6.0*math.random(); color = getrandomcolor(); gl.clearcolor(color[0], color[1], color[2], 1.0); } } function getrandomcolor() { 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 get ...
...webgl context." + "your browser or device may not support webgl."; re
turn null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); re
turn gl; } })(); the source code of this example is also available on github.
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)...
..." + "error log: " + linkerrlog; re
turn; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0, 0.0]), gl.static_draw); gl.vertexattribpointer(0, 2, gl.float, false, 0, 0); } fun...
...xt() { 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 get webgl context." + "your browser or device may not support webgl."; re
turn null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); re
turn gl; } })(); the source code of this example is also available on github.
Animating textures in WebGL - Web APIs
these 2 events ensures // there is data in the video video.addeventlistener('playing', function() { playing = true; checkready(); }, true); video.addeventlistener('timeupdate', function() { timeupdate = true; checkready(); }, true); video.src = url; video.play(); function checkready() { if (playing && timeupdate) { copyvideo = true; } } re
turn video; } first we create a video element.
... const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, 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.
... gl.texparameteri(gl.texture_2d, gl.texture_wrap_s, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); re
turn texture; } here's what the updatetexture() function looks like; this is where the real work is done: function updatetexture(gl, texture, video) { const level = 0; const internalformat = gl.rgba; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, level, internalformat, srcformat, srctype, video); } you've seen this code before.
Using textures in WebGL - Web APIs
turn off mips and set // wrapping to clamp to edge gl.texparameteri(gl.texture_2d, gl.texture_wrap_s, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); } }; image.src = url; re
turn texture; } function ispowerof2(value) { re
turn (value & (value - 1)) == 0; ...
...without performing the above configuration, webgl requires all samples of npot textures to fail by re
turning transparent black: rgba(0,0,0,0).
... re
turn { position: positionbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; first, this code creates a webgl buffer into which we'll store the texture coordinates for each face, then we bind that buffer as the array we'll be writing into.
Using WebGL extensions - Web APIs
var available_extensions = gl.getsupportedextensions(); the webglrenderingcontext.getsupportedextensions() method re
turns an array of strings, one for each supported extension.
...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().
WebRTC Statistics API - Web APIs
that function, in
turn, uses getstats() to obtain statistics for the connection and to make use of that data.
...then(stats => { var statsoutput = ""; stats.foreach(report => { if (report.type === "inbound-rtp" && report.kind === "video") { object.keys(report).foreach(statname => { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; }); } }); document.queryselector(".stats-box").innerhtml = statsoutput; }); } when the promise re
turned by getstats() is fulfilled, the resolution handler receives as input an rtcstatsreport object containing the statistics information.
... rtcdatachannelstats rtcstats ice-server statistics about the connection to an ice server (stun or
turn.
Lighting a WebXR setting - Web APIs
sa
turn's fifth-largest moon, tethys, bathed in sunlight, coming from the lower left.
... 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.
... 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.
WebXR permissions and security - Web APIs
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.
... if the document making the request isn't trustworthy, the request is denied and false is re
turned through the promise's fulfillment routine.
... 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.
Rendering and the WebXR frame animation callback - Web APIs
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.
... 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.
...arms and legs swing as a creature walks, heads bob and
turn, hair bounces and sways, torsos expand and contract as the character breathes.
Web Animations API - Web APIs
document.getanimations() re
turns an array of animation objects currently in effect on elements in the document.
...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.
Using the Web Storage API - Web APIs
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.
... here is a function that detects whether localstorage is both supported and available: function storageavailable(type) { var storage; try { storage = window[type]; var x = '__storage_test__'; storage.setitem(x, x); storage.removeitem(x); re
turn true; } catch(e) { re
turn e instanceof domexception && ( // everything except firefox e.code === 22 || // firefox e.code === 1014 || // test name field too, because code might not be present // everything except firefox e.name === 'quotaexceedederror' || // firefox e.name ==...
...this takes the key of the data item as an argument, and re
turns the data value.
Window.innerWidth - Web APIs
the read-only window property innerwidth re
turns the interior width of the window in pixels.
... more precisely, innerwidth re
turns the width of the window's layout viewport.
... 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.innerwid...
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.
... re
turn value a new mediaquerylist object for the media query.
... 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.
Window.pkcs11 - Web APIs
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.
window.postMessage() - Web APIs
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; // ...
... if (event.origin !== "http://example.com") re
turn; // event.source is popup // event.data is "hi there yourself!
... if (event.origin !== "http://example.com:8080") re
turn; // event.source is window.opener // event.data is "hello there!" // assuming you've verified the origin of the received message (which // you must do in any case), a convenient idiom for replying to a // message is to call postmessage on event.source and provide // event.origin as the targetorigin.
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.
... re
turn value a promise that resolves to the existing windowclient.
...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('/'); })); }); specifications specification status comment service workersthe definition of 'focus()' in that specification.
WindowEventHandlers.onbeforeunload - Web APIs
the html specification states that authors should use the event.preventdefault() method instead of using event.re
turnvalue to prompt the user.
... window.addeventlistener('beforeunload', function (e) { // cancel the event e.preventdefault(); // if you prevent default behavior in mozilla firefox prompt will always be shown // chrome requires re
turnvalue to be set e.re
turnvalue = ''; }); guarantee the browser unload by removing the re
turnvalue property of the event window.addeventlistener('beforeunload', function (e) { // the absence of a re
turnvalue property on the event will guarantee the browser unload happens delete e['re
turnvalue']; }); notes when your page uses javascript to render content, the javascript may stop when leaving and then navigating back to the page.
...if you do so, javascript in the page will be triggered on the subsequent re
turn visit and update the content as desired.
WindowOrWorkerGlobalScope.btoa() - Web APIs
re
turn value an ascii string containing the base64 representation of stringtoencode.
...for example: // convert a unicode string to a string in which // each 16-bit unit occupies only one byte function tobinary(string) { const codeunits = new uint16array(string.length); for (let i = 0; i < codeunits.length; i++) { codeunits[i] = string.charcodeat(i); } re
turn string.fromcharcode(...new uint8array(codeunits.buffer)); } // a string that contains characters occupying > 1 byte const mystring = "☸☹☺☻☼☾☿"; const converted = tobinary(mystring); const encoded = btoa(converted); console.log(encoded); // ocy5jjomoyy8jj4mpyy= if you do this, of course you'll have to reverse the conversion on the decoded string: function frombin...
...ary(binary) { const bytes = new uint8array(binary.length); for (let i = 0; i < bytes.length; i++) { bytes[i] = binary.charcodeat(i); } re
turn string.fromcharcode(...new uint16array(bytes.buffer)); } const decoded = atob(encoded); const original = frombinary(decoded); console.log(original); // ☸☹☺☻☼☾☿ polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it.
WindowOrWorkerGlobalScope.fetch() - Web APIs
the fetch() method of the windoworworkerglobalscope mixin starts the process of fetching a resource from the network, re
turning a promise which is fulfilled once the response is available.
... re
turn value a promise that resolves to a response object.
...status: ${response.status}`); } re
turn response.blob(); }) .then(function(response) { let objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in the fetch with init then request example (see fetch request init live), we do the same thing except that we pass in an init object when we invoke fetch(): const myimage = document.queryselector('img'); let myheaders = new headers(); myheaders.append('content-type', ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the queuemicrotask() method, which is exposed on the window or worker interface, queues a microtask to be executed at a safe time prior to control re
turning to the browser's event loop.
... the microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is re
turned to the browser's event loop.
... re
turn value undefined.
WorkerGlobalScope.location - Web APIs
the location read-only property of the workerglobalscope interface re
turns the workerlocation associated with the worker.
...ike the following: workerlocation {hash: "", search: "", pathname: "/worker.js", port: "8000", hostname: "localhost"…} hash: "" host: "localhost:8000" hostname: "localhost" href: "http://localhost:8000/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.
WorkerLocation - Web APIs
urlutilsreadonly.href read only is a stringifier that re
turns a domstring containing the whole 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.tostring() re
turns a domstring containing the whole url of the script executed in the worker.
HTML in XMLHttpRequest - Web APIs
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...
...this test file is small and is not well-formed xml: <title>&&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(callback) { if (!window.xmlhttprequest) { window.settimeout(function() { callback(false); }, 0); re
turn; } var done = false; var xhr = new window.xmlhttprequest(); xhr.onreadystatechange = function() { if (this.readystate == 4 && !done) { done = true; callback(!!(this.responsexml && this.responsexml.title && this.responsexml.title == "&&<")); } } xhr.onabort = xhr.onerror = function() { if (!done) { done = true; callback(false); } } try { ...
...lder browsers, you can even use the xmlhttprequest.responsetext property in association with regular expressions in order to get, for example, the source code of an html element given its id: function gethtml (oxhr, stargetid) { var ropen = new regexp("<(?!\!)\\s*([^\\s>]+)[^>]*\\s+id\\=[\"\']" + stargetid + "[\"\'][^>]*>" ,"i"), ssrc = oxhr.responsetext, aexec = ropen.exec(ssrc); re
turn aexec ?
XMLHttpRequest.send() - Web APIs
if the request is asynchronous (which is the default), this method re
turns as soon as the request is sent and the result is delivered using events.
... if the request is synchronous, this method doesn't re
turn until the response has arrived.
... re
turn value undefined.
XPathResult.iterateNext() - Web APIs
the iteratenext() method of the xpathresult interface iterates over a node set result and re
turns the next node from it or null if there are no more nodes.
... syntax var node = result.iteratenext(); re
turn value the next node within the node set of the xpathresult.
... invalid_state_err if the document is mutated since the result was re
turned, an xpathexception of type invalid_state_err is thrown.
XPathResult - Web APIs
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.
... 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.
XRInputSourceArray.keys() - Web APIs
the keys() method in the xrinputsourcearray interface re
turns a javascript iterator which can then be used to iterate over the keys used to reference each item in the array of input sources.
... re
turn value a javascript iterator that can be used to walk through the keys for each entry in the list of input sources.
... the values re
turned by the iterator are the indexes of each entry in the list; that is, the numbers 0, 1, 2, and so forth through the index of the last item in the list.
XRInputSourceArray.values() - Web APIs
the xrinputsourcearray method values() re
turns a javascript iterator that can walk over the list of xrinputsource objects contained in the array, from first to last.
... re
turn value a javascript iterator that can be used to walk through the list of xrinputsource objects in the array, starting with the first entry (at index 0) and proceeding straight through the list.
... examples this example snippet walks through each input and calls the function checkinput() with each re
turned value.
XRPermissionDescriptor.optionalFeatures - Web APIs
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..
... 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.
XRReferenceSpaceType - Web APIs
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..
... 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.
XRRigidTransform() - Web APIs
the xrrigidtransform() constructor creates and re
turns a new xrrigidtransform object, representing the position and orientation of a point or object.
... 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.
... 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.
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.
... 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.
XRRigidTransform.matrix - Web APIs
the read-only xrrigidtransform property matrix re
turns the transform matrix represented by the object.
... the re
turned matrix can then be premultiplied with a column vector to rotate the vector by the 3d rotation specified by the orientation, then translate it by the position.
...this yields the final transform matrix as re
turned by matrix: [1-2(qy2+qz2)2(qxqy-qzqw)2(qxqz+qyqw)px2(qxqy+qzqw)1-2(qx2+qz2)2(qyqz-qxqw)py2(qxqz-qyqw)2(qyqz+qxqw)1-2(qx2+qy2)pz0001]\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_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} example...
XRRigidTransform - Web APIs
xrrigidtransform.matrix read only re
turns the transform matrix in the form of a 16-member float32array.
... 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.
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.
... 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.
XRSystem: requestSession() - Web APIs
the xrsystem interface's requestsession() method re
turns a promise which resolves to an xrsession object through which you can manage the requested type of 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.
XRViewerPose.views - Web APIs
the read-only xrviewerpose property views re
turns an array which contains every xrview which must be rendered in order to fully represent the scene from the viewpoint defined by the viewer pose.
...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.
...ramebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0, 0, 0, 1); gl.cleardepth(1); gl.clear(gl.color_buffer_bit, gl.depth_buffer_bit); for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* render the scene for the eye view.eye */ } } passing each view to getviewport() re
turns the webgl viewport to apply in order to cause the rendered output to be positioned correctly in the framebuffer for renderijng to the corresponding eye on the output device.
XRViewerPose - Web APIs
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.
...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.
...ramebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0, 0, 0, 1); gl.cleardepth(1); gl.clear(gl.color_buffer_bit, gl.depth_buffer_bit); for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* render the scene for the eye view.eye */ } } passing each view to getviewport() re
turns the webgl viewport to apply in order to cause the rendered output to be positioned correctly in the framebuffer for renderijng to the corresponding eye on the output device.
XRWebGLLayer() - Web APIs
the webxr device api xrwebgllayer() constructor creates and re
turns a new xrwebgllayer object, providing the linkage between the webxr device and the webgl graphics layer used to render the 3d scene.
...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.
... 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.
msCapsLockWarningOff - Web APIs
the mscapslockwarningoff read/write property
turns automatic caps lock warning on or off for validated password input fields.
...automatic caps lock warning is
turned on.
... true: automatic caps lock warning is
turned off.
msWriteProfilerMark - Web APIs
re
turn value type: hresult.
... if this method succeeds, it re
turns s_ok.
... otherwise, it re
turns an hresult error code.
ARIA Test Cases - Accessibility
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.
... - - nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - other test cases application simple application with inner document with grid and menubar expected at behavior: if at supports virtual buffers (probably all windows screen readers), this should be automatically
turned off and the user should interact via the keyboard commands built into the web app.
...it
turns out that using aria-controls is actually not the best way to determine this in all browsers.
ARIA: grid role - Accessibility
to activate the interactive component, they will use the re
turn and space keys.
...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); ...
Cognitive accessibility - Accessibility
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.
...to achieve this, the dom order should match the visual order, which in
turn should match the tabbing order.
...however, if this technique is used, there must be a mechanism to
turn it off.
OpenType font features guide - CSS: Cascading Style Sheets
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.
... 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.
...this is helpful if you have a feature like ligatures enabled by default but you would like to
turn them off, like so: .no-ligatures { font-feature-settings: "liga" 0, "dlig" 0; } more on font-feature-settings codes 'the complete css demo for opentype features' (can't vouch for the truth of the name, but it's pretty big) a list of opentype features on wikipedia using css feature detection for implementation since not all properties are evenly implemented, it's good practice to set up...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
i’ve used writing modes to
turn these on their side in the column track: .wrapper { display: grid; grid-gap: 20px; grid-template-columns: 1fr auto; font: 1em helvetica, arial, sans-serif; } .wrapper nav { writing-mode: vertical-lr; } .wrapper ul { list-style: none; margin: 0; padding: 1em; display: flex; justify-content: space-between; } .wrapper a { text-decoration: none; } <div ...
...class="wrapper"> <div class="content"> <p>
turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale.
...bunya nuts black-eyed pea prairie
turnip leek lentil
turnip greens parsnip.
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) { // used when drawing horizontal lines to prevent subpixel blur var result = cy(y); re
turn math.round(result) == result ?
backface-visibility - CSS: Cascading Style Sheets
the backface-visibility css property sets whether the back face of an element is visible when
turned towards the user.
... 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.
transform - CSS: Cascading Style Sheets
syntax /* keyword values */ transform: none; /* function values */ transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0); transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); transform: perspective(17px); transform: rotate(0.5
turn); transform: rotate3d(1, 2.0, 3.0, 10deg); transform: rotatex(10deg); transform: rotatey(10deg); transform: rotatez(10deg); transform: translate(12px, 50%); transform: translate3d(12px, 50%, 3em); transform: translatex(2em); transform: translatey(3in); transform: translatez(2px); transform: scale(2, 0.5); transform: scale3d(2.5, 1.2, 0.3); transform: scalex(2); transform: scaley(0.5); transform: ...
...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.
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.
... syntax exsl:object-type(object) parameters object the object whose type is to be re
turned.
... re
turns the object's type, which will be one of the following: string number boolean node-set rtf external specifications exslt - exsl:object-type ...
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()).
... 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().
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()).
... 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().
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.
... 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.
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.
... 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.
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.
... re
turns a node-set containing the nodes that existed in both nodeset1 and in nodeset2.
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.
... 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.
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.
... 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.
Sets (set) - EXSLT
set:difference()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.set:distinct()set:distinct() re
turns a subset of the nodes in the specified node-set, re
turning only nodes with unique string values.set:has-same-node()set:has-same-node() determines whether two node-sets have any nodes in common.set:intersection()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.set:leading()set:leading() re
turns the nodes in one node-set that come before the first node in the other node-set.set:trailing()set:trailing() re
turns the nodes in one node-set that come after the first node in the other node-set.
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.
... 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.
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.
... re
turns a node-set of token elements, each containing one token from the string.
... example str:split('book, phone, computer, chair', ', ') re
turns a node set like: <token>book</token> <token>phone</token> <token>computer</token> <token>chair</token> specifications exslt - str:split ...
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.
... re
turns a node-set of token elements, each containing one token from the string.
... example: str:tokenize('2007-09-14-03t11:40:23', '-t:') re
turns a node set like this: <token>2007</token> <token>09</token> <token>14</token> <token>11</token> <token>40</token> <token>23</token> specifications exslt - str:tokenize ...
Event reference
nomatch speechrecognitionevent web speech api the speech recognition service re
turns a final result with no significant recognition.
... 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.
... 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.
DOM onevent handlers - Developer guides
(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.
... 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.
Constraint validation - Developer guides
the checkvalidity() method re
turns a boolean indicating whether the element's value passes its constraints.
...imit, and calls the constraint api to inform the browser if there is a violation: function checkfilesize() { var fs = document.getelementbyid("fs"); var files = fs.files; // if there is (at least) one file selected if (files.length > 0) { if (files[0].size > 75 * 1024) { // check the constraint fs.setcustomvalidity("the selected file must not be larger than 75 kb"); re
turn; } } // no custom constraint violation fs.setcustomvalidity(""); } finally we hook the method with the correct event: window.onload = function () { document.getelementbyid("fs").onchange = checkfilesize; } you can see a live example of the file size constraint validation.
... <textarea> the validitystate interface describes the object re
turned by the validity property of the element types listed above.
<img>: The Image Embed element - HTML: Hypertext Markup Language
image data from a cors-enabled image re
turned from a cors request can be reused in the <canvas> element without being marked "tainted".
...specifically, the image would raster at these dimensions and naturalwidth/naturalheight on images would re
turn the values specified in this attribute.
... <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.
<input type="password"> - HTML: Hypertext Markup Language
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.
...the text must not include carriage re
turns or line feeds.
HTML documentation index - HTML: Hypertext Markup Language
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).
... 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.
... 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).
Cross-Origin Resource Sharing (CORS) - HTTP
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.
... 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.
...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.
HTTP caching - HTTP
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.
...if so, the server re
turns a 304 (not modified) header without sending the body of the requested resource, saving some bandwidth.
... 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.
Equality comparisons and sameness - JavaScript
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.
... math.atan2 math.ceil math.pow math.round in some cases,it's possible for a -0 to be introduced into an expression as a re
turn value of these methods even when no -0 exists as one of the parameters.
... math.floor math.max math.min math.sin math.sqrt math.tan it's possible to get a -0 re
turn value out of these methods in some cases where a -0 exists as one of the parameters.
Regular expression syntax cheatsheet - JavaScript
\r matches a carriage re
turn.
... string.match() won't re
turn groups if the /.../g flag is set.
... (?<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>.
Memory Management - JavaScript
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.
... 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 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.
constructor - JavaScript
if your class is a base class, the default constructor is empty: constructor() {} if your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(...args) { super(...args); } that enables code like this to work: class validationerror extends error { printcustomermessage() { re
turn `validation failed :-( (details: ${this.message})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // this is error instead of validationerror!
...for example: class validationerror extends error { constructor(message) { super(message); // call parent class constructor this.name = 'validationerror'; this.code = '42'; } printcustomermessage() { re
turn `validation failed :-( (details: ${this.message}, code: ${this.code})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // now this is validationerror!
... 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.
static - JavaScript
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'.
... 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.
... 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.
The legacy Iterator protocol - JavaScript
property value next a zero arguments function that re
turns an value.
... difference between legacy and es2015 iterator protocols the value was re
turned directly as a re
turn value of calls to next, instead of the value property of a placeholder object iteration termination was expressed by throwing a stopiteration object.
... simple example with the old protocol function makeiterator(array){ var nextindex = 0; re
turn { next: function(){ if(nextindex < array.length){ re
turn array[nextindex++]; else throw new stopiteration(); } } } var it = makeiterator(['yo', 'ya']); console.log(it.next()); // 'yo' console.log(it.next()); // 'ya' try{ console.log(it.next()); } catch(e){ if(e instanceof stopiteration){ // iteration over } } ...
Warning: expression closures are deprecated - JavaScript
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.
... var x = function() { re
turn 1; } var obj = { count: function() { re
turn 1; } }; standard syntax using arrow functions alternatively, you can use arrow functions: var x = () => 1; standard syntax using shorthand method syntax expression closures can also be found with getter and setter, like this: var obj = { get x() 1, set x(v) this.v = v }; with es2015 method definitions, this can be converted to: var obj = { get x() { re
turn 1 }, set x(v) { this.v = v } }; ...
TypeError: "x" is not a function - JavaScript
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.
... var dog = function () { this.age = 11; this.color = "black"; this.name = "ralph"; re
turn this; } dog.prototype.name = function(name) { this.name = name; re
turn this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //uncaught typeerror: mynewdog.name is not a function use a different property name instead: var dog = function () { this.age = 11; this.color = "black"; this.dogname = "ralph"; //using this.dogname instead of .name re
turn this; } dog.prototype.name = function(name) { this.dogname = name; re
turn this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //dog { age: 11, color: 'black', dogname: 'cassidy' } using brackets for multiplication in math, you can write 2 × (3 ...
... an example helpers library (helpers.js) let helpers = function () { }; helpers.groupby = function (objectarray, property) { re
turn objectarray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); re
turn acc; }, {}); } export default helpers; the correct import usage (app.js): import helpers from './helpers' ...
InternalError: too much recursion - JavaScript
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.
... 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.
... class person{ constructor(){} set name(name){ this._name = name; } get name(){ re
turn this._name; } } const tony = new person(); tony.name = "tonisha"; console.log(tony); ...
SyntaxError: function statement requires a name - JavaScript
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.
...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.
... var greeter = { german: function () { re
turn "moin"; } }; callback syntax also, check your syntax when using callbacks.
Rest parameters - JavaScript
each one of them is then multiplied by the first parameter, and the array is re
turned: function multiply(multiplier, ...theargs) { re
turn theargs.map(element => { re
turn multiplier * element }) } let arr = multiply(2, 1, 2, 3) console.log(arr) // [2, 4, 6] use with the arguments object array methods can be used on rest parameters, but not on the arguments object: function sortrestargs(...theargs) { let sortedargs = theargs.sort() re
turn sortedargs } console.l...
...og(sortrestargs(5, 3, 7, 1)) // 1, 3, 5, 7 function sortarguments() { let sortedargs = arguments.sort() re
turn sortedargs // this will never happen } console.log(sortarguments(5, 3, 7, 1)) // throws a typeerror (arguments.sort is not a function) to use array methods on the arguments object, it must be converted to a real array first.
... function sortarguments() { let args = array.from(arguments) let sortedargs = args.sort() re
turn sortedargs } console.log(sortarguments(5, 3, 7, 1)) // 1, 3, 5, 7 specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification.
Array.prototype[@@iterator]() - JavaScript
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.
... function logiterable(it) { if (!(symbol.iterator in object.getprototypeof(it) /* or "symbol.iterator in object.__proto__" or "it[symbol.iterator]" */)) { console.log(it, ' is not an iterable object...'); re
turn; } var iterator = it[symbol.iterator](); // 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 iterator) { console.log(letter); } } // array logiterable(['a', 'b', 'c']); // a // b // c // string logiterable('abc'); // a // b // c logiterable(123); // 123 " is not an iterable object..." spec...
Array.prototype.copyWithin() - JavaScript
the copywithin() method shallow copies part of an array to another location in the same array and re
turns it without modifying its length.
... re
turn value the modified array.
... re
turn o; }, configurable: true, writable: true }); } examples using copywithin [1, 2, 3, 4, 5].copywithin(-2) // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copywithin(0, 3) // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(0, 3, 4) // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(-2, -3, -1) // [1, 2, 3, 3, 4] [].copywithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // es2015 typed arrays a...
Array.prototype.flat() - JavaScript
re
turn value a new array with the sub-array elements concatenated into it.
..., [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, 4, [5, 6]]]; // to enable deep level flatten use recursion with reduce and concat function flatdeep(arr, d = 1) { re
turn d > 0 ?
...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
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.
... re
turn value a new array with each element being the result of the callback function and flattened to a depth of 1.
...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.
Array.prototype.includes() - JavaScript
the includes() method determines whether an array includes a certain value among its entries, re
turning true or false as appropriate.
... 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).
... 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.
Array.prototype.splice() - JavaScript
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.
ArrayBuffer - JavaScript
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 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).
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.
... re
turn value the old value at the given position (typedarray[index]).
... 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
the static atomics.and() method computes a bitwise and with a given value at a given position in the array, and re
turns the old value at that position.
... re
turn value the old value at the given position (typedarray[index]).
... 5 0101 1 0001 ---- 1 0001 examples using and() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.and(ta, 0, 1); // re
turns 0, the old value atomics.load(ta, 0); // 1 specifications specification ecmascript (ecma-262)the definition of 'atomics.and' in that specification.
Atomics.compareExchange() - JavaScript
it re
turns the old value at that position whether it was equal to the expected value or not.
... re
turn value the old value at the given position (typedarray[index]).
... 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
the static atomics.exchange() method stores a given value at a given position in the array and re
turns the old value at that position.
... re
turn value the old value at the given position (typedarray[index]).
... 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
the static atomics.or() method computes a bitwise or with a given value at a given position in the array, and re
turns the old value at that position.
... re
turn value the old value at the given position (typedarray[index]).
... 5 0101 1 0001 ---- 5 0101 examples using or const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 2; atomics.or(ta, 0, 1); // re
turns 2, the old value atomics.load(ta, 0); // 3 specifications specification ecmascript (ecma-262)the definition of 'atomics.or' in that specification.
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.
... re
turn value the old value at the given position (typedarray[index]).
... 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.wait() - JavaScript
it re
turns a string which is either "ok", "not-equal", or "timed-out".
... re
turn value a string which is either "ok", "not-equal", or "timed-out".
...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.xor() - JavaScript
the static atomics.xor() method computes a bitwise xor with a given value at a given position in the array, and re
turns the old value at that position.
... re
turn value the old value at the given position (typedarray[index]).
... 5 0101 1 0001 ---- 4 0100 examples using xor const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.xor(ta, 0, 1); // re
turns 5, the old value atomics.load(ta, 0); // 4 specifications specification ecmascript (ecma-262)the definition of 'atomics.xor' 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.
DataView - JavaScript
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.
...precision may be lost'); re
turn combined; } alternatively, if you need full 64-bit range, you can create a bigint.
...nst bigint = window.bigint, bigthirtytwo = bigint(32), bigzero = bigint(0); function getuint64bigint(dataview, byteoffset, littleendian) { // split 64-bit number into two 32-bit (4-byte) parts const left = bigint(dataview.getuint32(byteoffset|0, !!littleendian)>>>0); const right = bigint(dataview.getuint32((byteoffset|0) + 4|0, !!littleendian)>>>0); // combine the two 32-bit values and re
turn re
turn littleendian ?
Date.prototype.getUTCFullYear() - JavaScript
the getutcfullyear() method re
turns the year in the specified date according to universal time.
... 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.
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.
...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.
Date.prototype.setFullYear() - JavaScript
re
turns new timestamp.
... 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.
Date.prototype.setHours() - JavaScript
the sethours() method sets the hours for a specified date according to local time, and re
turns the number of milliseconds since january 1, 1970 00:00:00 utc until the time represented by the updated date instance.
... 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.
Date.prototype.setUTCHours() - JavaScript
the setutchours() method sets the hour for a specified date according to universal time, and re
turns the number of milliseconds since january 1, 1970 00:00:00 utc until the time represented by the updated date instance.
... 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.
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.
... syntax dateobj.todatestring() re
turn value a string representing the date portion of the given date object in human readable form in english.
...calling tostring() will re
turn the date formatted in a human readable form in english.
Date.prototype.toGMTString() - JavaScript
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.
... 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.
Date.prototype.toJSON() - JavaScript
the tojson() method re
turns a string representation of the date object.
... syntax dateobj.tojson() re
turn value a string representation of the given date.
...calling tojson() re
turns a string (using toisostring()) representing the date object's value.
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.
... syntax dateobj.totimestring() re
turn value a string representing the time portion of the given date in human readable form in american english.
...calling tostring() will re
turn the date formatted in a human readable form in american english.
Date.prototype.valueOf() - JavaScript
the valueof() method re
turns the primitive value of a date object.
... syntax dateobj.valueof() re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date.
... description the valueof() method re
turns the primitive value of a date object as a number data type, the number of milliseconds since midnight 01 january, 1970 utc.
Error.prototype.toSource() - JavaScript
the tosource() method re
turns code that could eval to the same error.
... syntax e.tosource() re
turn value a string containing the source code of the error.
... examples using tosource calling the tosource method of an error instance (including nativeerrors) will re
turn a string containing the source code of the error.
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.
...'' : string(msg); if (name === '') { re
turn msg; } if (msg === '') { re
turn name; } re
turn name + ': ' + msg; }; examples using tostring() var e = new error('fatal error'); console.log(e.tostring()); // 'error: fatal error' e.name = undefined; console.log(e.tostring()); // 'error: fatal error' e.name = ''; console.log(e.tostring()); // 'fatal error' e.message = undefined; console.log(e.tostring()); // '' e.name = 'hell...
Function.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the 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.
Function - JavaScript
this can be seen with the code (function(){}).constructor === function, which re
turns true.
... function.prototype.tostring() re
turns a string representing the source code of the function.
... var x = 10; function createfunction1() { var x = 20; re
turn new function('re
turn x;'); // this |x| refers global |x| } function createfunction2() { var x = 20; function f() { re
turn x; // this |x| refers local |x| above } re
turn f; } var f1 = createfunction1(); console.log(f1()); // 10 var f2 = createfunction2(); console.log(f2()); // 20 while this code works in web browsers, f1() will produce a referenceerror...
Generator - JavaScript
the generator object is re
turned by a generator function and it conforms to both the iterable protocol and the iterator protocol.
...instead, a generator instance can be re
turned from a generator function: function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "generator { }" instance methods generator.prototype.next() re
turns a value yielded by the yield expression.
... generator.prototype.re
turn() re
turns the given value and finishes the generator.
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.
... 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.
...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.
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.
Intl.DisplayNames - JavaScript
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.
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
the intl.listformat.prototype.formattoparts() method 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.
... 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.
Intl​.List​Format​.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.
Intl.Locale.prototype.toString() - JavaScript
the intl.locale.prototype.tostring() re
turns the locale's full locale identifier string.
... syntax locale.tostring() re
turn value the locale's unicode locale identifier string.
...calling the tostring method on a locale object will re
turn the identifier string for that particular locale.
Intl.NumberFormat() constructor - JavaScript
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.
... examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is re
turned.
Intl.PluralRules - JavaScript
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.
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.
... 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.
JSON - JavaScript
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.
... json.stringify(value[, replacer[, space]]) re
turn a json string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
Map.prototype.delete() - JavaScript
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.
...mymap.has('bar'); // re
turns false.
Map.prototype.has() - JavaScript
the has() method re
turns a boolean indicating whether an element with the specified key exists or not.
... 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.acosh() - JavaScript
the math.acosh() function re
turns the hyperbolic arc-cosine of a number, that is ∀x≥1,math.acosh(x)=arcosh(x)= the unique y≥0such thatcosh(y)=x\forall x \geq 1, \mathtt{\operatorname{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.
... re
turn value the hyperbolic arc-cosine of the given number.
... 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.
Math.asinh() - JavaScript
the math.asinh() function re
turns the hyperbolic arcsine of a number, that is math.asinh(x)=arsinh(x)= the unique ysuch thatsinh(y)=x\mathtt{\operatorname{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.
... re
turn value the hyperbolic arcsine of the given number.
... 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 ?
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.
... 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.
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).
... 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.
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.
... re
turn value the hyperbolic arctangent of the given number.
... 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.
Math.cbrt() - JavaScript
the math.cbrt() function re
turns the cube root of a number, that is math.cbrt(x)=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.
... re
turn value the cube root of the given number.
... polyfill for all x≥0x \geq 0, have x3=x1/3\sqrt[3]{x} = x^{1/3} so this can be emulated by the following function: if (!math.cbrt) { math.cbrt = (function(pow) { re
turn function cbrt(x){ // ensure negative numbers remain negative: re
turn x < 0 ?
Math.cosh() - JavaScript
the math.cosh() function re
turns the hyperbolic cosine of a number, that can 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.
... re
turn value the hyperbolic cosine of the given number.
... 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.expm1() - JavaScript
the math.expm1() function re
turns ex - 1, where x is the argument, and e the base of the natural logarithms.
... re
turn value a number representing ex - 1, where e is euler's number and x is the argument.
... 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.sin() - JavaScript
the math.sin() function re
turns the sine of a number.
... 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.
Math.sinh() - JavaScript
the math.sinh() function re
turns the hyperbolic sine of a number, that can 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.
... re
turn value the hyperbolic sine of the given number.
... 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.
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.
... 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 ?
Number.isFinite() - JavaScript
re
turn value a boolean indicating whether or not the given value is a finite number.
...this means only values of the type number, that are also finite, re
turn true.
... polyfill if (number.isfinite === undefined) number.isfinite = function(value) { re
turn typeof value === 'number' && isfinite(value); } examples using isfinite number.isfinite(infinity); // false number.isfinite(nan); // false number.isfinite(-infinity); // false number.isfinite(0); // true number.isfinite(2e64); // true number.isfinite('0'); // false, would've been true with // global isfinite('0') number.isfinite(null); // false, would've been true with // global isfinite(null) specifications specification ecmascript (ecma-262)the definition of 'number.isinteger' 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.
... re
turn value a floating point number parsed from the given string.
Number.parseInt() - JavaScript
the number.parseint() method parses a string argument and re
turns an integer of the specified radix or base.
... 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.
Number.prototype.toPrecision() - JavaScript
the toprecision() method re
turns a string representing the number object to the specified precision.
... re
turn value a string representing a number object in fixed-point or exponential notation rounded to precision significant digits.
...s '5.1235' console.log(numobj.toprecision(2)) // logs '5.1' console.log(numobj.toprecision(1)) // logs '5' numobj = 0.000123 console.log(numobj.toprecision()) // logs '0.000123' console.log(numobj.toprecision(5)) // logs '0.00012300' console.log(numobj.toprecision(2)) // logs '0.00012' console.log(numobj.toprecision(1)) // logs '0.0001' // note that exponential notation might be re
turned in some circumstances console.log((1234.5).toprecision(2)) // logs '1.2e+3' specifications specification ecmascript (ecma-262)the definition of 'number.prototype.toprecision' in that specification.
Number.prototype.toSource() - JavaScript
the tosource() method re
turns 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.
Object() constructor - JavaScript
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.
Object.fromEntries() - JavaScript
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.isFrozen() - JavaScript
re
turn value a boolean indicating whether or not the given object is 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.
...in es2015, a non-object argument will be treated as if it was a frozen ordinary object, simply re
turn true.
Object.preventExtensions() - JavaScript
re
turn value the object being made non-extensible.
... examples using object.preventextensions // object.preventextensions re
turns the object // being made non-extensible.
...in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply re
turn it.
Object.seal() - JavaScript
re
turn value the object being sealed.
...object.defineproperty(obj, 'foo', { get: function() { re
turn 'g'; } }); // throws a typeerror // now any changes, other than to property values, // will fail.
...in es2015, a non-object argument will be treated as if it was a sealed ordinary object by simply re
turning it.
Object.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string representing the object.
... syntax obj.tolocalestring() re
turn value a string representing the object.
... description object's tolocalestring re
turns the result of calling tostring().
Promise.reject() - JavaScript
the promise.reject() method re
turns a promise object that is rejected with a given reason.
... 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.
handler.defineProperty() - JavaScript
re
turn value the defineproperty() method must re
turn a boolean indicating whether or not the property has been successfully defined.
... in strict mode, a false re
turn value from the defineproperty() handler will throw a typeerror exception.
... const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); re
turn true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to defineproperty() trap has one restriction—only following properties are usable (non-standard properties will be ignored): enumerable configurable writable value get set const p = new proxy({}, { defineproperty(target, prop, descriptor) { console.log(descriptor); re
turn reflect.defineproperty(target, prop, descriptor); } }); object.
handler.get() - JavaScript
re
turn value the get() method can re
turn any value.
... const p = new proxy({}, { get: function(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
re
turn value the has() method must re
turn a boolean value.
... 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
re
turn value the ownkeys() method must re
turn an enumerable object.
... const p = new proxy({}, { ownkeys: function(target) { 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.
Reflect.deleteProperty() - JavaScript
re
turn value a boolean indicating whether or not the property was successfully deleted.
...it re
turns a boolean indicating whether or not the property was successfully deleted.
... 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
it re
turns a property descriptor of the given property if it exists on the object, undefined otherwise.
... re
turn value a property descriptor object if the property exists in target object; otherwise, undefined.
... description the reflect.getownpropertydescriptor method re
turns a property descriptor of the given property if it exists in the target object, undefined otherwise.
RegExp.prototype[@@match]() - JavaScript
re
turn value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.
... for example, the following two examples re
turn same result.
... 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].
RegExp.prototype[@@split]() - JavaScript
re
turn value an array containing substrings as its elements.
...for example, the following two examples re
turn the same result.
... 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].
RegExp.prototype.source - JavaScript
the source property re
turns a string containing the source text of the regexp object, and it doesn't contain the two forward slashes on both sides and any flags.
... 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.
RegExp.prototype.toSource() - JavaScript
the tosource() method re
turns 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.
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.
...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.
... 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.
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.
... re
turn value re
turns true if an element with the specified value exists in the set object; otherwise false.
... 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.
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.
... syntax myset.values(); re
turn value a new iterator object containing the values for each element in the given set, in insertion order.
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.
... re
turn value true if the given characters are found at the end of the string; otherwise, false.
...however, you can polyfill string.prototype.endswith() with the following snippet: if (!string.prototype.endswith) { string.prototype.endswith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } re
turn this.substring(this_len - search.length, this_len) === search; }; } examples using endswith() let str = 'to be, or not to be, that is the question.' console.log(str.endswith('question.')) // true console.log(str.endswith('to be')) // false console.log(str.endswith('to be', 19)) // true specifications specification ecmascript (ecma-262)the definition of 'string.p...
String length - JavaScript
description this property re
turns the number of code units in the string.
... utf-16, the string format used by javascript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value re
turned by length to not match the actual number of characters in the string.
... unicode since `length` counts code units instead of characters, if you want to get the number of characters 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.l...
String.prototype.padStart() - JavaScript
if the value is less than str.length, then str is re
turned as-is.
... 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"); // "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.search() - JavaScript
re
turn value the index of the first match between the regular expression and the given string, or -1 if no match was found.
...(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).
...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.startsWith() - JavaScript
the startswith() method determines whether a string begins with the characters of a specified string, re
turning true or false as appropriate.
... re
turn value true if the given characters are found at the beginning of the string; otherwise, false.
...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.
String.prototype.toLocaleLowerCase() - JavaScript
the tolocalelowercase() method re
turns the calling string value converted to lower case, according to any locale-specific case mappings.
... re
turn value a new string representing the calling string converted to lower case, according to any locale-specific case mappings.
... description the tolocalelowercase() method re
turns the value of the string converted to lower case according to any locale-specific case mappings.
String.prototype.toLowerCase() - JavaScript
the tolowercase() method re
turns the calling string value converted to lower case.
... 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.
String.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing 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.
String.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified object.
... syntax str.tostring() re
turn value a string representing the calling object.
...for string objects, the tostring() method re
turns a string representation of the object and is the same as the string.prototype.valueof() method.
String.prototype.trim() - JavaScript
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.
... 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.
String.prototype.trimStart() - JavaScript
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.
...in some engines this means: string.prototype.trimleft.name === "trimstart"; polyfill //https://github.com/fabiovergani/js-polyfill_string-trimstart (function(w){ var string=w.string, proto=string.prototype; (function(o,p){ if(p in o?o[p]?false: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 usi...
String.prototype.valueOf() - JavaScript
the valueof() method re
turns the primitive value of a string object.
... syntax str.valueof() re
turn value a string representing the primitive value of a given string object.
... description the valueof() method of string re
turns the primitive value of a string object as a string data type.
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.
... re
turn value an existing symbol with the given key if found; otherwise, a new symbol is created and re
turned.
...in that case, that symbol is re
turned.
Symbol.species - JavaScript
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.
... 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.
Symbol.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the object.
... 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.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified symbol object.
... syntax symbol().tostring() re
turn value a string representing the specified symbol object.
...for symbol objects, the tostring method re
turns a string representation of the object.
Symbol.prototype.valueOf() - JavaScript
the valueof() method re
turns the primitive value of a symbol object.
... syntax symbol().valueof() re
turn value the primitive value of the specified symbol object.
... description the valueof method of symbol re
turns the primitive value of a symbol object as a symbol data type.
TypedArray.from() - JavaScript
re
turn value a new typedarray instance.
..., 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])...
...; } 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 ] generate a sequence of numbers uint8array.from({length: 5}, (v, k) => k); // uint8array [ 0, 1, 2, 3, 4 ] specifications spe...
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.
...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.
... re
turn value the first index of the element in the array; -1 if not found.
TypedArray.prototype.lastIndexOf() - JavaScript
the lastindexof() method re
turns the last index at which a given element can be found in the typed array, or -1 if it is not present.
...if the calculated index is less than 0, -1 is re
turned, i.e.
... re
turn value the last index of the element in the array; -1 if not found.
TypedArray.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string representing the elements of the typed array.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent.
... re
turn value a string representing the elements of the typed array.
TypedArray.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified array and its elements.
... syntax typedarray.tostring() re
turn value a string representing the elements of the typed array.
...for typedarray objects, the tostring method joins the array and re
turns one string containing each typed array element separated by commas.
WeakMap.prototype.delete() - JavaScript
re
turn value true if an element in the weakmap object has been removed successfully.
... examples using the delete method var wm = new weakmap(); wm.set(window, 'foo'); wm.delete(window); // re
turns true.
... wm.has(window); // re
turns false.
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.
... 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.
... 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
weaksets are ideal for this purpose: // execute a callback on everything stored inside an object function execrecursively(fn, subject, _refs = null){ if(!_refs) _refs = new weakset(); // avoid infinite recursion if(_refs.has(subject)) re
turn; fn(subject); if("object" === typeof subject){ _refs.add(subject); for(let key in subject) execrecursively(fn, subject[key], _refs); } } const foo = { foo: "foo", bar: { bar: "bar" } }; foo.bar.baz = foo; // circular reference!
... 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.
WebAssembly.CompileError - JavaScript
instance methods webassembly.compileerror.prototype.tosource() re
turns code that could eval to the same error.
... webassembly.compileerror.prototype.tostring() re
turns a string representing the specified error object..
...hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // re
turns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.Global - JavaScript
instance properties global.prototype.constructor re
turns the function that created this object's instance.
... instance methods global.prototype.valueof() old-style method that re
turns the value contained inside the global variable.
... 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).
WebAssembly.LinkError - JavaScript
instance methods webassembly.linkerror.prototype.tosource() re
turns code that could eval to the same error.
... webassembly.linkerror.prototype.tostring() re
turns a string representing the specified error object..
...rror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // re
turns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that specification.
WebAssembly.Memory - JavaScript
instance properties memory.prototype.buffer an accessor property that re
turns the buffer contained in the memory.
...its buffer property will re
turn an arraybuffer.
...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.
WebAssembly.Module.customSections() - JavaScript
the webassembly.customsections() function re
turns a copy of the contents of all custom sections in the given module with the given string name.
... re
turn value a (possibly empty) array containing arraybuffer copies of the contents of all custom sections matching sectionname.
...since there is a "name" section in the example, an arraybuffer object is re
turned.
WebAssembly.Module.exports() - JavaScript
the webassembly.module.exports() function re
turns an array containing descriptions of all the declared exports of the given module.
... re
turn value an array containing objects representing the exported functions of the given module.
...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.
WebAssembly.Module - JavaScript
static properties webassembly.module.customsections() given a module and string, re
turns a copy of the contents of all custom sections in the module with the given string name.
... webassembly.module.exports() given a module, re
turns an array containing descriptions of all the declared exports.
... webassembly.module.imports() given a module, re
turns an array containing descriptions of all the declared imports.
WebAssembly.RuntimeError - JavaScript
instance methods webassembly.runtimeerror.prototype.tosource() re
turns code that could eval to the same error.
... webassembly.runtimeerror.prototype.tostring() re
turns a string representing the specified error object..
...hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // re
turns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly - JavaScript
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.validate() validates a given typed array of webassembly binary code, re
turning whether the bytes are valid webassembly code (true) or not (false).
globalThis - JavaScript
you can also use function('re
turn this')(), but environments that disable eval(), like csp in browsers, prevent use of function in this way.
... 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')().
... however, this causes csp violations in some settings, so es6-shim uses a check like this, for example: var getglobal = function () { if (typeof self !== 'undefined') { re
turn self; } if (typeof window !== 'undefined') { re
turn window; } if (typeof global !== 'undefined') { re
turn global; } throw new error('unable to locate global object'); }; var globals = getglobal(); if (typeof globals.settimeout !== 'function') { // no settimeout in this environment!
uneval() - JavaScript
re
turn value a string representing the source code of object.
... note: this will not re
turn a json representation of 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.
Decrement (--) - JavaScript
the decrement operator (--) decrements (subtracts one from) its operand and re
turns a value.
... 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.
Increment (++) - JavaScript
the increment operator (++) increments (adds one to) its operand and re
turns a value.
... 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.
Logical OR assignment (||=) - JavaScript
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.
... 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).
class expression - JavaScript
'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() {} 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.
... 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.
break - JavaScript
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.
... 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.
for await...of - JavaScript
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 con...
... async function* streamasynciterable(stream) { const reader = stream.getreader(); try { while (true) { const { done, value } = await reader.read(); if (done) { re
turn; } yield value; } } finally { reader.releaselock(); } } // fetches data from url and calculates response size using the async generator.
... responsesize += chunk.length; } console.log(`response size: ${responsesize} bytes`); // expected output: "response size: 1071472" re
turn responsesize; } getresponsesize('https://jsonplaceholder.typicode.com/photos'); iterating over sync iterables and generators for await...of loop also consumes sync iterables and generators.
throw - JavaScript
function userexception(message) { this.message = message; this.name = 'userexception'; } function getmonthname(mo) { mo = mo - 1; // adjust month number for array index (1 = jan, 12 = dec) var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; if (months[mo] !== undefined) { re
turn months[mo]; } else { throw new userexception('invalidmonthno'); } } try { // statements to try var mymonth = 15; // 15 is out of bound to raise the exception var monthname = getmonthname(mymonth); } catch (e) { monthname = 'unknown'; console.error(e.message, e.name); // pass exception object to err handler } another example of throwing an object the following exampl...
... */ 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 cou...
... */ const zipcode_invalid = -1; const zipcode_unknown_error = -2; function verifyzipcode(z) { try { z = new zipcode(z); } catch (e) { if (e instanceof zipcodeformatexception) { re
turn zipcode_invalid; } else { re
turn zipcode_unknown_error; } } re
turn z; } a = verifyzipcode(95060); // re
turns 95060 b = verifyzipcode(9560); // re
turns -1 c = verifyzipcode('a'); // re
turns -1 d = verifyzipcode('95060'); // re
turns 95060 e = verifyzipcode('95060 1234'); // re
turns 95060 1234 rethrow an exception you can use throw to rethrow an exception after you catch it.
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.
... re
turns re
turns true if and only if the expanded-name is the name of an instruction.
...if the expanded-name has a null namespace uri, the element-available function will re
turn false.
key - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the key function re
turns a node-set of nodes that have the given value for the given key.
... value the re
turned node-set will contain every node that has this value for the given key.
... re
turns a node set.
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.
... re
turns true if the context node matches the given languages.
...if the language cannot be determined (no ancestor has an xml:lang attribute), this function will re
turn false.
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.
... re
turns a string.
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.
... re
turns a string representing the qname of a node.
not - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the not function evaluates a boolean expression and re
turns the opposite value.
... re
turns true for an expression that evaluates to false; false for an expression that evaluates to true.
... notes this function should behave similarly to the boolean() function except that it re
turns the opposite value.
substring - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the substring function re
turns a part of a given string.
...if omitted, the re
turned string will contain every character from thestart position to the end ofstring.
... re
turns a string.
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.
...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.
Navigator.mozNotification - Archive of obsolete content
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.
... re
turn value a new notification object.
Content Processes - Archive of obsolete content
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.
...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.
Module structure of the SDK - Archive of obsolete content
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.
... so a if you import a module using require, you can't change the properties of the object re
turned: self = require("sdk/self"); // attempting to define a new property // will fail, or throw an exception in strict mode self.foo = 1; // attempting to modify an existing property // will fail, or throw an exception in strict mode self.data = "foo"; using modules from outside the add-on sdk you can use commonjs modules outside the add-on sdk, in any environment where you can use components.utils.import.
base64 - Archive of obsolete content
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.
...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
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.
...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.
request - Archive of obsolete content
overridemimetype string use this string to override the mime type re
turned by the server in the response's content-type header.
...it is re
turned by the get(), head(), post(), put() or delete() method of a request object.
widget - Archive of obsolete content
re
turns widgetview : a widgetview instance associated with the browser window.
...ar tabs = require("sdk/tabs"); var windows = require("sdk/windows").browserwindows; var widget = require("sdk/widget").widget({ id: "window-specific-test", label: "widget with content specific to each window", content: " ", width: 50 }); // observe tab switch or document changes in each existing tab: function updatewidgetstate(tab) { var view = widget.getview(tab.window); if (!view) re
turn; // update widget displayed text: view.content = tab.url.match(/^https/) ?
windows - Archive of obsolete content
} }); 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.
... re
turns browserwindow : properties browserwindows browserwindows provides access to all the currently open browser windows as browserwindow objects.
test/assert - Archive of obsolete content
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.
... error : function|regexp either a constructor function re
turning the type of exception expected, or a regular expression expected to match the exception's message property.
test/utils - Archive of obsolete content
waituntil(predicate, interval) waituntil re
turns a promise that resolves upon the predicate re
turning a truthy value, which is called every interval milliseconds.
... re
turns promise : waituntil re
turns a promise that becomes resolved once the predicate re
turns a truthy value.
Modifying the Page Hosted by a Tab - Archive of obsolete content
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.
... 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 " + color; }); in the add-on script, we'll send the content script a "drawborder" message using the object re
turned from attach(): var self = require("sdk/self"); var tabs = require("sdk/tabs"); var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { var worker = tabs.activetab.attach({ contentscriptfile: self.data.url("my-script.js") }); worker.port.emit("drawborder", "red"); } }); the drawb...
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); ...
...if the file types are present in the drag data, the function re
turns that dropping the data is allowed.
On page load - Archive of obsolete content
if(gbrowser) gbrowser.addeventlistener("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.
... // 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.
JavaScript timers - Archive of obsolete content
performance.now() performance.now() re
turns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond.
... date.now() date.now() re
turns the number of milliseconds elapsed since 1 january 1970 00:00:00 utc.
Windows - Archive of obsolete content
however, window.open() re
turns a window object for content, not for the browser window itself, so you should get the chrome window first.
... 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.
getAttributeNS - Archive of obsolete content
function getattributenswrapper (thisitem, ns, nsatt) { if (thisitem === null) { re
turn false; } if (thisitem.getattributens) { re
turn thisitem.getattributens(ns, nsatt); } else if (ns === null) { re
turn thisitem.getattribute(nsatt); } else if (ns === 'http://www.w3.org/xml/1998/namespace') { // this is assumed so don't try to get an xmlns for the 'xml' prefix re
turn thisitem.getattribute('xml:'+nsatt); // prefix must be 'xml' per the ...
... attrs2 = thisitem.attributes; for (var i = 0; i < attrs2.length; i++) { // search for any prefixed xmlns declaration on thisitem which match prefixes found above with desired local name if (attrs2[i].nodename.match(xmlnsprefix) && attrs2[i].nodevalue === ns ) { // e.g., 'xmlns:xlink' and 'http://www.w3.org/1999/xlink' re
turn attrs[j].nodevalue; } } thisitem = thisitem.parentnode; } } } re
turn ''; // if not found (some implementations re
turn 'null' but this is not standard) } alert(getattributenswrapper (someelement, 'http://www.w3.org/1999/xlink', 'href')); // gets xlink:href, xl:href, etc.
Enhanced Extension Installation - Archive of obsolete content
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.
... 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.
Extension Versioning, Update and Compatibility - Archive of obsolete content
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.
... 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.
Extension Etiquette - Archive of obsolete content
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.
Appendix: What you should know about open-source software licenses - Archive of obsolete content
any discussion of copyright eventually
turns to the fact that some uses are prohibited, so it’s useful to understand what uses are unrestricted.
... 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.
Appendix D: Loading Scripts - Archive of obsolete content
components.utils.import("resource://my-package/my-module.jsm"); the following function will import an arbitrary module into a singleton object, which it re
turns.
... function module(uri) { if (!/^[a-z-]+:/.exec(uri)) uri = /([^ ]+\/)[^\/]+$/.exec(components.stack.caller.filename)[1] + uri + ".jsm"; let obj = {}; components.utils.import(uri, obj); re
turn obj; } given the above code, the following code will import the module "my-module.jsm" from the current directory and define the symbols foo and bar from that module in the current scope.
Custom XUL Elements with XBL - Archive of obsolete content
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> p...
...you can also have a re
turn value using the re
turn keyword, just like on regular js code.
Intercepting Page Loads - Archive of obsolete content
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.
... } 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.
Local Storage - Archive of obsolete content
here's what we usually do: we have a function that re
turns a reference to our root directory and creates it if necessary.
... 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.
Search Extension Tutorial (Draft) - Archive of obsolete content
if (reason == app_shutdown) re
turn; // reset our changes if the values have not been changed // in the meantime.
... 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.
chargingchange - Archive of obsolete content
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.
levelchange - Archive of obsolete content
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.
Creating a Web based tone generator - Archive of obsolete content
tail = tail.subarray(written); re
turn; // ...
... var frequency = 0, currentsoundsample; var samplerate = 44100; function requestsounddata(sounddata) { if (!frequency) { re
turn; // no sound selected } var k = 2* math.pi * frequency / samplerate; for (var i=0, size=sounddata.length; i<size; i++) { sounddata[i] = math.sin(k * currentsoundsample++); } } var audiodestination = new audiodatadestination(samplerate, requestsounddata); function start() { currentsoundsample = 0; frequency = parsefloat...
No Proxy For configuration - Archive of obsolete content
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").
...all proxied urls will re
turn errors, all non-proxied connections will be attempted normally (direct connection).
Using Dehydra - Archive of obsolete content
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.
... */ function isfinal(c) { if (!c.attributes) re
turn false; for each (let a in c.attributes) if (a.name == 'user' && a.value == 'final') re
turn true; re
turn false; } function process_type(t) { if (t.bases) for each (let base in t.bases) if (isfinal(base.type)) error("class " + t.name + " extends final class " + base.type.name, t.loc); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/final.js -o/dev/null -c final.cc it should print the following results and re
turn with an error code: final.cc:8: error: class subclass extends final class myclass see documentation for: process_type, error, .bases property, .attributes property ...
Code snippets - Archive of obsolete content
mainwindow.gbrowser.addtab(url); } } partially corrupt a server components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); function deletepath(path) { let resource = new resource(weave.service.storageurl + path); resource.setheader("x-confirm-delete", "1"); re
turn resource.delete(); } // delete meta/global: deletepath("meta/global"); // delete keys: deletepath("crypto/keys"); // delete server: deletepath(""); corrupt a single engine on the server let engine = "bookmarks"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); components.utils.import("resource://services-sync/util.js...
... bump meta/global's modified time components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); function getpath(path) { let r = new resource(weave.service.storageurl + path); let g = r.get(); re
turn [g, r]; }; let [g, r] = getpath("meta/global"); r.put(g); delete and restore a record components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); components.utils.import("resource://services-sync/record.js"); // for example: let id = "iasokuozpixz" let collection = "bookmarks"; let resource = new resource(weave.service.storageu...
Creating a Help Content Pack - Archive of obsolete content
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.
... nc:emptysearchtext specifies the text that is shown when a search through help re
turns no results.
generateCRMFRequest() - Archive of obsolete content
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.
importUserCertificates - Archive of obsolete content
if the import operation succeeds, an empty string will be re
turned.
... if it fails, one of the following error strings will be re
turned: error string description "error:usercancel" the user canceled the import operation "error:invalidcertificate" one of the certificate packages was incorrectly formatted "error:internalerror" the software encountered some internal error, such as out of memory "error:invalidrequestid" the request id in the response message does not match any outstanding request ...
Microsummary topics - Archive of obsolete content
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.
...to mitigate this effect, only re
turn microsummary-specific cache headers in response to microsummary-related requests.
Mozilla Crypto FAQ - Archive of obsolete content
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.
...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".
Porting NSPR to Unix Platforms - Archive of obsolete content
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>).
Space Manager High Level Design - Archive of obsolete content
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.
... 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.
Treehydra Manual - Archive of obsolete content
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.
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
the simplest demonstration of the problem is as follows: typedef struct shareddata { prlock *ml; prcondvar *cv; print32 counter; } shareddata; static void forkedthread(void *arg) { shareddata *shared = (shareddata*)arg; while (--shared->counter > 0) pr_waitcondvar(shared->cv, pr_interval_no_timeout); re
turn; } /* forkedthread */ printn main(printn argc, char **argv) { prthread *thread; shareddata shared; shared.ml = pr_newlock(); shared.cv = pr_newcondvar(shared.ml); shared.counter = 10; thread = pr_createthread( pr_user_thread, forkedthread, &shared, pr_priority_normal, pr_local_thread, pr_joinable_thread, 0); do { pr_sleep(pr_secondstointe...
...rval(1)); pr_lock(shared.ml); if (0 == shared.counter) break; pr_notifycondvar(shared.cv); pr_unlock(shared.ml); } while (pr_true); rv = pr_jointhread(thread); re
turn (pr_success == rv) ?
Using gdb on wimpy computers - Archive of obsolete content
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.
...if you have
turned off automatic shared library loading, you will have to load them when you need them.
Example Sticky Notes - Archive of obsolete content
--> <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.
exists - Archive of obsolete content
exists re
turns a value indicating whether the specified file or directory exists.
... re
turns a boolean value specifying whether the file or directory does indeed exist or does not.
isDirectory - Archive of obsolete content
summary re
turns a boolean value indicating whether the specified filespecobject is a 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.
... re
turns a boolean value indicating whether the filespecobject is a file or not.
IO - Archive of obsolete content
if the name 'subdirname' refers to a directory, then the re
turned object will refer to this directory.
... the re
turned value is still a nsifile object, however a number of methods may be used which are only of value for subdirectories.
addSession - Archive of obsolete content
« xul reference home addsession( session ) obsolete since gecko 26 re
turn type: nsiautocompletesession adds a new session object to the autocomplete widget.
...this method re
turns the object passed in.
appendCustomToolbar - Archive of obsolete content
« xul reference home appendcustomtoolbar( name, currentset ) firefox only re
turn type: element adds a custom toolbar to the toolbox with the given name.
...the method re
turns the dom element for the created toolbar.
appendItem - Archive of obsolete content
« xul reference home appenditem( label, value ) re
turn type: element creates a new item and adds it to the end of the existing list of items.
...the function re
turns the newly created element.
getBrowserIndexForDocument - Archive of obsolete content
« xul reference home getbrowserindexfordocument( document ) re
turn type: integer re
turns the index of the browser for the specified document in the tabbrowser the method was invoked on.
... the re
turned index is dependent on the tabs in the tabbrowser and is invalidated when the tab ordering changes.
getElementsByAttribute - Archive of obsolete content
« xul reference home getelementsbyattribute( attrib, value ) re
turn type: dom nodelist re
turns a nodelist of all the child elements of the element that have the attribute given by the first argument set to the value given by the second argument.
...note that like most nodelists (but unlike the nodelist re
turned by queryselectorall), the nodelist re
turned by this method is live.
getIcon - Archive of obsolete content
« xul reference home geticon( atab ) re
turn type: string re
turns the url of the specified tab's favicon.
... if atab is null, the current tab's icon is re
turned.
getNextItem - Archive of obsolete content
« xul reference home getnextitem( startitem, delta ) re
turn type: element this method re
turns the item a given distance (delta) after the specified startitem, or null if no such item exists.
... this example will re
turn the item two rows after someitem: getnextitem ( someitem, 2 ); ...
getPreviousItem - Archive of obsolete content
« xul reference home getpreviousitem( startitem, delta ) re
turn type: element this method re
turns the item a given distance (delta) before the specified startitem, or null if no such item exists.
... this example will re
turn the item five rows before someitem: getpreviousitem ( someitem, 5 ); ...
getSelectedItem - Archive of obsolete content
« xul reference home getselecteditem( index ) re
turn type: element when multiple items are selected, you can retrieve each selected item using this method.
...the item index is zero-based, thus this example will re
turn the first selected item: getselecteditem(0).
getSession - Archive of obsolete content
« xul reference home getsession( index ) obsolete since gecko 26 re
turn type: nsiautocompletesession re
turns the session object with the given index.
... this will re
turn an object of type nsiautocompletesession.
getSessionByName - Archive of obsolete content
« xul reference home getsessionbyname( name ) obsolete since gecko 26 re
turn type: nsiautocompletesession re
turns the session object with the given name.
... this will re
turn an object of type nsiautocompletesession.
getTabModalPromptBox - Archive of obsolete content
« xul reference home gettabmodalpromptbox( browser ) re
turn type: object re
turns an object that manages tab-modal prompts for the specified browser.
... re
turns a promptbox object representing the new prompt.
insertItem - Archive of obsolete content
« xul reference home 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 method re
turns the dom element for the created item.
insertItemAt - Archive of obsolete content
« xul reference home insertitemat( index, label, value ) re
turn type: element this method creates a new item and inserts it at the specified position.
...the new item element is re
turned.
loadGroup - Archive of obsolete content
« xul reference home loadgroup( group ) not in firefox re
turn type: the first tab loads a group of pages into multiple tabs.
...this function re
turns a reference to the first tab loaded.
replaceGroup - Archive of obsolete content
« xul reference home replacegroup( group ) not in firefox re
turn type: array of session history objects replaces existing tabs with a new set.
...this method re
turns an array of the session history objects for the tabs that were removed.
MenuItems - Archive of obsolete content
<script> function changetoolbarstate(event) { if (event.target.getattribute("checked") == "true") hidetoolbar(); event.target.removeattribute("checked"); } else { if (!showtoolbar()) re
turn; event.target.setattribute("checked", "true"); } } </script> ...
...the example assumes that the showtoolbar() function might fail so if it re
turns false, the checked attribute is not modified.
Menus - Archive of obsolete content
if it has been activated via navigation with the up or down arrow on the keyboard, then pressing the re
turn key or right arrow key will open the menu.
... if it were a menuitem, then pressing the re
turn key would have launched the command associated with it.
editable - Archive of obsolete content
« xul reference editable type: boolean re
turns true if the element is editable.
... autocomplete fields are editable so this property always re
turns true for those.
Building Trees - Archive of obsolete content
the builder looks at the label for the corresponding cell, translates any variables or predicates into values, and re
turns the value.
...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.
Introduction - Archive of obsolete content
for each result re
turned from the query, generate some content.
... the template syntax allows for different rules to generate different content based on particular criteria as well as set attribute values from re
turned results.
XML Assignments - Archive of obsolete content
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.
Additional Install Features - Archive of obsolete content
if it re
turns success, no error occured.
...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.
More Wizards - Archive of obsolete content
remember to re
turn false in this case, because you have already changed the page yourself.
...rsion="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="thewizard" title="secret code wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkcode(){ document.getelementbyid('thewizard').canadvance = (document.getelementbyid('secretcode').value == "cabbage"); } </script> <wizardpage onpageshow="checkcode(); re
turn true;"> <label value="enter the secret code:"/> <textbox id="secretcode" onkeyup="checkcode();"/> </wizardpage> <wizardpage> <label value="that is the correct secret code."/> </wizardpage> </wizard> there is also a corresponding canrewind property that you can use to enable or disable the back button.
Property Files - Archive of obsolete content
the function getstring() re
turns the value of the string or null if the string does not exist.
...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").
Using the Editor from XUL - Archive of obsolete content
nstexteditorkeylistener this event listener handles key presses for typing, and other editing operations (backspace, delete, enter/re
turn).
... 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.
colorpicker - Archive of obsolete content
://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="re
turn myfunction(event);"/> </window> preference type: id connects the element to a corresponding preference.
... open type: boolean re
turns true if the popup for a button-type colorpicker is open.
deck - Archive of obsolete content
nsertafter, 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 selectedindex type: integer re
turns the index of the currently selected item.
...re
turns -1 if no items are selected do not hide panels; the deck element only understands visible panels.
menuitem - Archive of obsolete content
control type: menu element re
turns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu.
... parentcontainer type: menu element read only property that re
turns the containing menu element, or null if there isn't a containing menu.
menuseparator - Archive of obsolete content
control type: menu element re
turns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu.
... parentcontainer type: menu element read only property that re
turns the containing menu element, or null if there isn't a containing menu.
prefpane - Archive of obsolete content
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.
...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.
tab - Archive of obsolete content
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.
... control type: tabs element re
turns the enclosing tabs element.
tabbox - Archive of obsolete content
selectedindex type: integer re
turns the index of the currently selected item.
...re
turns -1 if no items are selected selectedpanel type: element holds a reference to the currently selected panel within a <tabbox> element.
toolbar - Archive of obsolete content
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 method re
turns the dom element for the created item.
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"/...
...developer.mozilla.org/en/docs/xul_tutorial:open_and_save_dialogs */ var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"].createinstance(nsifilepicker); fp.init(window, "open file", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filtertext | nsifilepicker.filterall); var res = fp.show(); if (res == nsifilepicker.re
turnok) { var thefile = fp.file; alert(thefile.leafname); // --- do something with the file here --- } } xul does not currently support any other common dialogs.
Getting started with XULRunner - Archive of obsolete content
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.
...ry/frameworks/xul.framework/xulrunner-bin "/applications/finkle/testapp.app/contents/resources/application.ini" you may run it without installing (but with the menu bar and dock icon missing) in os x by typing: /library/frameworks/xul.framework/xulrunner-bin "/<full path>/testapp/application.ini" note: the full path is required or a "error: couldn't parse application.ini."-message will be re
turned.
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...
... } 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.
Using SOAP in XULRunner 1.9 - Archive of obsolete content
since the native soap interface was removed from gecko 1.9, those stuck speaking to soap apis need a new place to
turn.
...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...
NPFullPrint - Archive of obsolete content
if you want the plug-in to take complete control of the printing process, it should print the full page and set the field pluginprinted to true before re
turning.
... if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and re
turn immediately; the browser calls npp_print again with the npembedprint substructure of npprint.
NPN_UserAgent - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary re
turns the browser's user agent field.
... re
turns a pointer to a buffer that contains the user agent field of the browser.
NPStream - Archive of obsolete content
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.
...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.
NP_GetMIMEDescription - Archive of obsolete content
np_getmimedescription re
turns a supported mime type list for your plugin.
... 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.
NP_Initialize - Archive of obsolete content
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.
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...
-moz-window-shadow - Archive of obsolete content
however, for these windows shadows were
turned off and there was no way to
turn them on.
...this version introduced the -moz-window-shadow css property to provide a way to
turn off unwanted shadows.
Introduction - Archive of obsolete content
what really happens with the {} notation is that the variables' tostring method is called, and the re
turned value is placed in the element.
...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>.
Generator comprehensions - Archive of obsolete content
var numbers = [1, 2, 3]; // generator function (function*() { for (let i of numbers) { 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).
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
asyncoperationid must correspond to the operation name previously re
turned from debug.mstraceasyncoperationstarting.
... }, 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.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
asyncoperationid must correspond to the operation id previously re
turned from debug.mstraceasyncoperationstarting.
... }, 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.
Enumerator - Archive of obsolete content
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.
VBArray.dimensions - Archive of obsolete content
the vbarray.dimensions method re
turns the number of dimensions in a vbarray.
...o 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } re
turn(s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> 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 internet explorer 10 standards.
Object.observe() - Archive of obsolete content
re
turn value the object to be observed.
...| change.name === 'title') { updategreeting(); } }); }); custom change type // a point on a 2d plane var point = {x: 0, y: 0, distance: 0}; function setposition(pt, x, y) { // performing a custom change object.getnotifier(pt).performchange('reposition', function() { var olddistance = pt.distance; pt.x = x; pt.y = y; pt.distance = math.sqrt(x * x + y * y); re
turn {olddistance: olddistance}; }); } object.observe(point, function(changes) { console.log('distance change: ' + (point.distance - changes[0].olddistance)); }, ['reposition']); setposition(point, 3, 4); // distance change: 5 specifications not part of any standard.
String.prototype.quote() - Archive of obsolete content
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.
Archived JavaScript Reference - Archive of obsolete content
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.
...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 (").
Implementation Status - Archive of obsolete content
partial binds using index() are not 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.
Mozilla XForms Specials - Archive of obsolete content
in the mozilla xforms extension we added a getinstancedocuments() function to the model which re
turns all the model's instance documents.
...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.
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
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.
The Business Benefits of Web Standards - Archive of obsolete content
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.
... all these factors also contribute to easier site management, a larger audience and a better re
turn on investment.
Windows Media in Netscape - Archive of obsolete content
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}"); } .....
... <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.
Unconventional controls - Game development
this time it's about detecting sound waves bouncing off objects and re
turning to the microphone.
... 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.
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
(function () { var aname = "barry"; })(); // variable aname is not accessible from the outside scope aname // throws "uncaught referenceerror: aname is not defined" assigning the iife to a variable stores the function's re
turn value, not the function definition itself.
... var result = (function () { var name = "barry"; re
turn name; })(); // immediately creates the output: result; // "barry" ...
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
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.
...al times in a row, the client gets the same results: get /pagex http/1.1 get /pagex http/1.1 get /pagex http/1.1 get /pagex http/1.1 post /add_row http/1.1 is not idempotent; if it is called several times, it adds several rows: post /add_row http/1.1 post /add_row http/1.1 -> adds a 2nd row post /add_row http/1.1 -> adds a 3rd row delete /idx/delete http/1.1 is idempotent, even if the re
turned status code may change between requests: delete /idx/delete http/1.1 -> re
turns 200 if idx exists delete /idx/delete http/1.1 -> re
turns 404 as it just got deleted delete /idx/delete http/1.1 -> re
turns 404 learn more general knowledge definition of idempotent in the http specification.
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
a signature can include: parameters and their types a re
turn value and type exceptions that might be thrown or passed back information about the availability of the method in an object-oriented program (such as the keywords public, static, or prototype).
... the void keyword indicates that this method has no re
turn value.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... the method symbol.for(tokenstring) re
turns a symbol value from the registry, and symbol.keyfor(symbolvalue) re
turns a token string from the registry; each is the other's inverse, so the following is true: symbol.keyfor(symbol.for("tokenstring")) === "tokenstring" // true learn more general knowledge symbol (programming) on wikipedia javascript data types and data structures symbols in ecmascript 6 symbol in the mdn js reference...
Assessment: Accessibility troubleshooting - Learn web development
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.
...can you make it keyboard accessible, both in terms of focusing it using the tab key, and activating it using the re
turn key?
Debugging CSS - Learn web development
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.
... 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.
The box model - Learn web development
if you want to
turn on the alternative model for an element you do so by setting box-sizing: border-box on it.
...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.
Flexbox - Learn web development
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.
...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.
Introduction to CSS layout - Learn web development
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.
... 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.
Supporting older browsers - Learn web development
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.
... } .item { float: left; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } <div class="wrapper"> <div class="item">item one</div> <div class="item">item two</div> <div class="item">item three</div> </div> note: the clear property also has no effect once the cleared item becomes a grid item, so you could have a layout with a cleared footer, which is then
turned into a grid layout.
What is CSS? - Learn web development
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.
...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.
CSS first steps - Learn web development
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.
...in this lesson we will take a look at how a browser takes css and html and
turns that into a webpage.
Fundamental text and font styling - Learn web development
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.
How does the Internet work? - Learn web development
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.
...this modem
turns the information from our network into information manageable by the telephone infrastructure and vice versa.
How do I use GitHub Pages? - Learn web development
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.
... 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.
What is a web server? - Learn web development
(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.
... if neither process is possible, the web server re
turns an error message to the browser, most commonly 404 not found.
How do you set up a local testing server? - Learn web development
to check python is installed, enter the following command: python -v # or you might have the py command available, # in which case try py -v this should re
turn a version number.
... 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.
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 forms through JavaScript - Learn web development
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.
...eader.readystate === filereader.loading ) { reader.abort(); } reader.readasbinarystring( file.dom.files[0] ); } ); // senddata is our main function function senddata() { // if there is a selected file, wait it is read // if there is not, delay the execution of the function if( !file.binary && file.dom.files.length > 0 ) { settimeout( senddata, 10 ); re
turn; } // to construct our multipart form data request, // we need an xmlhttprequest instance const xhr = new xmlhttprequest(); // we need a separator to define each part of the request const boundary = "blob"; // store our body request in a string.
UI pseudo-classes - Learn web development
while it is being clicked on, or when the re
turn/enter key is being pressed down in the case of a keyboard activation).
...in the range of 12-120), the input
turns valid.
Dealing with files - Learn web development
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...
HTML basics - Learn web development
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.
... 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 ...
Getting started with HTML - Learn web development
edit the line below in the input area to
turn it into a link to your favorite website.
...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.
Test your skills: Advanced HTML text - Learn web development
advanced html text 1 in this task we want you to
turn the provided animals and their definitions into a description list.
... advanced html text 2 in this task we want you to add some semantics to the provided html as follows:
turn the second paragraph into a block-level quote, and semantically indicate that the quote is taken from accessibility.
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...
... 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).
Assessment: Structuring planet data - Learn web development
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.
...sa
turn) are a little tricky to sort out — you need to make sure each one spans the correct number of rows and columns.
Build your own function - Learn web development
in the next article we'll wrap up functions by explaining another essential related concept — re
turn values.
... previous overview: building blocks next 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 ...
Image gallery - Learn web development
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.
... 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 object basics - Learn web development
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.
... 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.
Measuring performance - Learn web development
webpagetest.org is another example of a tool that automatically tests your site and re
turns useful metrics.
...for example, the firefox network monitor re
turns detailed information on all the assets downloaded form the network, along with a time graph that shows how long each one took to download.
Perceived performance - Learn web development
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.
... 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.
Website security - Learn web development
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.
Getting started with Svelte - Learn web development
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.
...() { if (name === 'world') { name = 'svelte' } else { name = 'world' } } </script> <main> <h1>hello {name}!</h1> <button on:click={togglename}>toggle name</button> <p>visit the <a href="https://svelte.dev/tutorial">svelte tutorial</a> to learn how to build svelte apps.</p> </main> whenever the button is clicked, svelte executes the togglename() function, which in
turn updates the value of the name variable.
Using Vue computed properties - Learn web development
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>.
Handling common HTML and CSS problems - Learn web development
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.
... in the search packages text field, type "lint" and press enter/re
turn to search for linting-related packages.
Deploying our app - Learn web development
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.
...for this you need your github username and then — if you do not have two-factor authentication (2fa)
turned on — your github password.
Introducing a complete toolchain - Learn web development
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".
... 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.
Choosing the right memory allocator
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.
... do not use nscrt::strdup for re
turning values from an xpcom object, as that uses a different allocator.
Debugging on Windows
here are some wildcards you can use (tested with vc 8): nscomptr.*\:\:.*=nostepinto (nsg|g)etter_*addrefs.*=nostepinto ns_convertutf.* ; might be too broad: (ns|promise)[^\:]*[ss]tring.* ...add common functions to this list should probably make a .reg file for easy importing obtaining stdout and other file handles running the following command in the command window in visual studio re
turns the value of stdout, which can be used with various debugging methods (such as nsgenericelement::list) that take a file* param: debug.evaluatestatement {,,msvcr80d}(&__iob_func()[1]) (alternatively you can evaluate {,,msvcr80d}(&__iob_func()[1]) in the quickwatch window) similarly, you can open a file on the disk using fopen: >debug.evaluatestatement {,,msvcr80d}fopen("c:\\123", "w") 0x1031...
... 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.
Creating Custom Events That Can Pass Data
you will find that there is a bunch of code like: if (aeventtype.lowercaseequalsliteral("{somethingsomething}event")) re
turn ns_{somethingsomething}event(adomevent, aprescontext, nsnull); you can either have a function like this or write the code straight in nseventlistenermanager::createevent() like this: if (aeventtype.lowercaseequalsliteral("nsmyevent")){ //note: the lowercase is important!
... nsdomevent* it = new nsdommyevent(aprescontext, aevent); if (nsnull == it) { re
turn ns_error_out_of_memory; } re
turn callqueryinterface(it, adomevent); } in general though i'd strongly recommend using a function the way that everyone else does.
Eclipse CDT Manual Setup
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.
... whenever you create a new workspace for a mozilla source tree, you should be sure to
turn off the following two settings in the workspace preferences (window > preferences, or eclipse > preferences) before creating a project in that workspace: in "general > workspace", disable "build automatically" in "c/c++ > indexer", disable "automatically update the index"
turning off automatic indexing prevents the cpu intensive indexer from running at various stages during the steps below ...
Inner and outer windows
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 other words, window always re
turns the outer window.
Listening to events on all tabs
if any registered progress listener re
turns false from this method then the attempt to refresh will be blocked.
... re
turn value true if the refresh may proceed.
mach
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!
... the re
turn value from the @command method should be the integer exit code from the process.
Communicating with frame scripts
synchronous messaging to send a synchronous 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().
... because a single message can be received by more than one listener, the re
turn value of sendsyncmessage() is an array of all the values re
turned from every listener, even if it only contains a single value: // frame script addeventlistener("click", function (event) { var results = sendsyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }); content.console.log(results[0]); // "value from chrome" }, false); like arguments, re
turn values from sendsyncmessage() must be json-serializable, so chrome can't re
turn functions.
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.
... if the above doesn't work try this: function contentmmfromcontentwindow_method2(acontentwindow) { re
turn acontentwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidocshell) .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsicontentframemessagemanager); } ...
HTMLIFrameElement.executeScript()
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.
...e.com/index.html'}); request1.onsuccess = function() { console.log(request1.result); // 6 } var request2 = browser.executescript( new promise((resolve, reject) => { settimeout(function() { resolve(6); }, 1000}) ) , {origin: 'http://example.com'}); request2.onsuccess = function() { console.log(request2.result); // 6 } if the script value is a not a promise, it is simply re
turned as the request value.
HTMLIFrameElement.getContentDimensions()
note: the values re
turned are equivalent to document.body.scrollwidth and document.body.scrollheight.
... syntax var instanceofdomrequest = instanceofhtmliframeelement.getcontentdimensions(); re
turns a domrequest for handling the dimensions request.
HTMLIFrameElement.getManifest()
the getmanifest() method of the htmliframeelement interface retrieves the manifest of an app loaded in the browser <iframe> and re
turns it as json.
... re
turn value a promise that resolves to a json object representation of the loaded app's manifest.
mozbrowsercontextmenu
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.
...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.
mozbrowsermetachange
details the details property re
turns an anonymous javascript object with the following properties: name a domstring representing the <meta> name attribute value.
...if not included, the value re
turned is undefined.
Browser API
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.
... htmliframeelement.getmanifest() retrieves the manifest of an app loaded in the browser <iframe> and re
turns it as json.
IPDL Type Serialization
re
turn false if deserialization failed } }; } // namespace ipc the standard ipdl types (integers, floats, and xpcom strings) already have serializers.
...t paramtype; static void write(message* amsg, const paramtype& aparam) { writeparam(amsg, aparam.i); writeparam(amsg, aparam.j); for (int i = 0; i < 4; ++i) writeparam(amsg, aparam.k[i]); } static bool read(const message* amsg, void** aiter, paramtype* aresult) { if (!readparam(amsg, aiter, &(aresult->i)) || !readparam(amsg, aiter, &(aresult->j))) re
turn false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) re
turn false; re
turn true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<examplestruct>) by simply declaring "using nstarray<examplestruct>;' in your ipdl file, then using it in a ipc method.
Internationalized Domain Names (IDN) Support in Mozilla Browsers
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.
... 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.
JavaScript Tips
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.
...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.
DownloadList
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 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.
Http.jsm
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.
ISO8601DateUtils.jsm
re
turn value an iso 8601 format date string.
... re
turn value a javascript date object corresponding to the specified date string.
Interfacing with the Add-on Repository
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); }, 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.
OS.File.Error
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.
Mozilla Style System
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.
...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(); ...
Investigating leaks using DMD heap scan mode
the allowed values here are the same as those re
turned by xre_getprocesstype(), so adjust as needed.
... 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.
Leak-hunting strategies and tips
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().
Power profiling overview
that in
turn depends on the software running on the device.
... try
turning hardware acceleration on or off; e10s on or off; flash on or off.
Profiling with Xperf
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.
...also experiment with
turning columns on and off; removing a column will allow data to be aggregated without considering that column's contributions.
Reporting a Performance Problem
the toolbar icon
turns blue when it is recording.
... 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.
Optimizing Applications For NSPR
the nspr process creation api functions re
turn an error when invoked on windows 3.1.
...nspr functions re
turning floating point types and structs by value, including the derived types print64, are declared <tt>__pascal</tt>.
I/O Functions
whe the pollable event is set, pr_poll re
turns the the pr_poll_read flag set in the out_flags.
... 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).
PLHashComparator
it re
turns a nonzero value if the two values are equal, and 0 if the two values are not equal.
... remark the re
turn value of plhashcomparator functions should be of type prbool.
PL_CompareStrings
if the two strings are equal, it re
turns 1.
... if the two strings are not equal, it re
turns 0.
PL_HashTableAdd
re
turns a pointer to the new entry.
... pl_hashtableadd re
turns null if there is not enough memory to create a new entry.
PL_strdup
re
turns a pointer to a new memory node in the nspr heap containing a copy of a specified string.
... re
turns the function re
turns one of these values: if successful, a pointer to a copy of the specified string.
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.
PRDescIdentity
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.
...the string is copied by the runtime, and pr_getnameforidentity re
turns a reference to that copy.
PRFileMap
type re
turned by pr_createfilemap and passed to pr_memmap and pr_closefilemap.
...before actually mapping a file to memory, you must create a memory-mapped file object by calling pr_createfilemap, which re
turns a pointer to prfilemap.
PRIOMethods
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)).
...in cases where this partial implementation occurs, the function re
turns an error indication with an error code of pr_invalid_method_error.
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.
PR_Accept
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 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_AtomicDecrement
re
turns the function re
turns the decremented value (i.e., the result).
...the value re
turned is the referenced variable's final value.
PR_AttachSharedMemory
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.
... re
turns address where shared memory is mapped, or null if an error occurs.
PR_Available
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.
... if the function fails, it re
turns the value -1.
PR_Available64
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.
... if the function fails, it re
turns the value -1.
PR_Calloc
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().
PR_CWait
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_CancelJob
syntax #include <prtpool.h> nspr_api(prstatus) pr_canceljob(prjob *job); parameter the function has the following parameter: job a pointer to a prjob structure re
turned by a pr_queuejob function representing the job to be cancelled.
... re
turns prstatus ...
PR_Cleanup
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.
...when the primordial thread re
turns from main, the process immediately and silently exits.
PR_Close
re
turns one of the following values: if file descriptor is closed successfully, pr_success.
...on successful re
turn, pr_close frees the dynamic memory and other resources identified by the fd parameter.
PR_CloseDir
re
turns if successful, pr_success.
...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.
PR_CloseSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_closesemaphore(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 ...
PR_CloseSharedMemory
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_CreateFileMap
re
turns if successful, a file mapping of type prfilemap.
...the re
turned file-mapping object must be passed to pr_memmap to actually map a section of the file to memory.
PR_DeleteSharedMemory
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_DetachSharedMemory
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.
... re
turns prstatus.
PR_DetachThread
re
turns the function re
turns nothing.
...the call re
turns after the nspr thread object is destroyed.
PR_EnterMonitor
description when the calling thread re
turns, it will have acquired the monitor's lock.
... 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.
PR_ExplodeTime
re
turns nothing; the buffer pointed to by exploded is filled with the exploded time.
...upon re
turn, the location pointed to by the exploded parameter contains the converted time value.
PR_FamilyInet
syntax #include <prnetdb.h> pruint16 pr_familyinet(void); re
turns the value of the address family for internet protocol.
...the re
turned value can be assigned to the inet.family field of a prnetaddr object.
PR GetCanonNameFromAddrInfo
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.
PR_GetCurrentThread
re
turns the current thread object for the currently running code.
... syntax #include <prthread.h> prthread* pr_getcurrentthread(void); re
turns always re
turns a valid reference to the calling thread--a self-identity.
PR_GetDescType
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.
PR_GetError
re
turns the current thread's last set platform-independent error code.
... syntax #include <prerror.h> prerrorcode pr_geterror(void) re
turns the value re
turned is a 32-bit number.
PR_GetErrorTextLength
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
re
turns one of the following values: if the file information is successfully obtained, pr_success.
...the file size is re
turned as an unsigned 32-bit integer.
PR_GetFileInfo64
re
turns one of the following values: if the file information is successfully obtained, pr_success.
...the file size is re
turned as an unsigned 64-bit integer.
PR_GetHostByAddr
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.
PR_GetHostByName
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.
PR_GetOSError
re
turns the current thread's last set os-specific error code.
... syntax #include <prerror.h> print32 pr_getoserror(void) re
turns the value re
turned is a 32-bit signed number.
PR_GetPeerName
addr on re
turn, the address of the peer connected to the socket.
... re
turns if successful, pr_success.
PR_GetRandomNoise
re
turns prsize value equal to the size of the random number actually generated, or zero.
...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.
PR_GetSockName
addr on re
turn, the address of the socket.
... re
turns if successful, pr_success.
PR_GetUniqueIdentity
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.
PR_ImplodeTime
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 ImportTCPSocket
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.
...the caller gives up control of the native tcp socket osfd and should use the prfiledesc* re
turned by pr_importtcpsocket instead.
PR_JoinJob
syntax #include <prtpool.h> nspr_api(prstatus) pr_joinjob(prjob *job); parameter the function has the following parameter: job a pointer to a prjob structure re
turned by a pr_queuejob function representing the job to be cancelled.
... re
turns prstatus ...
PR_Listen
re
turns the function re
turns one of the following values: upon successful completion of listen request, pr_success.
... description pr_listen
turns the specified socket into a rendezvous socket.
PR_LocalTimeParameters
re
turns the time zone offset information that maps the specified prexplodedtime to local time.
... re
turns a time parameters structure that expresses the time zone offsets at the specified time.
PR_MALLOC
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().
PR_MemMap
re
turns the starting address of the memory region to which the section of file is mapped.
... re
turns null on error.
PR_NEWZAP
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.
PR NewProcessAttr
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.
PR_NewThreadPrivateIndex
re
turns a new index for a per-thread private data table and optionally associates a destructor with the data that will be assigned to the index.
... re
turns the function re
turns one of the following values: if successful, pr_success.
PR_Open
if the file already exists, no action and null is re
turned.
...up pr_iwgrp 0020 write permission, group pr_ixgrp 0010 execute/search permission, group pr_irwxo 0007 read, write, execute/search by others pr_iroth 0004 read permission, others pr_iwoth 0002 write permission, others pr_ixoth 0001 execute/search permission, others re
turns the function re
turns one of the following values: if the file is successfully opened, a pointer to a dynamically allocated prfiledesc for the newly opened file.
PR_OpenAnonFileMap
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.
PR_PostSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_postsemaphore(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 ...
PR_PushIOLayer
re
turns the function re
turns one of the following values: if the layer is successfully pushed onto the stack, pr_success.
...in other words, stack continues to point to the top of the stack after the function re
turns.
PR_Realloc
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().
PR_RecvFrom
addr a pointer to the prnetaddr object that will be filled in with the address of the sending peer on re
turn.
... re
turns the function re
turns one of the following values: a positive number indicates the number of bytes actually received.
PR_RmDir
re
turns if successful, pr_success.
...if the directory is not empty, pr_rmdir fails and pr_geterror re
turns the error code pr_directory_not_empty_error.
PR_Seek
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.
PR_Seek64
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.
PR_SetThreadPrivate
re
turns the function re
turns one of the following values: if successful, pr_success.
...on re
turn, the private data associated with the index is reassigned the new private data's value, even if it is null.
PR_Unmap
re
turns the function re
turns one of the following values: if the memory region is successfully unmapped, pr_success.
...the parameter addr is the re
turn value of an earlier call to pr_memmap.
PR_WaitForPollableEvent
blocks the calling thread until the pollable event is set, and then atomically unsetting the event before re
turning.
... re
turns the function re
turns one of the following values: if successful, pr_success.
Threads
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.
... pr_getcurrentthread re
turns the current thread object for the currently running code.
An overview of NSS Internals
it's important to note that nss requires strict cleanup for all handles re
turned by nss.
...the data will be processed and either re
turned directly or sent to a callback function registered in the context.
NSS Memory allocation
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.
...the second user will allocated it from the free list and re
turn it to the free list.
NSS 3.16 release notes
bug 981170: aeskeywrap_decrypt should not re
turn secsuccess for invalid keys.
... bugs fixed in nss 3.16 this bugzilla query re
turns all the bugs fixed in nss 3.16: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.16 ...
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 ...
...0 cn = globalsign ecc root ca - r4 sha1 fingerprint: 69:69:56:2e:40:80:f4:24:a1:e7:19:9f:14:ba:f3:ee:58:ab:6a:bb cn = globalsign ecc root ca - r5 sha1 fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa the version number of the updated root ca list has been set to 2.2 bugs fixed in nss 3.17.3 this bugzilla query re
turns all the bugs fixed in nss 3.17.3: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.3 compatibility nss 3.17.3 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.18.1 release notes
the websites and code signing trust bits were
turned off in nss 3.18.
... 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.
NSS 3.18 release notes
the following ca certificates had the websites and code signing trust bits
turned off ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a cn = equifax secure global ebusiness ca-1 sha1 fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45 cn = tc trustcenter class 3 ca ii sha1 fingerprint: 80:25:ef:f4:6e:70:c8:d4:72:24:65:84:fe:4...
...:d4 cn = entrust root certification authority - ec1 sha1 fingerprint: 20:d8:06:40:df:9b:25:f5:12:25:3a:11:ea:f7:59:8a:eb:14:b5:47 cn = cfca ev root sha1 fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83 the version number of the updated root ca list has been set to 2.3 bugs fixed in nss 3.18 this bugzilla query re
turns all the bugs fixed in nss 3.18: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.18 compatibility nss 3.18 shared libraries are backward compatible with all older nss 3.x shared libraries.
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...
...ayıcısı h6 sha1 fingerprint: 8a:5c:8c:ee:a5:03:e6:05:56:ba:d8:1b:d4:f6:c9:b0:ed:e5:2f:e0 cn = certinomis - root ca sha1 fingerprint: 9d:70:bb:01:a5:a4:a0:18:11:2e:f7:1c:01:b9:32:c5:34:e7:88:a8 the version number of the updated root ca list has been set to 2.5 bugs fixed in nss 3.19.3 this bugzilla query re
turns all the bugs fixed in nss 3.19.3: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.19.3 compatibility nss 3.19.3 shared libraries are backward compatible with all older nss 3.19 shared libraries.
NSS 3.19 release notes
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.
... 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.
NSS 3.23 release notes
dded cn = szafir root ca2 sha-256 fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe cn = certum trusted network ca 2 sha-256 fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 the following ca certificate had the email trust bit
turned on cn = actalis authentication root ca sha-256 fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1: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.
... 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.
NSS 3.30 release notes
new functions in cert.h cert_compareava - performs a comparison of two certava structures, and re
turns a seccomparison result.
... 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.
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...
... 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.
NSS Sample Code sample4
*/ #include "nss.h" #include "pk11pub.h" /* this callback is responsible for re
turning the password to the nss * key database.
...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
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.
...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.
FC_CancelFunction
fc_cancelfunction is a legacy function that simply re
turns ckr_function_not_parallel.
... re
turn value fc_cancelfunction always re
turns ckr_function_not_parallel.
FC_DecryptFinal
description fc_decryptfinal re
turns the last block of data of a multi-part decryption operation.
... re
turn value examples see also fc_decryptinit, nsc_decryptfinal ...
FC_DigestKey
the digest for the entire message is re
turned by a call to fc_digestfinal.
... re
turn value examples see also fc_digestinit, fc_digestfinal, nsc_digestkey ...
FC_DigestUpdate
the digest for the entire message is re
turned by a call to fc_digestfinal.
... re
turn value examples see also fc_digestinit, fc_digestfinal, nsc_digestupdate ...
FC_EncryptFinal
description fc_encryptfinal re
turns the last block of data of a multi-part encryption operation.
... re
turn value examples see also fc_encryptinit, nsc_encryptfinal ...
FC_GenerateKey
the handle of new key is re
turned.
... re
turn value examples see also nsc_generatekey ...
FC_GenerateKeyPair
the handles of new keys are re
turned.
... re
turn value examples see also nsc_generatekeypair ...
FC_GetFunctionStatus
description fc_getfunctionstatus is a legacy function that simply re
turns ckr_function_not_parallel.
... re
turn value fc_getfunctionstatus always re
turns ckr_function_not_parallel.
FC_Initialize
re
turn value fc_initialize re
turns the following re
turn codes.
...(note: we probably should re
turn ckr_host_memory instead.) the software integrity test or power-up self-tests failed.
FC_Login
re
turn value fc_login() re
turns the following re
turn codes.
... the function should re
turn ckr_pin_incorrect in this case.
FC_SignRecover
if psignature is null only the length of the signature is re
turned in *pussignaturelen.
... re
turn value examples see also nsc_signrecover ...
FC_SignUpdate
the signature for the entire message is re
turned by a call to fc_signfinal.
... re
turn value examples see also fc_signinit, fc_signfinal, nsc_signupdate ...
FC_UnwrapKey
if pwrappedkey is null the length of the wrapped key is re
turned in puswrappedkeylen and fc_unwrapkey may be called again with pwrappedkey set to retrieve the wrapped key.
... re
turn value examples see also nsc_unwrapkey ...
FC_Verify
re
turn value ckr_ok is re
turned on success.
... ckr_signature_invalid is re
turned for signature mismatch.
FC_VerifyRecover
if psignature is null only the length of the signature is re
turned in *pussignaturelen.
... re
turn value examples see also nsc_verifyrecover ...
FC_VerifyUpdate
the result for the entire message is re
turned by a call to fc_verifyfinal.
... re
turn value examples see also fc_verifyfinal, nsc_verifyupdate ...
FC_WrapKey
if pwrappedkey is null the length of the wrapped key is re
turned in puswrappedkeylen and fc_wrapkey may be called again with pwrappedkey set to retrieve the wrapped key.
... re
turn value examples see also nsc_wrapkey ...
NSC_Login
re
turn value nsc_login() re
turns the following re
turn codes.
... ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255).the function should re
turn ckr_pin_incorrect in this case.
NSS tools : certutil
ssl,s/mime, jar/xpi ca administrator of instance pki-ca1's example domain id u,u,u tps administrator's example domain id u,u,u google internet authority ,, certificate authority - example domain ct,c,c using additional arguments with -l can re
turn and print the information for a single, specific certificate.
...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.
NSS_3.12.3_release_notes.html
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.
...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
es ssl,s/mime,jar/xpi ca administrator of instance pki-ca1's example domain id u,u,u tps administrator's example domain id u,u,u google internet authority ,, certificate authority - example domain ct,c,c using additional arguments with -l can re
turn and print the information for a single, specific certificate.
...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.
Necko walkthrough
utputstreamready nshttpconnection::onsocketwritable tries to write the request data from the current transaction (mtransaction) tells the transaction to now wait (`resumerecv) nshttpconnection::resumerecv nshttptransaction::readsegments readrequestsegment is passed to mrequeststream->readsegments - this function pointer is called and used to read the request bytes, which in
turn calls ...
...back on the main thread: nsinputstreampump::oninputstreamready this function in
turn calls nsinputstreampump::onstatestart, nsinputstreampump::onstatetransfer and nsinputstreampump::onstatestop.
Rhino overview
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).
... 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).
Performance Hints
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.
...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.
Creating JavaScript jstest reftests
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.
...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.
64-bit Compatibility
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.
... stobj_get_fslot - re
turns jsval-width lins stobj_get_dslot - re
turns jsval-width lins stobj_set_dslot - stores jsval-width lins stobj_set_fslot - stores jsval-width lins box_jsval - re
turns jsval-width lins unbox_jsval - expects jsval-width lins ...
Invariants
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.
...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.
INT_FITS_IN_JSVAL
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.
JS::Add*Root
on success, these functions re
turn true.
... otherwise they report an out of memory error and re
turn false.
JS::Compile
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.
JS::CompileFunction
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.
JS::Evaluate
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.
JS::GetFirstArgumentAsTypeHint
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.
JS::GetSelfHostedFunction
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.
JS::Handle
method description const t *address() const re
turns a pointer to ptr.
... const t &get() const re
turns ptr.
JS::MutableHandle
method description const t &get() const re
turns *ptr.
... operator const t&() const t operator->() const t *address() re
turns ptr.
JS::NewFunctionFromSpec
on success, js::newfunctionfromspec re
turns a pointer to newly created function.
... on error, it re
turns nullptr.
JS::OrdinaryToPrimitive
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.
JS::Rooted
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.
JS::ToInt32
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.
JS::ToInt64
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.
JS::ToNumber
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.
JS::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.
JS::ToUint16
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.
JS::ToUint32
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.
JS::ToUint64
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.
JSConvertOp
on success it must re
turn a primitive value in *vp.
...(support for the other types may eventually be removed.) the callback re
turns true to indicate success or false to indicate failure.
JSFunction
the apis js_newfunction, js_definefunction, js_compilefunction, and their unicode equivalents re
turn values of type jsfunction *.
... for native functions and jsapi-compiled functions - that is, functions re
turned by the apis listed above-there is a simple one-to-one relationship between the jsfunction and the corresponding javascript function object.
JSGetObjectOps
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.
...it re
turns a pointer to a jsobjectops which is then used as a virtual table for operations on the new object.
JSNewResolveOp
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.
JSObjectOps.defaultValue
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.
JSObjectOps.getProperty
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.
JSObjectOps.newObjectMap
re
turn null on error, non-null on success.
...usually, the nrefs parameter to jsobjectops.newobjectmap will be 1, to count the ref re
turned to the caller on success.
JSObjectPrincipalsFinder
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.
JSPrincipalsTranscoder
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.
JSReserveSlotsOp
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).
...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.
JSResolveOp
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.
JS_ASSERT_STRING_IS_FLAT
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.
JS_AddExternalStringFinalizer
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.
JS_Add*Root
on success, these functions re
turn js_true.
... otherwise they report an out of memory error and re
turn js_false.
JS_BufferIsCompilableUnit
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.
JS_CheckAccess
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.
JS_ClearPendingException
(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.
...many jsapi functions can simply report an error and re
turn false without building and throwing an exception object.
JS_CompareStrings
on success the function re
turns js_true.
... on error, it re
turns js_false and the value in result is unchanged.
JS_CompileFunction
(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.
JS_CompileFunctionForPrincipals
on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals re
turn a pointer to the newly compiled function.
... on error or exception, they re
turn null.
JS_CompileScript
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.
JS_CompileScriptForPrincipals
on success, js_compilescriptforprincipals and js_compileucscriptforprincipals re
turn a pointer to the compiled script.
... on error or exception, they re
turn null.
JS_CompileUTF8File
on success, js_compileutf8file re
turns an object that represents the newly compiled script.
... otherwise it re
turns null.
JS_CompileUTF8FileHandle
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_ConcatStrings
description js_concatstrings concatenates two js strings, str1 and str2, and re
turns the result.
...when the string concatenation fails null is re
turned.
JS_ConstructObject
on success, js_constructobject re
turns a pointer to the newly instantiated object.
... otherwise it re
turns null.
JS_ContextIterator
each call to js_contextiterator re
turns the next context in the cycle.
... js_contextiterator re
turns the new value of *iterp.
JS_ConvertArgumentsVA
if js_convertargumentsva successfully converts all arguments, it re
turns true.
... otherwise it re
turns false.
JS_ConvertValue
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.
JS_DecompileFunction
if successful, js_decompilefunction re
turns a string containing the text of the function.
... otherwise, it re
turns null.
JS_DefaultValue
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.
JS_DefineConstDoubles
on success, js_defineconstdoubles/js_defineconstintegers re
turns true, indicating it has created all properties listed in the array.
... otherwise it re
turns false.
JS_DefineElement
on success, js_defineelement re
turns true.
... otherwise it re
turns false.
JS_DefineFunction
on success, js_definefunction and js_defineucfunction re
turn a pointer to the new function.
... on error or exception, they re
turn null.
JS_DefineFunctions
on success, js_definefunctions re
turns true.
... on error or exception, it stops defining functions and re
turns false.
JS_DefineObject
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.
JS_DefineProperties
on success, js_defineproperties re
turns true, indicating it has created all properties listed in the array.
... otherwise it re
turns false.
JS_DefineProperty
on success, js_defineproperty re
turns true.
... on error or exception, it re
turns false.
JS_DefinePropertyWithTinyId
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.
JS_DeleteProperty
if the hook re
turns false, the error is propagated.
... these functions re
turn true on success, regardless of whether a property was actually deleted, and false on error or exception.
JS_EncodeStringToBuffer
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.
JS_EnterCrossCompartmentCall
on success, js_entercrosscompartmentcall re
turns a pointer to a jscrosscompartmentcall object that must be passed to js_leavecrosscompartmentcall.
... otherwise it re
turns null.
JS_EnterLocalRootScope
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.
... js_leavelocalrootscope(cx); re
turn ok; } note: js_leavelocalrootscope or js_leavelocalrootscopewithresult must be called once for every prior successful call to js_enterlocalrootscope.
JS_EvaluateScript
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.
JS_EvaluateScriptForPrincipals
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.
JS_ExecuteScript
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.
JS_ExecuteScriptPart
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.
JS_ExecuteScriptVersion
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.
JS_ForwardGetPropertyTo
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.
JS_GetArrayLength
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.
JS_GetArrayPrototype
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.
JS_GetClass
description js_getclass re
turns a pointer to the jsclass associated with a specified js object, obj.
...if obj has no jsclass, this re
turns null.
JS_GetDefaultFreeOp
this article covers features introduced in spidermonkey 17 re
turn default jsfreeop for the runtime.
... description js_getdefaultfreeop re
turns default jsfreeop for the runtime.
JS_GetErrorPrototype
this article covers features introduced in spidermonkey 38 re
turn the original value of error.prototype.
... description js_geterrorprototype re
turns the original value of error.prototype from the global object of the current compartment of cx.
JS_GetExternalStringClosure
this article covers features introduced in spidermonkey 6 re
turns the string closure stored in a jsstring created by calling js_newexternalstringwithclosure.
... str jsstring * the string for which to re
turn the closure.
JS_GetFlatStringChars
syntax const jschar * js_getflatstringchars(jsflatstring *str); name type description str jsflatstring * the flattended string re
turned by js_flattenstring.
... description jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) re
turn js_false; const jschar *chars = js_getflatstringchars(fstr) js_assert(chars); see also js_flattenstring bug 1037869 ...
JS_GetFunctionCallback
re
turns the callback currently configured to be called when javascript functions are invoked or exited, as established by a prior call to js_setfunctioncallback.
... description js_getfunctioncallback re
turns the current function invocation callback, or null if there isn't one set up.
JS_GetFunctionName
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.
JS_GetFunctionPrototype
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.
JS_GetFunctionScript
description js_getfunctionscript re
turns a pointer to jsscript for the specified function, fun.
... if fun is a native function, it re
turns null.
JS_GetGCParameter
description js_getgcparameter re
turns the current parameter of the garbage collection.
... if successful, js_getgcparameter re
turns the current parameter.
JS_GetGlobalObject
this re
turns null if cx has no global object.
...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!
JS_GetInternedStringChars
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.
JS_GetObjectPrototype
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.
JS_GetParent
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.
JS_GetPendingException
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.
JS_GetPositiveInfinityValue
description js_getpositiveinfinityvalue re
turns a js::value that represents an ieee floating-point positive infinity.
... js_getnegativeinfinityvalue re
turns the corresponding negative infinity.
JS_GetPropertyDefault
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.
JS_GetPrototype
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.
JS_GetRegExpFlags
description js_getregexpflags re
turns flags of the specified object, obj.
... if successful, js_getregexpflags re
turns the flags, otherwise re
turns false.
JS_GetRegExpSource
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.
JS_GetStringLength
re
turn the length, in 16-bit code units, of a javascript string.
...this is the same as the length of the array re
turned by js_getstringchars, in char16_ts (not bytes).
JS_GetTypeName
re
turns a pointer to the string literal description of a specified js data type.
... description js_gettypename re
turns a pointer to a string literal description of a specified js data type, type.
JS_HasElement
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.
JS_IdToProtoKey
on success, js_idtoprotokey re
turns a jsprotokey.
... otherwise it re
turns jsproto_null.
JS_IdToValue
on success, js_idtovalue stores the converted value in *vp and re
turns true.
... otherwise it re
turns false.
JS_InternJSString
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.
JS_IsArrayObject
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.
JS_IsBuiltinEvalFunction
this article covers features introduced in spidermonkey 17 re
turn whether the given function is the global eval function.
... description js_isbuiltinevalfunction re
turns whether the given function is the global eval function.
JS_IsBuiltinFunctionConstructor
this article covers features introduced in spidermonkey 17 re
turn whether the given function is the global function constructor.
... description js::iscallable re
turns whether the given function is the global function constructor.
JS_IsIdentifier
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.
JS_IsRunning
if a script is executing, js_isrunning re
turns true.
... otherwise it re
turns false.
JS_LeaveCompartment
leave a the compartment, re
turning to the compartment active before the corresponding js_entercompartment.
... oldcompartment jscompartment * value re
turned by previous call to js_entercompartment.
JS_LeaveCrossCompartmentCall
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.
JS_New
on success, js_new re
turns a pointer to the new object.
... on error, it re
turns null.
JS_NewContext
on success, it re
turns a pointer to the new context.
... otherwise it re
turns null.
JS_NewDependentString
(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.
JS_NewDoubleValue
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.
JS_NewFunction
(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.
JS_NewNumberValue
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.
JS_NewObject
on success, js_newobject re
turns a pointer to the new object.
... otherwise it re
turns null.
JS_NewPlainObject
on success, js_newplainobject re
turns a pointer to the new object.
... otherwise it re
turns nullptr.
JS_NewPropertyIterator
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.
JS_NewStringCopyN
on success, js_newstringcopyn and js_newucstringcopyn re
turn a pointer to the new js string.
... otherwise they re
turn null.
JS_ObjectIsFunction
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_ObjectIsRegExp
if so, js_objectisregexp re
turns true.
... otherwise it re
turns false.
JS_ReportErrorNumber
if errorcallback re
turns null, (???
...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.
JS_ReportPendingException
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.
JS_ResolveStandardClass
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.
JS_SameValue
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 * ...
... description js_samevalue determines whether two values are the same, re
turning true or false accordingly.
JS_SaveExceptionState
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.
...this function re
turns null if the engine was not built with support for exceptions.
JS_SetArrayLength
on success, js_setarraylength re
turns true.
... otherwise it re
turns false.
JS_SetOperationCallback
(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.
...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.
JS_SetParent
on success, js_setparent re
turns js_true.
... otherwise, it reports an error or sets an exception and re
turns js_false.
JS_SetProperty
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.
JS_SetPrototype
on success, js_setprototype re
turns true.
... otherwise it re
turns false.
JS_StringEqualsAscii
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.
JS_StringToVersion
re
turns a jsversion value representing the version string.
...js_stringtoversion may re
turn any of the following values: string enumeration "1.0" jsversion_1_0 obsolete since jsapi 24 "1.1" jsversion_1_1 obsolete since jsapi 24 "1.2" jsversion_1_2 obsolete since jsapi 24 "1.3" jsversion_1_3 obsolete since jsapi 24 "1.4" jsversion_1_4 obsolete since jsapi 24 "ecmav3" jsversion_ecma_3 "1.5" jsversion_1_5 obsolete since jsapi 24 "1.6" jsversion_1_6 "1.7" jsversion_1_7 "1.8" j...
JS_THREADSAFE
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).
...then use js_readstructuredclone on the other side to
turn the serialized data back into javascript objects, strings, and so on.
JS_TypeOfValue
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.
JS_ValueToBoolean
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.
JS_ValueToECMAInt32
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.
JS_ValueToId
on success, js_valuetoid stores the converted value in *idp and re
turns true.
... otherwise it re
turns false.
JS_ValueToInt32
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_ValueToObject
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.
JS_ValueToSource
on success, js_valuetosource re
turns a pointer to a string.
... on error or exception, it re
turns null.
JS_VersionToString
re
turns a string representation of a jsversion value.
...js_versiontostring may re
turn any of the following values: enumeration string jsversion_1_0 "1.0" obsolete since jsapi 24 jsversion_1_1 "1.1" obsolete since jsapi 24 jsversion_1_2 "1.2" obsolete since jsapi 24 jsversion_1_3 "1.3" obsolete since jsapi 24 jsversion_1_4 "1.4" obsolete since jsapi 24 jsversion_ecma_3 "ecmav3" jsversion_1_5 "1.5" obsolete since jsapi 24 jsversion_1_6 "1.6" jsversion_1_7 "1.7" ...
JSAPI reference
they may re
turn new 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.
SpiderMonkey 1.8.5
t js_forgetlocalroot js_getfunctionname js_getoperationlimit js_getscriptobject js_getstringbytes js_getstringchars js_isassigning js_leavelocalrootscope js_leavelocalrootscopewithresult js_newdouble js_newdoublevalue js_newscriptobject js_newstring js_poparguments js_pusharguments js_pushargumentsva js_removeroot js_removerootrt js_sealobject js_setbranchcallback js_setcallre
turnvalue2 js_setcheckobjectaccesscallback js_setobjectprincipalsfinder js_setoperationlimit js_setprincipalstranscoder api changes operation callback js_setoperationcallback was introduced in js 1.8.0, replacing the branch callback, in anticipation of the addition of the tracing jit (tracemonkey).
...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).
SpiderMonkey 38
(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.
Web Replay
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.
... 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.
Using the Places tagging service
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.
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...
...t appendix a - setting up the gecko sdk downloading and setting the sdk building a microsoft visual cpp project creating a new project adding the gecko sdk to the project settings building a windows project a makefile for unix appendix b - resources weblock resources gecko resources xpcom resources general development resources next » copyright (c) 2003 by doug
turner and ian oeschger.
Interfacing with the XPCOM cycle collector
it only traverses objects that re
turn a helper object when qi'ed to nsicyclecollectionparticipant.
...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.
Components.results
usage implementing nsisupports the standard nsisupports is usually implemented in javascript by using components.results to get a failure re
turn value if does not implement the given interface.
...*/ queryinterface: function(id) { if (id.equals(ci.imyinterface)) re
turn this; throw cr.ns_error_no_interface; } }; ...
Components.utils.cloneInto
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.
... re
turns a reference to the cloned object.
Components.utils.createObjectIn
re
turn value a new object in the specified scope.
... example to create a new object in the scope of a specified dom window, you can simply do: function genpropdesc(value) { re
turn { enumerable: true, configurable: true, writable: true, value: value }; } var myobject = components.utils.createobjectin(mywindow); var proplist = { name: genpropdesc("name"), date: genpropdesc("date"), id: genpropdesc("id"), func: genpropdesc(function() { alert("called func!"); }) }; object.defineproperties(myobject, proplist); components.utils.makeobjectpropsnormal(myobject); this sets up the new object in the scope of the object mywindow, then adds properties by calling object.defineproperties(), then normalizes them by calling components.utils.makeobjectpropsnormal().
Components object
id constructor for xpcom nsids interfaces array of interfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to determine if a given result code is a success code lastresult result code of most recent xpconnect call manager the global xpcom component manager results array of known result codes by name re
turncode pending result for current call stack current javascript call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment.
... utils.getglobalforobject re
turns the global object with which a given object is associated (through its prototype chain at birth, for example).
HOWTO
however, when you start your script, it exits immediately, before the network request re
turns.
..."component re
turned failure code: 0x80040111 (ns_error_not_available) [nsixpccomponents_utils.import]" nsresult: "0x80040111 (ns_error_not_available)" location: "js frame :: file.js :: <top_level> :: line 12" data: no] solution 1 var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubscript("chrome://myall/content/file...
Observer Notifications
use only if your observer must be called before asyncopen re
turns.
... sent when the user re
turns from being idle.
nsDirectoryService
this service re
turns the locations of "well known" directories in an os-independent manner.
... */ nsresult gettempdir(nsifile **aresult) { nsresult rv; 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_...
NS_Alloc
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.
...it is equivalent to calling alloc on the nsimemory instance re
turned from ns_getmemorymanager.
NS_Realloc
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.
...it is equivalent to calling realloc on the nsimemory instance re
turned from ns_getmemorymanager.
BeginReading
« xpcom api reference summary the beginreading function re
turns a const pointer to the first element of the string's internal buffer.
... example code // count the number of times a particular character appears in the string pruint32 countchar(const nsacstring& str, char c) { const char* start = str.beginreading(); const char* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } re
turn count; } see also length, endreading ...
EndReading
« xpcom api reference summary the endreading function re
turns a const char_type pointer to the element just beyond the last element of the string's internal buffer.
... const char_type* endreading() const; remarks it is generally illegal to dereference the re
turned pointer, unless it is known that the string's internal buffer is null-terminated.
BeginReading
« xpcom api reference summary the beginreading function re
turns a const pointer to the first element of the string's internal buffer.
... example code // count the number of times a particular character appears in the string pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* start = str.beginreading(); const prunichar* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } re
turn count; } see also length ...
EndReading
« xpcom api reference summary the endreading function re
turns a const char_type pointer to the element just beyond the last element of the string's internal buffer.
... const char_type* endreading() const; remarks it is generally illegal to dereference the re
turned pointer, unless it is known that the string's internal buffer is null-terminated.
Alloc
re
turn values this function is infallible, therefore guaranteed to re
turn a pointer to the newly allocated buffer.
... note: prior to gecko 13.0, this function re
turned nsnull if memory allocation failed.
Clone
re
turn values this function re
turns nsnull if the memory allocation fails.
... otherwise, it re
turns a pointer to the newly allocated buffer.
HeapMinimize
re
turn values this function re
turn ns_ok if successful.
... otherwise, it re
turns an error code.
Realloc
re
turn values this function re
turns nsnull if the memory allocation fails.
... otherwise, it re
turns a pointer to the newly allocated buffer.
amIWebInstallListener
re
turn value true if the caller should start the installs.
... re
turn value true if the caller should start the installs.
amIWebInstaller
re
turn value true if the installation was successfully started.
... re
turn value true if installation is enabled.
imgICache
any images from windows in private browsing mode will not be present in the cache re
turned from a call with a null parameter).
... re
turn value null if the url was not found in the cache.
imgIDecoderObserver
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.
jsdIStackFrame
after you re
turn from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface.
...line result re
turn value ...
mozIAsyncFavicons
getfaviconlinkforicon/page will ignore any associated data if the favicon uri is "chrome:" and just re
turn the same chrome uri.
...getfaviconlinkforicon/page will ignore any associated data if the favicon uri is "chrome:" and just re
turn the same chrome uri.
mozIStoragePendingStatement
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.
mozIStorageResultSet
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.
...re
turn value a mozistoragerow object containing the next row from the result set, or null if there are no more results.
mozIStorageVacuumParticipant
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.
nsIAboutModule
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.
... re
turn value a fully constructed channel that will load the about uri.
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.
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.
GetAccessibleRelated
« nsiaccessible page summary this method re
turns an accessible related to this one by the given relation type.
... re
turn value re
turns an accessible which is related to the one provided by the given relation type.
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.
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.
GetRelation
« nsiaccessible page summary this method re
turns accessible relation for this accessible object by index.
... re
turn value re
turns nsiaccessiblerelation object for this accessible.
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.
nsIAccessibleImage
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.
... getimagesize() re
turns the size of the image accessible.
nsIAccessibleTableChangeEvent
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) attributes attribute type description numrowsorcols long re
turn the number of rows or cols.
... roworcolindex long re
turn the row or column index.
nsIAccessibleTreeCache
efox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview nsiaccessible getcachedtreeitemaccessible(in long arow, in nsitreecolumn acolumn); void invalidatecache(in long arow, in long acount); void treeviewchanged(); void treeviewinvalidated(in long astartrow, in long aendrow, in long astartcol, in long aendcol); methods getcachedtreeitemaccessible() re
turns the tree item from the cache for the cell in the specified row and column; the nsiaccessible is created if it doesn't already exist in the cache.
... re
turn value the nsiaccessible corresponding to the specified tree cell.
nsIAccessibleValue
methods setcurrentvalue() obsolete since gecko 1.9 (firefox 3) re
turn a success condition of the value getting set.
... re
turn value true if the value is within the range of minimumvalue - maximumvalue, false if it is not.
nsIAlertsService
if the text is too long, try to use line re
turns in the text to have it split and displayed over multiple lines.
... textclickable optional if true, if the user clicks on it, the listener is notified; when hovered the notification background becomes lighter and the cursor
turns to a pointer.
nsIApplicationUpdateService
re
turn value a string indicating the status of the update upon re
turn: "downloading" the update is being downloaded.
... re
turn value an nsiupdate object indicating the most appropriate update to install.
nsIAuthPromptCallback
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.
nsIBidiKeyboard
(supported on: win32, mac, gtk2) note: prior to gecko 1.9 this method used a parameter 'out prbool aisrtl' to re
turn the value.
...re
turn value true if the current keyboard is right-to-left, false if it is not.
nsICacheVisitor
re
turn value re
turns true to start visiting all entries for this device, otherwise re
turns false to advance to the next device.
... 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.
nsICachingChannel
this may re
turn an error if cacheasfile is false.
...re
turn value re
turns true if this channel's data is being loaded from the cache, otherwise re
turns false.
nsIChannelEventSink
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.
...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.
nsICharsetResolver
closure the closure re
turned by requestcharset().
... re
turn value the resolved charset, or an empty string if no charset could be determined.
nsICompositionStringSynthesizer
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.
nsIContentSniffer
re
turn value the content type.
... 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 } ...
nsIController
re
turn value re
turn true if the specified command is currently available to be used; otherwise, it should re
turn false.
... re
turn value true if the specified command is supported; otherwise false.
nsICookieConsent
the policy for the given uri and channel is also re
turned.
... re
turn value re
turns nscookiestatus.
nsICookieService
re
turn value re
turns the resulting cookie string.
... re
turn value re
turns the resulting cookie string.
nsIDOMClientRect
the type of box is specified by the method that re
turns such an object.
... it is re
turned by functions like element.getboundingclientrect.
nsIDOMGlobalPropertyInitializer
re
turn value the initialized global property.
... ensure that you never re
turn any internal xpcom objects to untrusted code.
nsIDOMStorageList
nsidomstorage nameditem( in domstring domain ); parameters domain the name of the domain for whom to re
turn the storage object.
... re
turn value the nsidomstorage object representing the data store for the specified domain.see also dom storage structured client-side storage (html 5 specification) nsidomwindow ...
nsIDOMXPathExpression
dom/interfaces/xpath/nsidomxpathexpression.idlscriptable represents a compiled xpath query re
turned from nsidomxpathevaluator.createexpression or document.createexpression inherits from: nsisupports last changed in gecko 1.7 method overview nsisupports evaluate(in nsidomnode contextnode, in unsigned short type, in nsisupports result) methods evaluate() evaluate the xpath expression.
... re
turn value an xpath result.
nsIDOMXULSelectControlElement
selectedindex long selecteditem nsidomxulselectcontrolitemelement value 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 ...
nsIDialogParamBlock
re
turn value the previously set integer, or 0 if no integer has been previously set at that index.
... re
turn value the string at the given index, or the empty string if no string has previously been set at that index.
getFile
the individual platform implementation of nsidirectoryserviceprovider maps the symbolic path location passed to this function and re
turns the appropriate nsifile.
... xpcom file system aliases apersistent [out] this output parameter indicates to the caller whether or not the re
turned location is persistent.
nsIDocumentLoader
re
turn value isbusy() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) boolean isbusy(); parameters none.
... re
turn value stop() void stop(); parameters none.
nsIDragService
[noscript] void firedrageventatsource( in mozilla::eventmessage aeventmessage ); parameters aeventmessage one of the event messages between edragdropeventfirst and edragdropeventlast defined in widget/eventmessagelist.h getcurrentsession() re
turns the current nsidragsession.
... re
turn value the current drag session, or null if no drag is in progress.
nsIErrorService
re
turn value the url of the string bundle registered for that module.
... re
turn value the key to use to retrieve the error string from the nsresult's module's string bundle.
nsIFileURL
the getter re
turns a reference to an immutable object.
... callers must clone before attempting to modify the re
turned nsifile object.
nsIFrameLoaderOwner
methods getframeloader() re
turns the frame loader object owned by this object.
...re
turn value the nsiframeloader owned by this object.
nsIFrameMessageListener
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.
nsIGlobalHistory3
not all histories have them; this need not be supported (just re
turn ns_error_not_implemented.
... re
turn value the gecko flags for the uri.
nsIINIParserFactory
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.
... re
turn value the nsiiniparser object you can use to parse the ini file.
nsIJSCID
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.
nsIJetpack
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.
...re
turn value the new handle.
nsIJetpackService
method overview nsijetpack createjetpack(); methods createjetpack() this method creates a new jetpack process and re
turns an nsijetpack interface that represents it.
...re
turn value an nsijetpack interface representing the remote process.
nsILoadGroup
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).
... requests nsisimpleenumerator re
turns the requests contained directly in this group.
nsIMemoryReporter
once that has been done, the reporter will be found by any client accessing the enumerator re
turned by nsimemoryreportermanager.enumeratereporters().
...the amount re
turned must never decrease over the lifetime of the application.
nsIMessageBroadcaster
getchildat() re
turn a single subordinate message manager.
... re
turns nsimessagelistenermanager: the message manager at the given index.
nsIMicrosummary
re
turn value re
turns true if the microsummaries are equal.
... note: this method re
turns false if either objects don't have a generator removeobserver() remove a microsummary observer from this microsummary.
nsIMicrosummarySet
toolkit/components/places/public/nsimicrosummaryservice.idlscriptable this interface provides access to sets of microsummaries re
turned from the nsimicrosummaryservice.
...re
turn value an enumerator of nsimicrosummary objects.
nsIMsgDatabase
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.
...if there are no such messages, null may be re
turned.
nsIMsgFilterCustomAction
* * @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 actionfolder folder in the filter list * @param filtertype filter type (manual, offlinemail, etc.) * * @re
turn errormessage a localized message to display if invalid * set to null if the actionvalue is valid */ autf8string validateactionvalue(in autf8string actionvalue, in nsimsgfolder actionfolder, in nsmsgfiltertypetype filtertype); /* allow duplicate actions in the same filter list?
nsIMsgIdentity
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.
nsIMsgProtocolInfo
methods getdefaultserverport() re
turns the default port for a connection to a server of this account type.
... re
turn value the default port number for connections of this account type.
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 ajunkscoreorigin); matchbody /** * test if the body of the passed in message matches "this" search term.
nsIMsgThread
getchildat() re
turns the message at an index.
... getroothdr() nsimsgdbhdr getroothdr(out long index); re
turn index changed to the index of the root.
nsINavHistoryFullVisitResultNode
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.
nsINavHistoryResultViewObserver
to provide behavior similar to the folder pane in thunderbird, where drops are only permitted on items themselves instead of on the pane as a whole, always re
turn false when the orientation isn't drop_on.
... re
turn value re
turn true if the drop is permitted or false if it isn't.
nsIObserverService
otherwise an error will be re
turned.
... re
turn value re
turns an enumeration of all registered listeners.
nsIParentalControlsService
re
turn value true if the block was successfully overridden, otherwise false.
... re
turn value true if the block was successfully overridden, otherwise false.
nsIPipe
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.
...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.
nsIPrivateBrowsingService
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.
... you may also
turn private browsing mode on and off by setting the value of this attribute.
nsIProperties
getkeys() re
turns an array of property names.
... re
turn value true if the property exists, false if the property does not exist.
nsIPropertyBag
nsivariant getproperty( in astring name ); parameters name the name to re
turn the matching property.
... re
turn value the property matching the given name.
nsIProtocolProxyCallback
void onproxyavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value re
turned from asyncresolve.
...the value re
turned from asyncresolve.
nsIRequest
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).
... re
turn value true if the request has yet to reach completion.
nsIScriptError
note: nsiconsolemessage.message will re
turn the error formatted with file/line information.
... re
turn value a string representing the error message described by the nsiscripterror object.
nsIScriptableUnescapeHTML
re
turn value an nsidomdocumentfragment of the element with the new text appended.
... re
turn value the result of the plain text conversion.
nsISearchEngine
re
turn value an nsisearchsubmission supportsresponsetype() determines whether the engine can re
turn responses in the given mime type.
... re
turn value re
turns true if the engine spec has a url with the given responsetype, false otherwise.
nsISocketProviderService
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.
... re
turn value nsisocketprovider that handles the specified socket type.
nsIStreamListener
note: your implementation of this method must read exactly acount bytes of data before re
turning.
...you must read all of these bytes before re
turning to the caller.
nsIStringBundleOverride
re
turn value an enumeration of nsipropertyelement objects for the keys that are overridden in the given string bundle.
... re
turn value the override value.
nsISupportsCString
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsChar
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsDouble
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsFloat
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsID
methods tostring() this method re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsInterfacePointer
methods tostring() re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRBool
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRInt16
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRInt32
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRInt64
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRTime
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRUint16
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRUint32
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRUint64
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsPRUint8
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsISupportsString
methods tostring() this methods re
turns a string valued representation of the object.
...re
turn value a string valued representation of the object.
nsITaskbarWindowPreview
methods getbutton() re
turns the specified button from the preview's toolbar.
... re
turn value an nsitaskbarpreviewbutton describing the requested button.
nsIToolkitProfile
note: the unlocker object cannot be re
turned to javascript as the error causes an exception to be thrown.
... re
turn value an nsiprofilelock object which holds a profile lock as long as you hold a reference to it.
nsIUpdate
re
turn value an nsiupdatepatch object describing the specified patch.
... re
turn value the patch object serialized into an nsidomelement.
nsIUpdateManager
methods getupdateat() re
turns the update at the specified index into the history list.
... re
turn value the nsiupdate at the specified index into the history list.
nsIVersionComparator
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 ...
...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 ...
nsIWebBrowser
re
turn value ns_ok listener was successfully added.
... re
turn value ns_ok listener was successfully added.
nsIWebBrowserChrome3
re
turn value a new link target, if appropriate.
... otherwise re
turns originaltarget.
nsIWebBrowserFind
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.
...re
turn value whether an occurrence was found.
nsIWebBrowserPersist
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.
... encode_flags_cr_linebreaks 512 output with carriage re
turn line breaks.
nsIWebSocketChannel
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.
nsIWindowsShellService
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.
nsIXFormsModelElement
orts last changed 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.
nsIXULWindow
re
turn value the newly minted window.
... re
turn value the tree item corresponding to the given id, if any.
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.
... syntax ns_ensure_success(nsresult, re
turn-value); usage nsresult mozmyclass::mozstringmucking() { nsresult rv = ns_cstringcopy(mdeststring, msrcstring); ns_ensure_success(rv, rv); // this is the same as doing: nsresult rv = ns_cstringcopy(mdeststring, msrcstring); if (ns_failed(rv)) re
turn rv; re
turn ns_ok; } ...
NS_CStringAppendData
re
turn values the ns_cstringappenddata function re
turns ns_ok if successful.
... otherwise, it re
turns an error code.
XPCOM string functions
this is a low-level api.ns_cstringclonedatathe ns_cstringclonedata function re
turns a null-terminated, heap allocated copy of the string's internal buffer.ns_cstringcontainerfinishthe ns_cstringcontainerfinish function releases any memory allocated by a nscstringcontainer instance.ns_cstringcontainerinitthe ns_cstringcontainerinit function initializes a nscstringcontainer instance for use as a nsacstring.ns_cstringcontainerinit2the ns_cstringcontainerinit2 function initializes a nscstringc...
...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.
Using nsCOMPtr
you'll have to
turn to the xpcom newsgroup or another experienced nscomptr user, or find the answer by experimentation.
...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.
Working with out parameters
} 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.
wrappedJSObject
// 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.
... the underlying object has a wrappedjsobject property that re
turns a js object.
XPIDL Syntax
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).
pyxpidl
the pyxpidl tool suite has been built to replace the older xpidl tool which, in the past, was used to
turn xpidl files into c++ headers and xpcom typelibs (xpt files).
... xpidl option description pyxpidl equivalent -a emit annotations to typelib n/a (feature removed) -w
turn on warnings n/a (this is now the default and can't be
turned off) -v verbose mode (nyi) n/a (feature removed) -t creates a typelib of a specific version number n/a (feature removed, and probably never actually worked) -i add an entry to start of include path for #include "nsifoo.idl" -i (unchanged) -o specify the base name for output (-o...
Autoconfiguration in 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.
... 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!
Mail composition back end
if message creation fails, the nsimsgsend operation will re
turn an ns_failed() re
turn code.
... 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.
Styling the Folder Pane
servertype-server afolder.server.type re
turns the type of the server.
... 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).
Using C struct and pointers
the call to structtype() re
turns a ctype object, and we then apply the new operator to it to create a specific instance of this newly defined type - a javascript representation of the c struct.
... using c strings with js-ctypes a pointer to char in javascript is declared as follows: var str = ctypes.pointertype(ctypes.char); now imagine you call a c function that re
turns a c string and you want to modify the contents of this string.
ctypes.open
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.
... var lib = ctypes.open(filepath_mylib); var add_with_c = lib.declare("add", ctypes.default_abi, ctypes.int, // re
turn type ctypes.int, // a ctypes.int // b ); var rez = add_with_c(2, 5); // rez is 7 lib.close(); references heather's paragraphs: playing around with js-ctypes on linux - credits for basis of this article github :: diegocr - fx-sapi-test - creating a native file for windows (dll) and use in a simple bootstrap add-on standard os libraries see standard os libraries ...
Scripting plugins - Plugins
a plugin that wishes to be scriptable using this new mechanism needs to re
turn the appropriate npobject (which is created by calling npn_createobject) when the browser requests it by calling: npp_getvalue(npp, nppvpluginscriptablenpobject, ...); accessing browser objects from a plugin a plugin that wishes to access objects in the browser window that loaded the plugin can do this by getting the npobject for the browser's window object, or the dom element that loaded the ...
...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.
Step through code - Firefox Developer Tools
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.
... 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.
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
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|.
...</div> <script> function makefactory(type) { re
turn function factory(content) { var elt = document.createelement(type); elt.textcontent = content; re
turn elt; }; } var divfactory = makefactory('div'); var spanfactory = makefactory('span'); function divsandspans() { for (i = 0; i < 10; i++) { var div = divfactory('div #' + i); div.appendchild(spanfactory('span #' + i)); document.body.appendchild...
DOM allocation example - Firefox Developer Tools
it just contains a script that creates a large number 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 ins...
...tances 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.getelementbyid("container"); for (var i = 0; i < toolbarcount; i++) { var toolbar = createtoolbar(); container.appendchild(toolbar); } } createtoolbars(); a simple pseudocode representation of how this code operates looks like this: createtoolbars() -> createtoolbar() // called 200 times, creates 1 div element each time -> createtoolbarbutton() // called 20 times per toolbar, creates 1 span element each time in total, then, it creates 200 htmldivelement objects, and 4000 htmlspanelement objects.
Examine and edit CSS - Firefox Developer Tools
(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.
...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.
Use the Inspector API - Firefox Developer Tools
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.
Console messages - Firefox Developer Tools
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 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.
AddressErrors.organization - Web APIs
the re
turned string explains the error and should offer suggestions for how to correct 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.
AddressErrors - Web APIs
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.
... 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.
AmbientLightSensor - Web APIs
the ambientlightsensor interface of the the sensor apis re
turns the current light level or illuminance of the ambient light around the hosting device.
... properties ambientlightsensor.illuminance re
turns the current light level in lux of the ambient light level around the hosting device.
AnalyserNode.getByteFrequencyData() - Web APIs
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.
... re
turn value none.
AnalyserNode.getByteTimeDomainData() - Web APIs
syntax const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); const dataarray = new uint8array(analyser.fftsize); // uint8array should 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.
... 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.
AnalyserNode.getFloatTimeDomainData() - Web APIs
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.
... re
turn value none.
Animation.currentTime - Web APIs
the animation.currenttime property of the web animations api re
turns and sets 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, currenttime's re
turn value is null.
Animation.finish() - Web APIs
re
turn value none.
... elem.getanimations().foreach( function(animation){ re
turn animation.finish(); } ); specifications specification status comment web animationsthe definition of 'finish()' in that specification.
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.
... 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.
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.
AnimationEffect - Web APIs
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.
AnimationEvent() - Web APIs
the animationevent() constructor re
turns a newly created animationevent, representing an event in relation with an animation.
... re
turn value a new animationevent, initialized per any provided options.
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.
...if the namespaceuri re
turns the xul namespace and the localname re
turns "browser", then the node is understood to be a xul <browser/>.
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).
... re
turn value a float32array.
AudioContext.close() - Web APIs
the re
turned promise resolves when all audiocontext-creation-blocking resources have been released.
...}); await audioctx.close(); re
turns a promise that resolves with void.
AudioContext.getOutputTimestamp() - Web APIs
the getoutputtimestamp() property of the audiocontext interface re
turns a new audiotimestamp object containing two audio timestamp values relating to the current audio context.
... re
turns an audiotimestamp object, which has the following properties.
AudioProcessingEvent - Web APIs
note the the re
turned audiobuffer is only valid in the scope of the onaudioprocess function.
...note the the re
turned audiobuffer is only valid in the scope of the onaudioprocess function.
AudioScheduledSourceNode.start() - Web APIs
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.
...the times are calculated by adding the desired number of seconds to the context's current time stamp re
turned by audiocontext.currenttime.
AudioTrackList - Web APIs
gettrackbyid() re
turns the audiotrack found within the audiotracklist whose id matches the specified string.
... if no match is found, null is re
turned.
AudioWorkletNode.port - Web APIs
the read-only port property of the audioworkletnode interface re
turns the associated messageport.
... // 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.
AudioWorkletProcessor() - Web APIs
re
turn value the newly constructed audioworkletprocessor instance.
... // 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.
AudioWorkletProcessor.port - Web APIs
the read-only port property of the audioworkletprocessor interface re
turns the associated messageport.
... // 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.
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.
... 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.
AuthenticatorAttestationResponse - Web APIs
the authenticatorattestationresponse interface of the web authentication api is re
turned by credentialscontainer.create() when a publickeycredential is passed, and provides a cryptographic root of trust for the new key pair that has been generated.
... methods authenticatorattestationresponse.gettransports()secure context re
turns an array of strings describing which transport methods (e.g.
BaseAudioContext.createBufferSource() - Web APIs
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.
BaseAudioContext.createWaveShaper() - Web APIs
syntax baseaudioctx.createwaveshaper(); re
turns a waveshapernode.
...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; }; ...
BaseAudioContext.decodeAudioData() - Web APIs
re
turn value void, or a promise object that fulfills with the decodeddata.
... 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 .
BatteryManager.chargingTime - Web APIs
even if the time re
turned is precise to the second, browsers round them to a higher interval (typically to the closest 15 minutes) for privacy reasons.
... syntax var time = battery.chargingtime on re
turn, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully charged, or 0 if the battery is already fully charged.
BatteryManager.dischargingTime - Web APIs
even if the time re
turned is precise to the second, browsers round them to a higher interval (typically to the closest 15 minutes) for privacy reasons.
... syntax var time = battery.dischargingtime on re
turn, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully discharged and the system will suspend.
BatteryManager.level - Web APIs
syntax var level = battery.level on re
turn, level is a number representing the system's battery charge level scaled to a value between 0.0 and 1.0.
...a value of 1.0 is also re
turned if the implementation isn't able to determine the battery charge level or if the system is not battery-powered.
Beacon API - Web APIs
if the browser successfully queues the request for delivery, the method re
turns "true" and re
turns "false" otherwise.
...if the browser successfully queues the request for delivery, the method re
turns "true" and otherwise re
turns "false".
Blob() - Web APIs
the blob() constructor re
turns a new blob object.
... re
turn value a new blob object containing the specified data.
Bluetooth.getDevices() - Web APIs
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.
... re
turn value a promise that resolves with an array of bluetoothdevices.
adData - Web APIs
the bluetoothdevice.addata read-only property re
turns instance of bluetoothadvertisingdata containing the most recent advertising data received for the device.
... syntax var instanceofbluetoothaddata = instanceofbluetoothdevice.addata re
turns an instance of bluetoothadvertisingdata.
connectGATT() - Web APIs
the bluetoothdevice.connectgatt() method re
turns a promise that resolves to an instance of bluetoothgattremoteserver.
...}) re
turns a promise that resolves to an instance of bluetoothgattremoteserver.
deviceClass - Web APIs
the bluetoothdevice.deviceclass read-only property re
turns a number representing the bluetooth devices "class of device".
... syntax var deviceclass = instanceofbluetoothdevice.deviceclass re
turns a number.
BluetoothDevice.gatt - Web APIs
the bluetoothdevice.gatt read-only property re
turns a reference to the device's bluetoothremotegattserver.
... syntax var gattserver = instanceofbluetoothdevice.gatt re
turns a reference to the device's bluetoothremotegattserver.
gattServer - Web APIs
the bluetoothdevice.gattserver read-only property re
turns a reference to the device's gatt server or null if the device is disconnected.
... syntax var gattserver = instanceofbluetoothdevice.gattserver re
turns a reference to the device's gatt server or null if the device is disconnected.
id - Web APIs
the bluetoothdevice.id read-only property re
turns a domstring that uniquely identifies a device.
... syntax var id = instanceofbluetoothdevice.id re
turns a domstring.
BluetoothDevice.name - Web APIs
the bluetoothdevice.name read-only property re
turns a domstring that provides a human-readable name for the device.
... syntax var name = instanceofbluetoothdevice.name re
turns a domstring.
BluetoothDevice.paired - Web APIs
the bluetoothdevice.paired read-only property re
turns a boolean value indicating whether the device is paired with the system.
... syntax var paired = instanceofbluetoothdevice.paired re
turns a boolean.
productID - Web APIs
the bluetoothdevice.productid read-only property re
turns the 16-bit product id field in the pnp_id characteristic in the device_information service.
... syntax var productid = instanceofbluetoothdevice.productid re
turns the 16-bit product id field.
productVersion - Web APIs
the bluetoothdevice.productversion read-only property re
turns the 16-bit product version field in the pnp_id characteristic in the device_information service.
... syntax var productversion = instanceofbluetoothdevice.productversion re
turns the 16-bit product version field.
vendorID - Web APIs
the bluetoothdevice.vendorid read-only property re
turns the 16-bit vendor id field in the pnp_id characteristic in the device_information service.
... syntax var vendorid = instanceofbluetoothdevice.vendorid re
turns the the 16-bit vendor id field.
vendorIDSource - Web APIs
the bluetoothdevice.vendoridsource read-only property re
turns the vendor id source field in the pnp_id characteristic in the device_information service.
... syntax var vendoridsource = instanceofbluetoothdevice.vendoridsource re
turns the vendor id source field.
BluetoothRemoteGATTCharacteristic.getDescriptors() - Web APIs
the bluetoothremotegattcharacteristic.getdescriptors() method re
turns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid.
...}) re
turns a promise that resolves to an array of bluetoothgattdescriptor objects.
BluetoothRemoteGATTCharacteristic.properties - Web APIs
the bluetoothremotegattcharacteristic.properties read-only property re
turns a bluetoothcharacteristicproperties instance containing the properties of this characteristic.
... syntax var properties = bluetoothremotegattcharacteristic.properties re
turns the properties of this characteristic.
BluetoothRemoteGATTCharacteristic.readValue() - Web APIs
the bluetoothremotegattcharacteristic.readvalue() method re
turns a promise that resolves to a dataview holding a duplicate of the value property if it is available and supported.
...}) re
turns a promise that resolves to an dataview.
BluetoothRemoteGATTCharacteristic.service - Web APIs
the bluetoothremotegattcharacteristic.service read-only property re
turns the bluetoothgattservice this characteristic belongs to.
... syntax var bluetoothremotegattserviceinstance = bluetoothremotegattcharacteristic.service re
turns an instance bluetoothgattservice.
BluetoothRemoteGATTCharacteristic.uuid - Web APIs
the bluetoothremotegattcharacteristic.uuid read-only property re
turns domstring containing the uuid of the characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
... syntax var uuid = bluetoothremotegattcharacteristic.uuid re
turns a domstring.
BluetoothRemoteGATTCharacteristic.value - Web APIs
the bluetoothremotegattcharacteristic.value read-only property re
turns currently cached characteristic value.
... syntax var value = bluetoothremotegattcharacteristic.value re
turns the currently cached characteristic value.
characteristic - Web APIs
the bluetoothremotegattdescriptor.characteristic read-only property re
turns the bluetoothremotegattcharacteristic this descriptor belongs to.
... syntax var characteristic = bluetoothremotegattcharacteristic.characteristic re
turns an instance of bluetoothremotegattcharacteristic.
readValue() - Web APIs
the bluetoothremotegattdescriptor.readvalue() method re
turns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported.
...}) re
turns a promise that resolves to an arraybuffer.
uuid - Web APIs
the bluetoothremotegattdescriptor.uuid read-only property re
turns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor.
... syntax var uuid = bluetoothremotegattdescriptor.uuid re
turns a uuid.
value - Web APIs
the bluetoothremotegattdescriptor.value read-only property re
turns an arraybuffer containing the currently cached descriptor value.
... syntax var characteristic = bluetoothremotegattdescriptor.characteristic re
turns an arraybuffer.
writeValue() - Web APIs
the bluetoothremotegattdescriptor.writevalue() method sets the value property to the bytes contained in an arraybuffer and re
turns a promise.
... re
turns a promise.
BluetoothRemoteGATTServer.getPrimaryService() - Web APIs
the bluetoothremotegattserver.getprimaryservice() method re
turns a promise to the primary bluetoothgattservice offered by the bluetooth device for a specified bluetoothserviceuuid.
...}) re
turns a promise that resolves to a bluetoothgattservice object.
BluetoothRemoteGATTServer.getPrimaryServices() - Web APIs
the bluetoothremotegattserver.getprimaryservices() method re
turns a promise to a list of primary bluetoothgattservice objects offered by the bluetooth device for a specified bluetoothserviceuuid.
...}) re
turns a promise that resolves to a list of bluetoothgattservice objects.
device - Web APIs
the bluetoothgattservice.device read-only property re
turns information about a bluetooth device through an instance of bluetoothdevice.
... syntax var bluetoothdeviceinstance = bluetoothgattservice.device re
turns an instance of bluetoothdevice.
getCharacteristic() - Web APIs
the bluetoothgattservice.getcharacteristic() method re
turns a promise to an instance of bluetoothgattcharacteristic for a given universally unique identifier (uuid).
...} ) re
turns a promise to an instance of bluetoothgattcharacteristic parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
getCharacteristics() - Web APIs
the bluetoothgattservice.getcharacteristics() method re
turns a promise to a list of bluetoothgattcharacteristic instances for a given universally unique identifier (uuid).
...} ) re
turns a promise to an array of bluetoothgattcharacteristic instances.
getIncludedService() - Web APIs
the bluetoothgattservice.getincludedservice() method re
turns a promise to an instance of bluetoothgattservice for a given universally unique identifier (uuid).
...} ) re
turns a promise to an instance of bluetoothgattservice.
getIncludedServices() - Web APIs
the bluetoothgattservice.getincludedservices() method re
turns a promise to an array of bluetoothgattservice instances for an optional universally unique identifier (uuid).
...} ) re
turns a promise to an instance of bluetoothgattservice.
isPrimary - Web APIs
the bluetoothgattservice.isprimary read-only property re
turns a boolean that indicates whether this is a primary service.
... syntax var isprimary = bluetoothgattservice.isprimary re
turns a boolean.
uuid - Web APIs
the bluetoothgattservice.uuid read-only property re
turns a domstring representing the uuid of this service.
... syntax var uuid = bluetoothgattservice.uuid re
turns a domstring.
Body.blob() - Web APIs
it re
turns a promise that resolves with a blob.
... re
turn value a promise that resolves with a blob.
Body.body - Web APIs
const image = document.getelementbyid('target'); // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); 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(v...
...alue); 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 specification status comment fetchthe definition of 'body' in that specification.
Body.bodyUsed - Web APIs
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 = 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.
Body.formData() - Web APIs
it re
turns a promise that resolves with a formdata object.
... re
turn value a promise that resolves with a formdata object.
Body.json() - Web APIs
it re
turns a promise that resolves with the result of parsing the body text as json.
... re
turn value a promise that resolves to a javascript object.
BudgetService.getBudget() - Web APIs
the getbudget() property of the budgetservice interface re
turns a promise that resolves to an array of budgetstate objects indicating the expected state of the budget at times in the future.
... re
turns a promise that resolves to an instance of budgetstate.
BudgetService.getCost() - Web APIs
the getcost() property of the budgetservice interface re
turns a promise that resolves to a double indicating the worst-case background operation cost of the provided background operation.
... re
turns a promise that resolves to a number.
BudgetService.reserve() - Web APIs
the reserve() property of the budgetservice interface re
turns a promise that resolves to a boolean indicating whether the requested budget operation can be reserved.
...}); parameters operation desc re
turns a promise that resolves to a boolean.
BudgetState - Web APIs
properties budgetstate.budgetat re
turns the anticipated processing budget at a specific time.
... budgetstate.time re
turns a timestamp at which the budgetat value is valid.
ByteLengthQueuingStrategy.size() - Web APIs
the size() method of the bytelengthqueuingstrategy interface re
turns the given chunk’s bytelength property.
... re
turn value an integer representing the byte length of the given chunk.
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.
...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...
CSS.supports() - Web APIs
the css.supports() method re
turns a boolean value indicating if the browser supports a given css feature, or not.
... re
turn value true if the browser supports the rule, otherwise false.
CSS - Web APIs
css.supports() re
turns a boolean indicating if the pair property-value, or the condition, given in parameter is supported.
... 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.
CSSKeywordValue - Web APIs
the interface instance name is a stringifier meaning that when used anywhere a string is expected it will re
turn the value of csskeyword.value.
... properties csskeywordvalue.value re
turns or sets the value of the csskeywordvalue.
CSSMathSum - Web APIs
a cssmathsum is the object type re
turned when the stylepropertymapreadonly.get() method is used on a css property whosevalue is created with a calc() function.
... properties cssmathsum.values re
turns a cssnumericarray object which contains one or more cssnumericvalue objects.
CSSMathValue.operator - Web APIs
for example, if the current cssmathvalue subtype is cssmathsum, this property will re
turn the string "sum".
...console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').values ); // cssnumericarray {0: cssunitvalue, 1: cssmathnegate, length: 2} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values[1].operator ) // 'negate' the cssmathvalue.operator re
turns sum for the equation and negate for the operator on the second value.
CSSNamespaceRule.namespaceURI - Web APIs
the cssnamespacerule.namespaceuri read-only property re
turns a domstring containing the text of the uri of the given namespace.
... syntax var namespaceuri = cssnamespacerule.namespaceuri re
turns a domstring containing a uri.
CSSNumericValue.max() - Web APIs
the max() method of the cssnumericvalue interface re
turns the highest value from among the values passed.
... re
turn value a cssunitvalue.
CSSNumericValue.min() - Web APIs
the min() method of the cssnumericvalue interface re
turns the lowest value from among those values passed.
... re
turn value a cssunitvalue.
CSSNumericValue.parse() - Web APIs
re
turn value a cssnumericvalue.
... exceptions syntaxerror tbd examples the following re
turns a cssunitvalue object with a unit property equal to "px" and a value property equal to 42.
CSSPrimitiveValue.getFloatValue() - Web APIs
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.
... re
turn value a float value in the specified unit.
CSSPrimitiveValue.getRGBColorValue() - Web APIs
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.
CSSPrimitiveValue.setFloatValue() - Web APIs
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.
... re
turn value void.
CSSPseudoElement - Web APIs
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.
CSSRule - Web APIs
cssrule.parentrule read only re
turns the containing rule, otherwise null.
... 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.
CSSStyleDeclaration.setProperty() - Web APIs
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.
... 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...
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.
... re
turn value an array of cssstylevalue objects, each containing one of the supplied values.
CSSStyleValue - Web APIs
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.
CSSUnitValue - Web APIs
properties cssunitvalue.value re
turns a double indicating the number of units.
... cssunitvalue.unit re
turns a usvstring indicating the type of unit.
CSSUnparsedValue.keys() - Web APIs
the cssunparsedvalue.keys() method re
turns a new array iterator object that contains the keys for each index in the array.
... re
turn value a new array.
CSSUnparsedValue.values() - Web APIs
the cssunparsedvalue.values() method re
turns a new array iterator object that contains the values for each index in the cssunparsedvalue object.
... re
turn value a new array.
CSSValueList.item() - Web APIs
if the index is greater than or equal to the number of values in the list, this method re
turns null.
... re
turn value a cssvalue object at the index position in the cssvaluelist, or null if that is not a valid index.
CSSVariableReferenceValue - Web APIs
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.
Using dynamic styling information - Web APIs
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).
...--> <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.
CSS Painting API - Web APIs
paintsize re
turns the read-only values of the output bitmap's width and height.
... we create our paintworklet called 'hollowhighlights' using the registerpaint() function: registerpaint('hollowhighlights', class { static get inputproperties() { re
turn ['--boxcolor']; } static get inputarguments() { re
turn ['*','<length>']; } static get contextoptions() { re
turn {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; const thecolor = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strok...
Cache.delete() - Web APIs
the delete() method of the cache interface finds the cache entry whose key is the request, and if found, deletes the cache entry and re
turns a promise that resolves to true.
... re
turn value a promise that resolves to true if the cache entry is deleted, or false otherwise.
Cache.matchAll() - Web APIs
the matchall() method of the cache interface re
turns a promise that resolves to an array of all matching responses in the cache object.
... re
turn value a promise that resolves to an array of all matching responses in the cache object.
CanvasRenderingContext2D.getTransform() - Web APIs
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.
CanvasRenderingContext2D.measureText() - Web APIs
the canvasrenderingcontext2d.measuretext() method re
turns a textmetrics object that contains information about the measured text (such as its width, for example).
... re
turn value a textmetrics object.
Manipulating video using canvas - Web APIs
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.
...idth, this.height); let frame = this.ctx1.getimagedata(0, 0, this.width, this.height); let l = frame.data.length / 4; for (let i = 0; i < l; i++) { let r = frame.data[i * 4 + 0]; let g = frame.data[i * 4 + 1]; let b = frame.data[i * 4 + 2]; if (g > 100 && r > 100 && b < 43) frame.data[i * 4 + 3] = 0; } this.ctx2.putimagedata(frame, 0, 0); re
turn; } when this routine is called, the video element is displaying the most recent frame of video data, which looks like this: in line 2, that frame of video is copied into the graphics context ctx1 of the first canvas, specifying as the height and width the values we previously saved to draw the frame at half size.
Compositing and clipping - Web APIs
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.
CaretPosition - Web APIs
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.
Client.url - Web APIs
the url read-only property of the client interface re
turns the url of the current service worker client.
...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('/'); })); }); specifications specification status comment service workersthe definition of 'url' in that specification.
CompositionEvent - Web APIs
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).
console.count() - Web APIs
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 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.
Console.countReset() - Web APIs
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 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.
ConstantSourceNode.offset - Web APIs
the read-only offset property of the constantsourcenode interface re
turns a audioparam object indicating the numeric a-rate value which is always re
turned by the source when asked for the next sample.
...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.
ContentIndex.add() - Web APIs
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.
...lat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { re
turn; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope.
ContentIndex.delete() - Web APIs
re
turn value re
turns a promise that resolves with undefined exceptions no exceptions are thrown.
... 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.
ContentIndexEvent() - Web APIs
re
turn value a contentindexevent object configured using the given inputs.
... 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.
CountQueuingStrategy.size() - Web APIs
the size() method of the countqueuingstrategy interface always re
turns 1, so that the total queue size is a count of the number of chunks in the queue.
... re
turn value 1.
Credential - Web APIs
properties credential.id read only re
turns a domstring containing the credential's identifier.
... credential.type read only re
turns a domstring containing the credential's type.
CredentialsContainer.create() - Web APIs
the create() method of the credentialscontainer interface 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.
... re
turns a promise that resolves with a credential instance, such as passwordcredential, federatedcredential, or publickeycredential.
CredentialsContainer.preventSilentAccess() - Web APIs
the preventsilentaccess() method of the credentialscontainer interface sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then re
turns an empty promise.
... re
turns an empty promise.
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.
... re
turns a promise, resolving to the passed credential instance.
CustomElementRegistry.define() - Web APIs
re
turn value void.
... // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent re
turn text.split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element conte...
CustomElementRegistry.whenDefined() - Web APIs
the whendefined() method of the customelementregistry interface re
turns a promise that resolves when the named element is defined.
... re
turn value a promise that resolves to undefined when the custom element is defined.
DOMError - Web APIs
properties domerror.name read only re
turns a domstring representing one of the error type names (see below).
... domerror.message read only re
turns a domstring representing a message or description associated with the given error type name.
DOMPoint.fromPoint() - Web APIs
the static dompoint method frompoint() creates and re
turns a new mutable dompoint object given a source point.
... re
turn value a new dompoint object whose coordinate and perspective values are identical to those in the source point.
DOMPointReadOnly() - Web APIs
the dompointreadonly() constructor re
turns a new dompointreadonly object representing a point in 2d or 3d space, optionally with perspective, whose values cannot be altered by script code.
... re
turn value a new dompointreadonly object representing the specified location in space.
DOMPointReadOnly.fromPoint() - Web APIs
the static dompointreadonly method frompoint() creates and re
turns a new dompointreadonly object given a source point.
... re
turn value a new dompointreadonly object (which is identical to the source point).
DOMPointReadOnly.toJSON() - Web APIs
the dompointreadonly method tojson() re
turns a dompointinit object giving the json form of the point object.
... re
turn value a new dompointinit object whose properties are set to the values in the dompoint or dompointreadonly on which the method was called.
DOMTokenList.contains() - Web APIs
the contains() method of the domtokenlist interface re
turns a boolean — true if the underlying list contains the given token, otherwise false.
... re
turn value a boolean, which is true if the calling list contains token, otherwise false.
DOMTokenList.entries() - Web APIs
the domtokenlist.entries() method re
turns an iterator allowing you to go through all key/value pairs contained in this object.
... syntax tokenlist.entries(); re
turn value re
turns an iterator.
DOMTokenList.keys() - Web APIs
the keys() method of the domtokenlist interface re
turns an iterator allowing to go through all keys contained in this object.
... re
turn value re
turns an iterator.
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.
... re
turns a boolean indicating whether the token was found.
DOMTokenList.values() - Web APIs
the values() method of the domtokenlist interface re
turns an iterator allowing developers to go through all values contained in the domtokenlist.
... re
turn value re
turns an iterator.
DOMUserData - Web APIs
it is re
turned or used as an argument by node.setuserdata(), node.getuserdata(), used as the third argument to handle() on userdatahandler, and is used or re
turned by various domconfiguration methods.
... note that although it can be an object, in mozilla, it may be re
turned as a string or other type, if it was set as such a type (e.g., node.setuserdata() and node.getuserdata()).
DataTransfer.mozCursor - Web APIs
the datatransfer.mozcursor property re
turns or sets the drag cursor's state.
... syntax datatransfer.mozcursor; re
turn value a domstring representing one of the values listed above.
DataTransfer.mozItemCount - Web APIs
the datatransfer.mozitemcount property re
turns the number of items being dragged.
... syntax datatransfer.mozitemcount; re
turn value a number representing the number of items being dragged.
DataTransfer.mozUserCancelled - Web APIs
if the user canceled the event, the property re
turns true and re
turns false otherwise.
... syntax datatransfer.mozusercancelled; re
turn value a boolean representing true if the user canceled the drag event and re
turns false otherwise.
DataTransfer.types - Web APIs
the datatransfer.types read-only property re
turns an array of the drag data formats (as strings) that were set in the dragstart event.
... syntax datatransfer.types; re
turn value an array of the data formats used in the drag operation.
DataTransfer - Web APIs
constructor datatransfer() creates and re
turns a new datatransfer object.
...if the index is not in the range from 0 to the number of items minus one, an empty string list is re
turned.
DataTransferItem.getAsString() - Web APIs
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.
DataTransferItem.kind - Web APIs
the read-only datatransferitem.kind property re
turns a datatransferitem representing the drag data item kind: some text or some file.
... syntax var itemkind = datatransferitem.kind; re
turn value a domstring representing the drag data item's kind.
DataTransferItem.type - Web APIs
the read-only datatransferitem.type property re
turns the type (format) of the datatransferitem object representing the drag data item.
... syntax dataitem.type; re
turn value a domstring representing the drag data item's type.
DataTransferItem - Web APIs
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.webkitgetasentry() re
turns an object based on filesystementry representing the selected file's entry in its file system.
DataTransferItemList - Web APIs
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.datatransferitem() getter that re
turns a datatransferitem at the given index.
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.
... 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.
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).
...if the date is not known, this property will re
turn null.
DeviceMotionEvent.rotationRate - Web APIs
re
turns the rate at which the device is rotating around each of its axes in degrees per second.
... note: if the hardware isn't capable of providing this information, this property re
turns null.
DisplayMediaStreamConstraints - Web APIs
the displaymediastreamconstraints dictionary is used to specify whether or not to include video and/or audio tracks in the mediastream to be re
turned by getdisplaymedia(), as well as what type of processing must be applied to the tracks.
... properties audio a boolean or mediatrackconstraints value; if a boolean, this value simply indicates whether or not to include an audio track in the mediastream re
turned by getdisplaymedia().
Document.all - Web APIs
the document interface's read-only all property re
turns an htmlallcollection rooted at the document node.
... in other words, it re
turns all of the document's elements, accessible by order (like an array) and by id (like a regular object).
Document.anchors - Web APIs
the anchors read-only property of the document interface re
turns a list of all of the anchors in the document.
...d> <body onload="init()"> <h1>title</h1> <h2><a name="contents">contents</a></h2> <ul id="toc"></ul> <h2><a name="plants">plants</a></h2> <ol> <li>apples</li> <li>oranges</li> <li>pears</li> </ol> <h2><a name="veggies">veggies</a></h2> <ol> <li>carrots</li> <li>celery</li> <li>beats</li> </ol> </body> </html> view on jsfiddle notes for reasons of backwards compatibility, the re
turned set of anchors only contains those anchors created with the name attribute, not those created with the id attribute.
Document.applets - Web APIs
the applets property of the document interface re
turns a list of the applets within a document.
...since then, calling document.applets in those browsers always re
turns an empty htmlcollection.
Document.caretRangeFromPoint() - Web APIs
the caretrangefrompoint() method of the document interface re
turns a range object for the document fragment under the specified coordinates.
... re
turns one of the following: a range.
Document.characterSet - Web APIs
the document.characterset read-only property re
turns the character encoding of the document that it's currently rendered with.
...despite the name of this property, it re
turns the encoding.
Document.createProcessingInstruction() - Web APIs
createprocessinginstruction() generates a new processing instruction node and re
turns it.
... 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.createTouch() - Web APIs
the document.createtouch() method creates and re
turns a new touch object.
... re
turn value touch a touch object configured as described by the input parameters.
Document.createTouchList() - Web APIs
the document.createtouchlist() method creates and re
turns a new touchlist object.
... re
turn value list a touchlist object containing the touch objects specified by the touches parameter.
Document.fonts - Web APIs
the fonts property of the document interface re
turns the fontfaceset interface of the document.
... syntax let fontfaceset = document.fonts; value the re
turned value is the fontfaceset interface of the document.
Document.forms - Web APIs
the forms read-only property of the document interface re
turns an htmlcollection listing all the <form> elements contained in the document.
... if the document has no forms, the re
turned collection is empty, with a length of zero.
Document.getAnimations() - Web APIs
the getanimations() method of the document interface re
turns an array of all animation objects currently in effect whose target elements are descendants of the document.
... re
turn value an array of animation objects, each representing one animation currently associated with elements which are descendants of the document on which it's called.
Document.hasFocus() - Web APIs
the hasfocus() method of the document interface re
turns a boolean value indicating whether the document or any element inside the document has 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.
Document.hasStorageAccess() - Web APIs
the hasstorageaccess() method of the document interface re
turns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage.
... re
turn value a promise that resolves with a boolean value indicating whether the document has access to its first-party storage.
Document.images - Web APIs
the images read-only property of the document interface re
turns a collection of the images in the current html document.
... usage notes you can use either javascript array notation or the item() method on the re
turned collection to access the items in the collection.
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.
... if the current document is not in a browsing context, the re
turned value is null.
Document.origin - Web APIs
the document.origin read-only property re
turns the document's origin.
... syntax var origin = document.origin; examples var origin = document.origin; // on this page, re
turns:'https://developer.mozilla.org' var origin = document.origin; // on "about:blank", re
turns:'null' var origin = document.origin; // on "data:text/html,<b>foo</b>", re
turns:'null' ...
Document.queryCommandSupported() - Web APIs
re
turn value re
turns a boolean which is true if the command is supported and false if the command isn't.
... notes 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 [1] example var flg = document.querycommandsupported("selectall"); if(flg) { // ...do something } specifications specification status comment execcommand ...
Document.referrer - Web APIs
the document.referrer property re
turns the uri of the page that linked to this page.
...because this property re
turns only a string, it doesn't give you document object model (dom) access to the referring page.
Document.rootElement - Web APIs
document.rootelement re
turns the element that is the root element of the document if it is an <svg> element, otherwise null.
... it is deprecated in favor of document.documentelement, which re
turns the root element for all documents.
Document.scripts - Web APIs
the scripts property of the document interface re
turns a list of the <script> elements in the document.
... the re
turned object is an htmlcollection.
Document.scrollingElement - Web APIs
the scrollingelement read-only property of the document interface re
turns a reference to the element that scrolls the document.
... 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.
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.
Document.title - Web APIs
the assignment affects the re
turn value of document.title, the title displayed for the document (e.g.
... 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.
Document.xmlVersion - Web APIs
re
turns the version number as specified in the xml declaration (e.g., <?xml version="1.0"?>) or "1.0" if the declaration is absent.
... this attribute was never really useful, since it always re
turned 1.0, and has been removed in dom level 4.
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.
... 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.
DocumentOrShadowRoot.activeElement - Web APIs
the activeelement read-only property of the document and shadowroot interfaces re
turns the element within the dom or shadow dom tree that currently has focus.
... often activeelement will re
turn a htmlinputelement or htmltextareaelement object if it has the text selection at the time.
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
the caretpositionfrompoint() property of the documentorshadowroot interface re
turns a caretposition object, containing the dom node, along with the caret and caret's character offset within that node.
... re
turns a caretposition object.
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).
... re
turn value an array of element objects.
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.
... 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.
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).
... re
turns an array of node objects.
DocumentOrShadowRoot.styleSheets - Web APIs
the stylesheets read-only property of the documentorshadowroot interface re
turns a stylesheetlist of cssstylesheet objects, for stylesheets explicitly linked into or embedded in a document.
... examples function getstylesheet(unique_title) { for (var i=0; i<document.stylesheets.length; i++) { var sheet = document.stylesheets[i]; if (sheet.title == unique_title) { re
turn sheet; } } } notes the re
turned list is ordered as follows: stylesheets retrieved from <link> headers are placed first, sorted in header order.
Events and the DOM - Web APIs
the re
turn value is treated in a special way, described in the html specification.
...the re
turn value is treated in a special way, described in the html specification.
Examples of web and XML development using the DOM - Web APIs
angetext() { var p = document.getelementbyid("pid"); p.style.color = "blue" p.style.fontsize = "18pt" } </script> </head> <body> <p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">linker</p> <form> <p><input value="rec" type="button" onclick="changetext();" /></p> </form> </body> </html> example 4: using stylesheets the stylesheets property on the document object re
turns a list of the stylesheets that have been loaded on that document.
... 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.
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
the ext_disjoint_timer_query.isqueryext() method of the webgl api re
turns true if the passed object is a webglquery object.
... re
turn value a glboolean indicating whether the given object is a webglquery object (true) or not (false).
EffectTiming.delay - Web APIs
the value of delay corresponds directly to effecttiming.delay in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
... examples in the pool of tears example, each tear is passed a random delay via its timing object: // randomizer function var getrandommsrange = function(min, max) { re
turn math.random() * (max - min) + min; } // loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" }); }); s...
EffectTiming.duration - Web APIs
the value of duration corresponds directly to animationeffecttimingreadonly.duration in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
... examples in the pool of tears example, each tear is passed a random duration via its timing object: // randomizer function var getrandommsrange = function(min, max) { re
turn math.random() * (max - min) + min; } // loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" }); }); ...
Element.getElementsByTagNameNS() - Web APIs
the element.getelementsbytagnamens() method re
turns a live htmlcollection of elements with the given tag name belonging to the given namespace.
... living standard changed the re
turn value from nodelist to htmlcollection.
Element.matches() - Web APIs
re
turn value result is a boolean.
...tchesselector || element.prototype.mozmatchesselector || element.prototype.msmatchesselector || element.prototype.omatchesselector || element.prototype.webkitmatchesselector || function(s) { var matches = (this.document || this.ownerdocument).queryselectorall(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} re
turn i > -1; }; } however, given the practicality of supporting older browsers, the following should suffice for most (if not all) practical cases (i.e.
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.
...if the namespaceuri re
turns the xul namespace and the localname re
turns "browser", then the node is understood to be a xul <browser/>.
Element.outerHTML - Web APIs
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.
...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
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.
...<input type="submit" id="nextstep" value="next" /> </p> </form> css #notice { display: inline-block; margin-bottom: 12px; border-radius: 5px; width: 600px; padding: 5px; border: 2px #7fdf55 solid; } #rules { width: 600px; height: 130px; padding: 5px; border: #2a9f00 solid 2px; border-radius: 5px; } javascript function checkreading () { if (checkreading.read) { re
turn; } checkreading.read = this.scrollheight - this.scrolltop === this.clientheight; document.registration.accept.disabled = document.getelementbyid("nextstep").disabled = !checkreading.read; checkreading.noticebox.innerhtml = checkreading.read ?
Element.setAttributeNode() - Web APIs
replacedattr is the replaced attribute node, if any, re
turned by this function.
... 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.
Element.setAttributeNodeNS() - Web APIs
syntax replacedattr = element.setattributenodens(attributenode) replacedattr is the replaced attribute node, if any, re
turned by this function.
...lns:myns="http://www.mozilla.org/ns/specialspace" // myns:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.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.
Element.toggleAttribute() - Web APIs
re
turn value true if attribute name is eventually present, and false otherwise.
...ens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removeattribute (dom 1) removeattributens removeattributenode - polyfill if (!element.prototype.toggleattribute) { element.prototype.toggleattribute = function(name, force) { if(force !== void 0) force = !!force if (this.hasattribute(name)) { if (force) re
turn true; this.removeattribute(name); re
turn false; } if (force === false) re
turn false; this.setattribute(name, ""); re
turn true; }; } specification specification status comment domthe definition of 'element.toggleattribute' in that specification.
ElementCSSInlineStyle.style - Web APIs
when getting, it re
turns a cssstyledeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute.
... setting styles styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute re
turns a cssstyledeclaration object which is also read-only.
Event.msConvertURL() - Web APIs
re
turn value this method does not re
turn a value.
... 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.
EventTarget() - Web APIs
re
turn value an instance of the eventtarget object.
... examples class myeventtarget extends eventtarget { constructor(mysecret) { super(); this._secret = mysecret; } get secret() { re
turn this._secret; } }; let myeventtarget = new myeventtarget(5); let value = myeventtarget.secret; // == 5 myeventtarget.addeventlistener("foo", function(e) { this._secret = e.detail; }); let event = new customevent("foo", { detail: 7 }); myeventtarget.dispatchevent(event); let newvalue = myeventtarget.secret; // == 7 specifications specification status comment domthe definition of 'eventtarget() constructor' in that specification.
EventTarget.removeEventListener() - Web APIs
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.
... now look at each of these calls to removeeventlistener() in
turn.
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++) { ...
... stack[i].call(this, event); } re
turn !event.defaultprevented; }; specifications specification status comment domthe definition of 'eventtarget' in that specification.
ExtendableEvent.waitUntil() - Web APIs
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.
FeaturePolicy.allowsFeature() - Web APIs
it re
turns a boolean that is true if and only if the specified feature is allowed in the specified context (or the default context if no context is specified).
... re
turn value a boolean that is true if and only if the feature is allowed.
FeaturePolicy.features() - Web APIs
the features() method of the featurepolicy interface re
turns a list of names of all features supported by the user agent.
... re
turn value a list of strings that represent names of all feature policy directives supported by the user agent.
FederatedCredential - Web APIs
federatedcredential.provider read only re
turns a usvstring containing a credential's federated identity provider.
... federatedcredential.protocol read only re
turns a domstring containing a credential's federated identity protocol.
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.
... example self.addeventlistener('fetch', function(event) { event.respondwith( if (event.isreload) { //re
turn something } else { //re
turn something else }; ); ​}); ...
Fetch API - Web APIs
it re
turns a promise that resolves to the response to that request, whether it is successful or not.
... 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.
Using files from web applications - Web APIs
actly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy: let dropbox; dropbox = document.getelementbyid("dropbox"); dropbox.addeventlistener("dragenter", dragenter, false); dropbox.addeventlistener("dragover", dragover, false); dropbox.addeventlistener("drop", drop, false); in this example, we're
turning the element with the id dropbox into our drop zone.
... 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/").
File.getAsText() - Web APIs
syntax var str = instanceoffile.getastext(encoding); parameters encoding a string indicating the encoding to use for the re
turned data.
... re
turns a string containing the file's data interpreted as text in the specified encoding.
File.lastModified - Web APIs
files without a known last modified date re
turn the current date.
... 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.
File.lastModifiedDate - Web APIs
the file.lastmodifieddate read-only property re
turns the last modified date of the file.
... files without a known last modified date re
turns the current date .
File.type - Web APIs
re
turns the media type (mime) of the file represented by a file object.
...uncommon file extensions would re
turn an empty string.
FileReader.error - Web APIs
the filereader error property re
turns the error that occurred while reading the file.
...in chrome 48+/firefox 58+ this property re
turns a domexception because domerror has been removed from the dom standard.
FileSystemEntry.getParent() - Web APIs
re
turn value undefined.
...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.
FileSystemEntry - Web APIs
getparent() re
turns a filesystemdirectoryentry representing the entry's parent directory.
... tourl() creates and re
turns a url which identifies the entry.
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.
... re
turn value undefined.
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.
... re
turn value undefined.
FileHandle API - Web APIs
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.
... 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.
FontFace.load - Web APIs
the load() method of the fontface interface 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.
... re
turn value a promise that resolves with a reference to the current fontface object when the font loads or rejects with a networkerror if the loading process fails.
FontFaceSet.load() - Web APIs
syntax result = afontfaceset.load(font); result = afontfaceset.load(font, text); re
turns a promise of an array of fontface loaded.
... examples // re
turns a promise that will be fulfilled or rejected according the success to load myfont // the code in 'then' can assume the availability of that font.
FontFaceSet.ready - Web APIs
the ready readonly property of the fontfaceset interface re
turns a promise that resolves to the given fontfaceset.
...}); re
turns a promise that resolves to the given fontfaceset.
FormData.entries() - Web APIs
the formdata.entries() method re
turns an iterator allowing to go through all key/value pairs contained in this object.
... syntax formdata.entries(); re
turn value re
turns an iterator.
FormData.keys() - Web APIs
the formdata.keys() method re
turns an iterator allowing to go through all keys contained in this object.
... syntax formdata.keys(); re
turn value re
turns an iterator.
FormData.values() - Web APIs
the formdata.values() method re
turns an iterator allowing to go through all values contained in this object.
... syntax formdata.values(); re
turn value re
turns an iterator.
FormDataEntryValue - Web APIs
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.
Frame Timing API - Web APIs
this method re
turns a list of "frame" performanceentry objects.
... each frame object's duration property re
turns the timestamp of two consecutive frames.
Gamepad.hand - Web APIs
the hand read-only property of the gamepad interface re
turns an enum defining what hand the controller is being held in, or is most likely to be held in.
... empty string ("") — this value is re
turned if the other values are not applicable, e.g.
Gamepad.id - Web APIs
the gamepad.id property of the gamepad interface re
turns a string containing some information about the controller.
... for example, a ps2 controller re
turned 810-3-usb gamepad.
GamepadButton - Web APIs
a gamepadbutton object is re
turned by querying any value of the array re
turned by the buttons property of the gamepad interface.
... note: this is the case in firefox gecko 28 and later; chrome and earlier firefox versions still re
turn an array of double values when this property is accessed.
GamepadEvent - Web APIs
constructor gamepadevent() re
turns a new gamepadevent object.
... properties gamepadevent.gamepad read only re
turns a gamepad object, providing access to the associated gamepad data for the event fired.
GeolocationCoordinates.longitude - Web APIs
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.
... examples in this simple example, we fetch the user's location and display the resulting coordinates once they're re
turned.
GeolocationPosition.coords - Web APIs
the geolocationposition.coords read-only property re
turns a geolocationcoordinates object representing a geographic position.
... it contains the location, that is longitude and latitude on the earth, the altitude, and the speed of the object concerned, regrouped inside the re
turned value.
GeolocationPosition - Web APIs
geolocationposition.coords read only secure context re
turns a geolocationcoordinates object defining the current location.
... geolocationposition.timestamp read only secure context re
turns a domtimestamp representing the time at which the location was retrieved.
GlobalEventHandlers.onerror - Web APIs
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.
...ror) { var string = msg.tolowercase(); var substring = "script error"; if (string.indexof(substring) > -1){ alert('script error: see browser console for detail'); } else { var message = [ 'message: ' + msg, 'url: ' + url, 'line: ' + lineno, 'column: ' + columnno, 'error object: ' + json.stringify(error) ].join(' - '); alert(message); } re
turn false; }; when using the inline html markup (<body onerror="alert('an error occurred')">), the html specification requires arguments passed to onerror to be named event, source, lineno, colno, error.
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.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
re
turn value none.
...also uses netutil.jsm 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(); 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('...
HTMLCanvasElement.mozGetAsFile() - Web APIs
the non-standard, firefox-specific the htmlcanvaselement method mozgetasfile() re
turns a memory-based file object representing the image contained in the canvas.
... re
turn value a file object representing the image contained in the canvas.
HTMLDialogElement.show() - Web APIs
re
turn value void.
...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
re
turn value void.
...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
the htmlelement.offsetheight read-only property re
turns the height of an element, including vertical padding and borders, as an integer.
... 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.
HTMLElement.offsetWidth - Web APIs
the htmlelement.offsetwidth read-only property re
turns the layout width of an element as an integer.
... 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.
HTMLFieldSetElement - Web APIs
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.
HTMLFormControlsCollection - Web APIs
it represents the lists re
turned by the htmlformelement interface's elements property and the htmlfieldsetelement interface's elements property.
... 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.
HTMLHtmlElement.version - Web APIs
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.
... 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.
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.
HTMLHyperlinkElementUtils.toString() - Web APIs
the htmlhyperlinkelementutils.tostring() stringifier method re
turns a usvstring containing the whole url.
... syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // re
turns: 'https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring' specifications specification status comment html living standard living standard ...
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.
HTMLIFrameElement.contentWindow - Web APIs
the contentwindow property re
turns the window object of an htmliframeelement.
... 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.
HTMLImageElement.naturalHeight - Web APIs
the htmlimageelement interface's naturalheight property is a read-only value which re
turns the intrinsic (natural), density-corrected height of the image in css pixels.
... 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.
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.
HTMLInputElement.mozGetFileNameArray() - Web APIs
the htmlinputelement.mozgetfilenamearray() method re
turns an array of the names of the files that were selected by the user on an html input element.
... syntax inputelement.mozgetfilenamearray(alength, afilenames); parameters alength if specified, will receive the number of file names in the re
turned array.
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.
...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.
HTMLLegendElement - Web APIs
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.
HTMLMediaElement.audioTracks - Web APIs
the read-only audiotracks property on htmlmediaelement objects re
turns an audiotracklist object listing all of the audiotrack objects representing the media element's audio tracks.
... 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.
HTMLMediaElement.captureStream() - Web APIs
the capturestream() property of the htmlmediaelement interface re
turns a mediastream object which is streaming a real-time capture of the content being rendered in the media element.
... re
turn value a mediastream object which can be used as a source for audio and/or video data by other media processing code, or as a source for webrtc.
HTMLMediaElement.load() - Web APIs
re
turn value undefined.
... 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.
HTMLMediaElement.seekable - Web APIs
the seekable read-only property of the htmlmediaelement re
turns a timeranges object that contains the time ranges that the user is able to seek to, if any.
... 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
the setmediakeys() property of the htmlmediaelement interface re
turns a promise that resolves to the passed mediakeys, which are those used to decrypt media during playback.
... re
turns a promise that resolves to the passed instance of mediakeys.
HTMLMediaElement.setSinkId() - Web APIs
the htmlmediaelement.setsinkid() method sets the id of the audio device to use for output and re
turns a promise.
...}) re
turns a promise that resolves to undefined.
HTMLMediaElement.videoTracks - Web APIs
the read-only videotracks property on htmlmediaelement objects re
turns a videotracklist object listing all of the videotrack objects representing the media element's video tracks.
... 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.
HTMLMeterElement.labels - Web APIs
the htmlmeterelement.labels read-only property re
turns a nodelist of the <label> elements associated with the <meter> element.
... syntax var labelelements = meter.labels; re
turn value a nodelist containing the <label> elements associated with the <meter> element.
HTMLObjectElement.checkValidity - Web APIs
the checkvalidity() method of the htmlobjectelement interface re
turns a boolean that always is true, because object objects are never candidates for constraint validation.
... re
turn value true exceptions none.
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.
... 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).
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.
HTMLOutputElement - Web APIs
htmloutputelement.checkvalidity() checks the validity of the element and re
turns a boolean holding the check result.
...if there are problems, fires an invalid event at the element, and re
turns false; if there are no problems, it re
turns true.
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.
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.
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.
HTMLTableElement.insertRow() - Web APIs
the htmltableelement.insertrow() method inserts a new row (<tr>) in a given <table>, and re
turns a reference to the new row.
... re
turn value newrow is an htmltablerowelement that references the new row.
HTMLTableElement.rows - Web APIs
the read-only htmltableelement property rows re
turns a live htmlcollection of all the rows in the table, including the rows contained within any <thead>, <tfoot>, and <tbody> elements.
... although the property itself is read-only, the re
turned object is live and allows the modification of its content.
HTMLTableRowElement.insertCell() - Web APIs
the htmltablerowelement.insertcell() method inserts a new cell (<td>) into a table row (<tr>) and re
turns a reference to the cell.
... re
turn value newcell is an htmltablecellelement that references the new cell.
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.
HTMLTrackElement - Web APIs
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.
... htmltrackelement.track read only re
turns texttrack is the track element's text track data.
File drag and drop - Web APIs
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.
...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.
Headers() - Web APIs
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.
...tructor 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 create another headers object, passing it the first headers object as its init object: var secondheadersobj = new headers(myheaders); secondheadersobj.get('content-type'); // would re
turn 'image/jpeg' — it inherits it from the first headers object specifications specification status comment fetchthe definition of 'headers()' in that specification.
Headers.delete() - Web APIs
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.
Headers.entries() - Web APIs
the headers.entries() method re
turns an iterator allowing to go through all key/value pairs contained in this object.
... syntax headers.entries(); re
turn value re
turns an iterator.
Headers.keys() - Web APIs
the headers.keys() method re
turns an iterator allowing to go through all keys contained in this object.
... syntax headers.keys(); re
turn value re
turns an iterator.
Headers.set() - Web APIs
re
turns void.
...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.
Headers.values() - Web APIs
the headers.values() method re
turns an iterator allowing to go through all values contained in this object.
... syntax headers.values(); re
turn value re
turns an iterator.
History.length - Web APIs
the history.length read-only property 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.
IDBCursor.delete() - Web APIs
the delete() method of the idbcursor interface re
turns an idbrequest object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position.
... syntax myidbcursor.delete(); re
turns an idbrequest object on which subsequent events related to this operation are fired.
IDBCursor.source - Web APIs
the source read-only property of the idbcursor interface re
turns the idbobjectstore or idbindex that the cursor is iterating over.
... 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.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.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBDatabase.transaction() - Web APIs
the transaction method of the idbdatabase interface immediately re
turns a transaction object (idbtransaction) containing the idbtransaction.objectstore method, which you can use to access your object store.
... details optional dictionary of other settings, supported only by chrome: re
turn value an idbtransaction object.
databases - Web APIs
the databases method of the idbfactory interface re
turns a list represening all the available databases, including their names and versions.
... re
turn value a promise that resolves either to an error or a list of dictionaries, each with two elements, name and version.
IDBFactory - Web APIs
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.
IDBIndex.getAll() - Web APIs
count optional the number records to re
turn.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBIndex.getAllKeys() - Web APIs
count optional the number records to re
turn.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
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.
...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.
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".
...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.
IDBIndex.name - Web APIs
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.
FileHandle.open() - Web APIs
summary the open method re
turns a lockedfile object that allows to safely write in the file.
... re
turn a lockedfile object.
IDBMutableFile - Web APIs
methods mutablefile.open() re
turns a lockedfile object to read or write the associated file safely.
... mutablefile.getfile() re
turns a domrequest object.
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.
... syntax var request = objectstore.clear(); re
turns an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.createIndex() - Web APIs
the createindex() method of the idbobjectstore interface creates and re
turns a new idbindex object in the connected database.
... re
turn value an idbindex object: the newly created index.
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.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.get() - Web APIs
the get() method of the idbobjectstore interface re
turns an idbrequest object, and, in a separate thread, re
turns the object store selected by the specified key.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
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.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.openCursor() - Web APIs
the opencursor() method of the idbobjectstore interface re
turns an idbrequest object, and, in a separate thread, re
turns a new idbcursorwithvalue object.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.openKeyCursor() - Web APIs
the openkeycursor() method of the idbobjectstore interface re
turns an idbrequest object whose result will be set to an idbcursor that can be used to iterate through matching results.
... re
turn value an idbrequest object on which subsequent events related to this operation are fired.
IDBRequest.onerror - Web APIs
the onerror event handler of the idbrequest interface handles the error event, fired when a request re
turns an error.
...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 onsuccess event handler of the idbrequest interface handles the success event, fired when the result of a request is successfully re
turned.
...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
the readystate read-only property of the idbrequest interface re
turns the state of the request.
...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
the result read-only property of the idbrequest interface re
turns the result of the request.
...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...
IDBTransaction.objectStoreNames - Web APIs
the objectstorenames read-only property of the idbtransaction interface re
turns a domstringlist of names of idbobjectstore objects.
... syntax var mydatabase = transactionobj.objectstorenames; re
turns a domstringlist of names of idbobjectstore objects.
IDBTransaction.error - Web APIs
the idbtransaction.error property of the idbtransaction interface re
turns one of several types of error when there is an unsuccessful transaction.
...in chrome 48+/firefox 58+ this property re
turns a domexception because domerror has been removed from the dom standard.
IDBTransaction.mode - Web APIs
the mode read-only property of the idbtransaction interface re
turns the current mode for accessing the data in the object stores in the scope of the transaction (i.e.
...ore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // re
turn the mode this transaction has been opened in (should be "readwrite" in this case) transaction.mode; }; specification specification status comment indexed database api 2.0the definition of 'mode' in that specification.
IDBTransactionSync - Web APIs
objectstore() re
turns an object store that has already been added to the scope of this transaction.
... re
turns idbobjectstoresync an object for accessing the requested object store.
IDBVersionChangeEvent - Web APIs
idbversionchangeevent.oldversion read only re
turns the old version of the database.
... idbversionchangeevent.newversion read only re
turns the new version of the database.
IdleDeadline - Web APIs
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.
...your callback can call this repeatedly to see if there's enough time left to do more work before re
turning.
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.
... re
turn value a new imagedata object.
IndexedDB API - Web APIs
this method re
turns an idbrequest object; asynchronous operations communicate to the calling application by firing events on idbrequest objects.
... idbcursorwithvalue iterates over object stores and indexes and re
turns the cursor's current value.
firesTouchEvents - Web APIs
the inputdevicecapabilities.firestouchevents read-only property re
turns a boolean that indicates whether the device dispatches touch events.
... 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.
InputEvent.getTargetRanges() - Web APIs
the gettargetranges() property of the inputevent interface re
turns an array of static ranges that will be affected by a change to the dom if the input event is not canceled.
... re
turn value an array of staticrange objects.
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.
InstallEvent.activeWorker - Web APIs
the activeworker read-only property of the installevent interface re
turns the serviceworker that is currently actively controlling the page.
... this will re
turn null if no active worker is already controlling the page.
InstallEvent - Web APIs
installevent.activeworker read only re
turns the serviceworker that is currently controlling the page.
...resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { re
turn cache.addall(urlstoprefetch.map(function(urltoprefetch) { re
turn new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(error) { console.error('pre-fetching failed:', error); }) ); }); specifications specification status comment serv...
installChrome - Web APIs
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.
IntersectionObserver.IntersectionObserver() - Web APIs
the intersectionobserver() constructor creates and re
turns a new intersectionobserver object.
... 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.
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.
... 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.
Keyboard.getLayoutMap() - Web APIs
the getlayoutmap() method of the keyboard interface 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.
... re
turn value a promise that resolves with an instance of keyboardlayoutmap.
Keyboard.lock() - Web APIs
the lock() method of the keyboard interface re
turns a promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard.
... re
turn value a promise.
Keyboard.unlock() - Web APIs
the unlock() method of the keyboard interface unlocks all keys captured by the keyboard.lock() method and re
turns synchronously.
... re
turn value undefined specifications specification status comment keyboard mapthe definition of 'keyboard' in that specification.
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.
... syntax var code = event.charcode; re
turn value a number that represents the unicode value of the character key that was pressed.
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.
... syntax var ctrlkeypressed = instanceofkeyboardevent.ctrlkey re
turn value a boolean example <html> <head> <title>ctrlkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + e.key + "\n" + "ctrl key pressed: " + e.ctrlkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the ctrl key.<br /> you can also use the shift key together with the ctrl key.</p> </body> </html> specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.ctrlkey' in that specification.
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.
... 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.
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.
... 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.
KeyboardEvent.repeat - Web APIs
the repeat read-only property of the keyboardevent interface re
turns a boolean that is true if the given key is being held down such that it is automatically repeating.
... syntax var repeat = event.repeat; re
turn value boolean specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.repeat' in that specification.
KeyboardEvent.which - Web APIs
the which read-only property of the keyboardevent interface re
turns the numeric keycode of the key pressed, or the character code (charcode) for an alphanumeric key pressed.
... syntax var keyresult = event.which; re
turn value keyresult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed.
KeyboardLayoutMap.has() - Web APIs
the has() method of the keyboardlayoutmap interface re
turns a boolean indicating whether the object has an element with the specified key.
... re
turn value a boolean indicating whether the specifed key was found.
Keyboard API - Web APIs
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.
... 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.
KeyframeEffect.target - Web APIs
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: '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.
LinkStyle - Web APIs
linkstyle.sheet read only re
turns the cssstylesheet object associated with the given element, or null if there is none.
... 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.
LocalFileSystem - Web APIs
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.
... 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.
LocalFileSystemSync - Web APIs
re
turns filesystemsync an object that represents the file system.
... re
turns entrysync an object that represents entries in the file system.
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.
... 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.
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.
... 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.
Location: toString() - Web APIs
the tostring() stringifier method of the location interface re
turns a usvstring containing the whole url.
... syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/location/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // re
turns: 'https://developer.mozilla.org/docs/location/tostring' specifications specification status comment html living standard living standard ...
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.
...lockmanager is the object re
turned by navigator.locks.
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.
...lockmanager is the object re
turned by navigator.locks.
LockManager.query() - Web APIs
the query() method of the lockmanager interface re
turns a promise which resolves with an object containing information about held and pending locks.
... re
turn value a promise that resolves with a lockmanagersnapshot containing the following properties.
LockedFile.readAsText() - Web APIs
encoding optional a string indicating the encoding to use for the re
turned data.
... re
turn a filerequest object to handle the success or failure of the operation.
Long Tasks API - Web APIs
work the browser does between different
turns of the event loop that exceeds 50 ms.
... taskattributiontiming re
turns information about the work involved in a long task and its associate frame context.
MIDIAccess - Web APIs
properties midiaccess.inputs read only re
turns an instance of midiinputmap which provides access to any available midi input ports.
... midiaccess.outputs read only re
turns an instance of midioutputmap which provides access to any available midi output ports.
MSGestureEvent - Web APIs
msgestureevent derives from uievent, which in
turn derives from event.
... msgestureevent.gestureobject read only re
turns the msgesture object for this gesture event.
MSManipulationEvent - Web APIs
properties property description currentstateread only re
turns the current state of a manipulation event.
... laststateread only re
turns the last state after a manipulation change event.
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.
... re
turn value a promise fulfilling with a mediacapabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient exceptions a typeerror is raised if the mediaconfiguration passed to the decodinginfo() method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, the media decoding configuration is not a valid value for the media decoding type, or any other error in the media configuration passed to th...
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.
... re
turn value a promise fulfilling with a mediacapabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient exceptions a typeerror is raised if the mediaconfiguration passed to the encodinginfo() method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, or any other error in the media configuration passed to the method, including omitting any of the media encoding configuration ele...
MediaCapabilities - Web APIs
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.
MediaDevices.getSupportedConstraints() - Web APIs
the getsupportedconstraints() method of the mediadevices interface re
turns an object based on the mediatracksupportedconstraints dictionary, whose member fields each specify one of the constrainable properties the user agent understands.
... re
turn value a new object based on the mediatracksupportedconstraints dictionary listing the constraints supported by the user agent.
load() - Web APIs
the mediakeysession.load() method re
turns a promise that resolves to a boolean value after loading data for a specified session object.
... re
turn value a promise that resolves to a boolean indicating whether the load succeeded or failed.
remove() - Web APIs
the mediakeysession.remove() method re
turns a promise after removing any session data associated with the current object.
... re
turn value a promise that resolves to a boolean indicating whether the load succeeded or failed.
update() - Web APIs
the mediakeysession.update() method loads messages and licenses to the cdm, and then re
turns a promise .
... re
turn value a promise.
MediaKeyStatusMap.entries() - Web APIs
the entries() read-only property of the mediakeystatusmap interface re
turns a new iterator object, containing an array of [key, value] pairs for each element in the status map, in insertion order.
... re
turns exceptions specifications specification status comment encrypted media extensions recommendation initial definition.
MediaKeyStatusMap.has() - Web APIs
the has property of the mediakeystatusmap interface re
turns a boolean, asserting whether a value has been associated with the given key.
... syntax var boolean = mediakeystatusmap(key) parameters key the key whose value you want re
turned re
turns a boolean.
MediaKeyStatusMap.keys() - Web APIs
the keys property of the mediakeystatusmap interface re
turns a new iterator object, containing keys for each element in the status map, in insertion order.
... re
turns a new iterator.
MediaKeyStatusMap.values() - Web APIs
the values property of the mediakeystatusmap interface re
turns a new iterator object, containing values for each element in the status map, in insertion order.
... re
turns a new iterator.
MediaKeys - Web APIs
methods mediakeys.createsession() re
turns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
... mediakeys.setservercertificate() re
turns a promise to a server certificate to be used to encrypt messages to the license server.
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.
MediaRecorder.isTypeSupported - Web APIs
the mediarecorder.istypesupported() static method re
turns a boolean which is true if the mime type specified is one the user agent should be able to successfully record.
... re
turn value true if the mediarecorder implementation is capable of recording blob objects for the specified mime type.
MediaRecorder.state - Web APIs
the mediarecorder.state read-only property re
turns the current state of the current mediarecorder object.
... record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); // will re
turn "recording" console.log("recorder started"); } ...
MediaRecorderErrorEvent.error - Web APIs
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.
...der = 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(event.data); }; recorder.onerror = function(event) { let error = event.error; }; recorder.start(100); /* 100ms time slices per buffer */ re
turn recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecordererrorevent.error' in that specification.
MediaRecorderErrorEvent - Web APIs
the mediarecordererrorevent interface represents errors re
turned by the mediastream recording api.
... constructor mediastreamrecorderevent() creates and re
turns a new mediarecordererrorevent event object with the given parameters.
MediaSource.addSourceBuffer() - Web APIs
the new sourcebuffer is also re
turned.
... re
turn value a sourcebuffer object representing the new source buffer that has been created and added to the media source.
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.
... re
turn value a newly-created mediastream object, either empty, or containing the tracks provided, if any.
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.
...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.
MediaStream.ended - Web APIs
the ended read-only property of the mediastream interface re
turns a boolean value which is true if the stream has been completely read, or false if the end of the stream has not been reached.
... syntax var hasended = mediastream.ended; value a boolean value that re
turns true if the end of the stream has been reached.
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.
... re
turn value an array of mediastreamtrack objects.
MediaStreamAudioSourceNode() - Web APIs
the web audio api's mediastreamaudiosourcenode() constructor creates and re
turns a new mediastreamaudiosourcenode object which uses the first audio track of a given mediastream as its source.
... re
turn value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream.
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.
... 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.
MediaStreamTrackAudioSourceNode() - Web APIs
the web audio api's mediastreamtrackaudiosourcenode() constructor creates and re
turns a new mediastreamtrackaudiosourcenode object whose audio is taken from the mediastreamtrack specified in the given options object.
... re
turn value a new mediastreamtrackaudiosourcenode object representing the audio node whose media is obtained from the specified media track.
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.
... re
turn value a new mediastreamtrackevent, initialized based on the provided options.
Using the MediaStream Recording API - Web APIs
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".
... grabbing and using the blob when recording has stopped, the state property re
turns a value of "inactive", and a stop event is fired.
MediaTrackConstraints.deviceId - Web APIs
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().
...that means that a given track will only re
turn one value for the deviceid when you call getcapabilities().
MediaTrackConstraints.displaySurface - Web APIs
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().
... 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.
MediaTrackConstraints.groupId - Web APIs
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().
...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.
MediaTrackConstraints.logicalSurface - Web APIs
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().
... 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.
MediaTrackSettings.deviceId - Web APIs
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().
... 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.
MessageChannel() - Web APIs
the messagechannel() constructor of the messagechannel interface re
turns a new messagechannel object with two new messageport objects.
... syntax var channel = new messagechannel(); re
turns a newly created messagechannel object.
MouseEvent.button - Web APIs
syntax var buttonpressed = instanceofmouseevent.button re
turn value a number representing a given button: 0: main button pressed, usually the left button or the un-initialized state 1: auxiliary button pressed, usually the wheel button or the middle button (if present) 2: secondary button pressed, usually the right button 3: fourth button, typically the browser back button 4: fifth button, typically the browser forward button as noted above, butto...
... obsolete compared to document object model (dom) level 2 events specification, the re
turn value can be negative.
MouseEvent.getModifierState() - Web APIs
the mouseevent.getmodifierstate() method re
turns the current state of the specified modifier key: true if the modifier is active (i.e., 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.
MouseEvent.pageX - Web APIs
the pagex read-only property of the mouseevent interface re
turns the x (horizontal) coordinate (in pixels) at which the mouse was clicked, relative to the left edge of the entire document.
...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.
MouseEvent.relatedTarget - Web APIs
the eventtarget the pointing device entered to the eventtarget the pointing device exited from dragenter the eventtarget the pointing device entered to the eventtarget the pointing device exited from dragexit the eventtarget the pointing device exited from the eventtarget the pointing device entered to for events with no secondary target, relatedtarget re
turns null.
... syntax var target = instanceofmouseevent.relatedtarget re
turn value an eventtarget object or null.
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.
... re
turn value a new mutationobserver object, configured to call the specified callback when dom mutations occur.
MutationObserver.takeRecords() - Web APIs
the mutationobserver method takerecords() re
turns a list of all matching dom changes that have been detected but not yet processed by the observer's callback function, leaving the mutation queue empty.
... re
turn value an array mutationrecord objects, each describing one change applied to the observed portion of the document's dom tree.
MutationObserver - Web APIs
constructor mutationobserver() creates and re
turns a new mutationobserver which will invoke a specified callback function when dom changes occur.
... takerecords() removes all pending notifications from the mutationobserver's notification queue and re
turns them in a new array of mutationrecord objects.
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.
... re
turn value a new ndefreader.
NDEFReader.scan() - Web APIs
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.
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.
... re
turn value a new ndefrecord.
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.
... re
turn value a list of ndefrecords.
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.
... re
turn value a new ndefwriter.
NDEFWriter.write() - Web APIs
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.
Using Navigation Timing - Web APIs
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.
... this information is provided by the performance.navigation property, which re
turns a performancenavigation object that includes the needed information.
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.
... the battery property has been removed in favor of the standard navigator.getbattery() method, which re
turns a battery promise.
Navigator.buildID - Web APIs
re
turns the build identifier of the browser.
... in modern browsers this property now re
turns a fixed timestamp as a privacy measure, e.g.
Navigator.canShare() - Web APIs
the navigator.canshare() method of the web share api re
turns true if a call to navigator.share() would succeed.
... re
turn value a boolean.
Navigator.clipboard - Web APIs
the clipboard api adds to the navigator interface the read-only clipboard property, which re
turns the clipboard object used to read and write the clipboard's contents.
...this happens because readtext() re
turns an empty string if the clipboard is empty or doesn't contain text.
Navigator.getUserMedia() - Web APIs
while technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise re
turning version.
... re
turn value undefined.
Navigator.mediaDevices - Web APIs
the navigator.mediadevices read-only property re
turns a mediadevices object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing.
... syntax var mediadevices = navigator.mediadevices; re
turn value the mediadevices singleton object.
Navigator.mediaSession - Web APIs
the read-only navigator property mediasession re
turns a mediasession object that can be used to share with the browser metadata and other information about the current playback state of media being handled by a document.
... this information may, in
turn, be shared with the device and/or operating system in order to a device's standard media control user experience to describe and control the playback of the media.
Navigator.sendBeacon() - Web APIs
re
turn values the sendbeacon() method re
turns true if the user agent successfully queued the data for transfer.
... otherwise, it re
turns false.
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.
navigator.hardwareConcurrency - Web APIs
the navigator.hardwareconcurrency read-only property re
turns the number of logical processors available to run threads on the user's computer.
... 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.
NavigatorConcurrentHardware - Web APIs
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.
NavigatorID.appName - Web APIs
note: do not rely on this property to re
turn a real browser name.
... all browsers re
turn "netscape" as the value of this property.
NavigatorID.product - Web APIs
note: do not rely on this property to re
turn a real product name.
... all browsers re
turn "gecko" as the value of this property.
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.
... note that in safari on ios prior to 10.2, the country code re
turned is lowercase: "en-us", "fr-fr" etc.
Online and offline events - Web APIs
you also need to know when your application has re
turned to an 'online' status again.
...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)...
NavigatorPlugins.mimeTypes - Web APIs
re
turns a mimetypearray object, which contains a list of mimetype objects representing the mime types recognized by the browser.
... 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.
NavigatorStorage.storage - Web APIs
the navigatorstorage.storage read-only property re
turns the singleton storagemanager object used to access the overall storage capabilities of the browser for the current site or app.
... the re
turned object lets you examine and configure persistence of data stores and learn approximately how much more space your browser has available for local storage use.
NavigatorStorage - Web APIs
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.
NetworkInformation.downlinkMax - Web APIs
the networkinformation.downlinkmax read-only property re
turns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology.
... syntax var max = networkinformation.downlinkmax re
turn value an unrestricted double representing the maximum downlink speed, in megabits per second (mb/s), for the underlying connection technology.
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.
... syntax rtt = networkinformation.rtt re
turn value a number.
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.
... 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.
Node.appendChild() - Web APIs
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.
Node.baseURI - Web APIs
the baseuri read-only property re
turns the absolute base url of a node.
...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.
Node.baseURIObject - Web APIs
the node.baseuriobject property re
turns the nsiuri representing the node's (typically a document or an element) base url.
... it's similar to node.baseuri, except it re
turns an nsiuri instead of a string.
Node.insertBefore() - Web APIs
re
turn value re
turns the added child (unless newnode is a documentfragment, in which case the empty documentfragment is re
turned).
... 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).
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.
... re
turn value result is a boolean that holds the re
turn value true or false.
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.
...if the version is not specified, supporting any version of the feature will cause the method to re
turn true.
Node.lastChild - Web APIs
the node.lastchild read-only property re
turns the last child of the node.
...it re
turns null if there are no child elements.
Node.rootNode - Web APIs
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.
... 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.
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.
... 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.
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.
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.
NodeIterator.whatToShow - Web APIs
the nodeiterator.whattoshow read-only property represents an unsigned integer representing a bitmask signifying what types of nodes should be re
turned by the nodeiterator.
... 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.
NodeList.entries() - Web APIs
the nodelist.entries() method re
turns an iterator allowing to go through all key/value pairs contained in this object.
... syntax list.entries(); re
turn value re
turns an iterator.
NodeList.keys() - Web APIs
the nodelist.keys() method re
turns an iterator allowing to go through all keys contained in this object.
... syntax nodelist.keys(); re
turn value re
turns an iterator.
NodeList.values() - Web APIs
the nodelist.values() method re
turns an iterator allowing to go through all values contained in this object.
... syntax nodelist.values(); re
turn value re
turns an iterator.
NonDocumentTypeChildNode - Web APIs
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.
Notification.data - Web APIs
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.
... 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.
OES_vertex_array_object.isVertexArrayOES() - Web APIs
the oes_vertex_array_object.isvertexarrayoes() method of the webgl api re
turns true if the passed object is a webglvertexarrayobject object.
... re
turn value a glboolean indicating whether the given object is a webglvertexarrayobject object (true) or not (false).
OES_vertex_array_object - Web APIs
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.
... ext.isvertexarrayoes() re
turns true if a given object is a webglvertexarrayobject.
OfflineAudioContext.OfflineAudioContext() - Web APIs
the offlineaudiocontext() constructor—part of the web audio api—creates and re
turns a new offlineaudiocontext object instance, which can then be used to render audio to an audiobuffer rather than to an audio output device.
... re
turn value a new offlineaudiocontext object whose associated audiobuffer is configured as requested.
OfflineAudioContext.suspend() - Web APIs
the suspend() method of the offlineaudiocontext interface schedules a suspension of the time progression in the audio context at the specified time and re
turns a promise.
... re
turns a promise resolving to void.
OfflineAudioContext - Web APIs
offlineaudiocontext.suspend() schedules a suspension of the time progression in the audio context at the specified time and re
turns a promise.
... when the startrendering() promise resolves, rendering has completed and the output audiobuffer is re
turned out of the promise.
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.
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.
OscillatorNode - Web APIs
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).
... 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).
ParentNode.firstElementChild - Web APIs
the parentnode.firstelementchild read-only property re
turns the object's first child element, or null if there are no child elements.
...) { if (constructor && constructor.prototype && constructor.prototype.firstelementchild == null) { object.defineproperty(constructor.prototype, 'firstelementchild', { get: function() { var node, nodes = this.childnodes, i = 0; 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.firstelementchild' in that specification.
ParentNode.prepend() - Web APIs
re
turn value undefined.
... var parent = document.createelement("div"); with(parent) { prepend("foo"); } // referenceerror: prepend is not defined polyfill you can polyfill the prepend() method if it's not available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('prepend')) { re
turn; } object.defineproperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isn...
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.
...in such cases, the browser re
turns an empty string as the value of region.
PaymentAddress.regionCode - Web APIs
the regioncode read-only attribute of the paymentaddress interface re
turns a one-, two-, or three-alphanumeric code (domstring) representing the region of the address (e.g., "ca" for california, or "11" for lisbon, portugal).
... 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.
PaymentAddress.toJSON() - Web APIs
the tojson() property of the paymentaddress interface is a standard serializer that re
turns a json representation of the paymentaddress object's properties.
... re
turn value a json object.
PaymentRequest.prototype.id - Web APIs
the id read-only attribute of the paymentrequest interface re
turns a unique identifier for a particular paymentrequest instance.
... 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.
PaymentRequest: shippingaddresschange event - Web APIs
const paymentrequest = 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.
... re
turn detailsupdate; }; you can also establish a handler for shippingaddresschange using the onshippingaddresschange event handler property: paymentrequest.onshippingaddresschange = event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupdate); }; specifications specification status comment payment request apithe definition of 'shippingaddresschange' in that specification.
PaymentResponse.methodName - Web APIs
the methodname read-only property of the paymentresponse interface re
turns a string uniquely identifying the payment handler selected by the user.
... example the following example extracts the method name from the paymentresponse object to the promise re
turned from paymentrequest.show().
PaymentResponse.shippingOption - Web APIs
the shippingoption read-only property of the paymentrequest interface re
turns the id attribute of the shipping option selected by the user.
...ls.shippingoptions[0]; othershippingoption = details.shippingoptions[1]; details.total.amount.value = '55.00'; } else if (shippingoption === 'express') { selectedshippingoption = details.shippingoptions[1]; othershippingoption = details.shippingoptions[0]; details.total.amount.value = '67.00'; } else { reject('unknown shipping option \'' + shippingoption + '\''); re
turn; } selectedshippingoption.selected = true; othershippingoption.selected = false; details.displayitems.splice(2, 1, selectedshippingoption); resolve(details); } specifications specification status comment payment request api candidate recommendation initial definition.
performance.clearResourceTimings() - Web APIs
syntax performance.clearresourcetimings(); arguments void re
turn value none this method has no re
turn value.
... example function load_resource() { var image = new image(); image.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; } function clear_performance_timings() { if (performance === undefined) { log("browser does not support web performance"); re
turn; } // create a resource timing performance entry by loading an image load_resource(); var supported = typeof performance.clearresourcetimings == "function"; if (supported) { console.log("run: performance.clearresourcetimings()"); performance.clearresourcetimings(); } else { console.log("performance.clearresourcetimings() not supported"); re
turn; } // getentries should now re
turn zero var p = performance.getentriesbytype("resource"); if (p.length == 0) console.log("...
performance.setResourceTimingBufferSize() - Web APIs
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.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.
... syntax myperf = performance.tojson() arguments none re
turn value myperf a json object that is the serialization of the performance object.
PerformanceEntry - Web APIs
properties performanceentry.name read only a value that further specifies the value re
turned by the performanceentry.entrytype property.
... methods performanceentry.tojson() re
turns a json representation of the performanceentry object.
PerformanceNavigationTiming.domComplete - Web APIs
the domcomplete read-only property re
turns a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to complete.
... syntax perfentry.domcomplete; re
turn value a timestamp representing a time value equal to the time immediately before the user agent sets the current document readiness of the current document to complete.
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
the domcontentloadedeventend read-only property re
turns a timestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes.
... syntax perfentry.domcontentloadedeventend; re
turn value a timestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes.
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
the domcontentloadedeventstart read-only property re
turns a timestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document.
... syntax perfentry.domcontentloadedeventstart; re
turn value a timestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document.
PerformanceNavigationTiming.domInteractive - Web APIs
the dominteractive read-only property re
turns a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive.
... syntax perfentry.dominteractive; re
turn value a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive.
PerformanceNavigationTiming.loadEventEnd - Web APIs
the loadeventend read-only property re
turns a timestamp which is equal to the time when the load event of the current document is completed.
... syntax perfentry.loadeventend; re
turn value a timestamp representing the time when the load event of the current document is completed.
PerformanceNavigationTiming.loadEventStart - Web APIs
the loadeventstart read-only property re
turns a timestamp representing the time value equal to the time immediately before the load event of the current document is fired.
... syntax perfentry.loadeventstart; re
turn value a timestamp representing a time value equal to the time immediately before the load event of the current document is fired.
PerformanceNavigationTiming.redirectCount - Web APIs
the redirectcount property re
turns a timestamp representing the number of redirects since the last non-redirect navigation under the current browsing context.
... syntax perfentry.redirectcount; re
turn value a number representing the number of redirects since the last non-redirect navigation under the current browsing context.
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.
PerformanceNavigationTiming.type - Web APIs
the type read-only property re
turns a string representing the type of navigation.
... syntax perfentry.type; re
turn value a string which is one of the values listed above.
PerformanceNavigationTiming.unloadEventEnd - Web APIs
the unloadeventend read-only property re
turns a timestamp representing the time value equal to the time immediately after the user agent finishes the unload event of the previous document.
... syntax perfentry.unloadeventend; re
turn value a timestamp representing a time value equal to the time immediately after the user agent finishes the unload event of the previous document.
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.
... re
turn value a list of performanceentry objects.
PerformanceObserver - Web APIs
constructor performanceobserver() creates and re
turns a new performanceobserver object.
... performanceobserver.takerecords() re
turns the current list of performance entries stored in the performance observer, emptying it out.
PerformanceResourceTiming.connectEnd - Web APIs
the connectend read-only property re
turns the timestamp immediately after the browser finishes establishing the connection to the server to retrieve the resource.
... syntax resource.connectend; re
turn value a domhighrestimestamp representing the time after a connection is established.
PerformanceResourceTiming.connectStart - Web APIs
the connectstart read-only property re
turns the timestamp immediately before the user agent starts establishing the connection to the server to retrieve the resource.
... syntax resource.connectstart; re
turn value a domhighrestimestamp immediately before the browser starts to establish the connection to the server to retrieve the resource.
PerformanceResourceTiming.domainLookupEnd - Web APIs
the domainlookupend read-only property re
turns the timestamp immediately after the browser finishes the domain name lookup for the resource.
... syntax resource.domainlookupend; re
turn value a domhighrestimestamp representing the time immediately after the browser finishes the domain name lookup for the resource.
PerformanceResourceTiming.domainLookupStart - Web APIs
the domainlookupstart read-only property re
turns the timestamp immediately before the browser starts the domain name lookup for the resource.
... syntax resource.domainlookupstart; re
turn value a domhighrestimestamp immediately before the browser starts the domain name lookup for the resource.
PerformanceResourceTiming.encodedBodySize - Web APIs
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.
PerformanceResourceTiming.fetchStart - Web APIs
if there are http redirects the property re
turns the time immediately before the user agent starts to fetch the final resource in the redirection.
... syntax resource.fetchstart; re
turn value a domhighrestimestamp immediately before the browser starts to fetch the resource.
PerformanceResourceTiming.responseEnd - Web APIs
the responseend read-only property re
turns a timestamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.
... syntax resource.responseend; re
turn value a domhighrestimestamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.
PerformanceResourceTiming.responseStart - Web APIs
the responsestart read-only property re
turns a timestamp immediately after the browser receives the first byte of the response from the server, cache, or local resource.
... syntax resource.responsestart; re
turn value a domhighrestimestamp immediately after the browser receives the first byte of the response from the server.
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.
PerformanceResourceTiming.transferSize - Web APIs
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.
PerformanceResourceTiming.workerStart - Web APIs
the workerstart read-only property of the performanceresourcetiming interface 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.
PerformanceServerTiming.toJSON - Web APIs
the tojson() method of the performanceservertiming interface re
turns a domstring that is the json representation of the performanceservertiming object.
... re
turn value a domstring containing json.
PerformanceServerTiming - Web APIs
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(/\n/g, '') }; response.writehead(200, headers); response.write(''); re
turn settimeout(_ => { response.end(); }, 1000) }; http.createserver(requesthandler).listen(3000).on('error', console.error); the performanceservertiming entries are now observable from javascript via the performanceresourcetiming.servertiming property: let entries = performance.getentriesbytype('resource'); console.log(entries[0].servertiming); // 0: performanceservertiming {name: "cache", duration: 2...
PerformanceTiming.loadEventEnd - Web APIs
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.
PerformanceTiming.loadEventStart - Web APIs
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.
PerformanceTiming.redirectEnd - Web APIs
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.
PerformanceTiming.redirectStart - Web APIs
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.
PerformanceTiming.secureConnectionStart - Web APIs
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.
PerformanceTiming.unloadEventEnd - Web APIs
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.
PerformanceTiming.unloadEventStart - Web APIs
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.
Using the Performance API - Web APIs
the now() method re
turns a timestamp (of type domhighrestimestamp) that is a discrete point in time.
... function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); endtime = performance.now(); re
turn (endtime - starttime); } serializing the performance object json serialization of the performance object is done via the tojson() method.
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'.
PermissionStatus - Web APIs
properties permissionstatus.state read only re
turns the state of a requested permission; one of 'granted', 'denied', or 'prompt'.
... permissionstatus.statusread only re
turns the state of a requested permission; one of 'granted', 'denied', or 'prompt'.
Permissions.revoke() - Web APIs
by the user, in the relevant permissions dialog), navigator.permissions.query() will re
turn true for both notifications and push.
... re
turns a promise that calls its fulfillment handler with a permissionstatus object indicating the result of the request.
Permissions API - Web APIs
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.
PhotoCapabilities.redEyeReduction - Web APIs
the redeyereduction read-only property of the photocapabilities interface re
turns an enum indicating the red-eye reduction capability of the source.
... always red-eye reduction is available in the source and it is always
turned on.
Plugin - Web APIs
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.
PointerEvent.getCoalescedEvents() - Web APIs
the getcoalescedevents() method of the pointerevent interface re
turns a sequence of all pointerevent instances that were coalesced into the dispatched pointermove event.
... re
turns a sequence of pointerevent instances.
PointerEvent.isPrimary - Web APIs
it re
turns true if the pointer that caused the event to be fired is the primary device and re
turns false otherwise.
... 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.
PointerEvent - Web APIs
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.
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 infinity the device must re
turn a cached position regardless of its age.
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.
PromiseRejectionEvent() - Web APIs
the promiserejectionevent() constructor re
turns a newly created promiserejectionevent, which represents events fired when a javascript promise is rejected.
... re
turn value a new promiserejectionevent configured as specified by the parameters.
PublicKeyCredential.getClientExtensionResults() - Web APIs
getclientextensionresults() is a method of the publickeycredential interface that re
turns an arraybuffer which contains a map between the extensions identifiers and their results after having being processed by the client.
... re
turn value an arraybuffer containing the result of the processing of the different extensions by the client.
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
isuserverifyingplatformauthenticatoravailable() is a static method of the publickeycredential interface that re
turns a promise which resolves to true if a user-verifying platform authenticator is available.
... re
turn value a promise which resolves to a boolean indicating whether or a not a user-verifying platform authenticator is available.
PublicKeyCredential - Web APIs
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.
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.
... self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { re
turn; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { ...
PushEvent - Web APIs
additional properties: pushevent.data read only re
turns a reference to a pushmessagedata object containing data sent to the pushsubscription.
... self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { re
turn; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new self.notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { client...
PushMessageData.json() - Web APIs
the json()method of the pushmessagedata interface extracts push message data by parsing it as a json string and re
turning the result.
... re
turns the result of parsing push event data as json.
PushSubscription.toJSON() - Web APIs
the tojson() method of the pushsubscription interface is a standard serializer: it re
turns a json representation of the subscription properties, providing a useful shortcut.
... re
turns a json object.
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.
... re
turns a promise that resolves to a boolean when the current subscription is successfully unsubscribed.
RTCConfiguration.iceServers - Web APIs
the rtcconfiguration dictionary's iceservers property is an array of rtciceserver objects, each of which describes a single stun or
turn server to use for negotiation purposes.
...]; value an array of zero or more rtciceserver objects, each of which describes one stun or
turn server for the ice agent to use during the connection's negotiation.
RTCDataChannel.close() - Web APIs
a background task is established to handle the remainder of the steps below, and close() re
turns to the caller.
... re
turn value undefined.
RTCDataChannelEvent - Web APIs
the rtcdatachannelevent() constructor re
turns a new rtcdatachannelevent object, which represents a datachannel event.
... 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.
RTCDtlsTransport.state - Web APIs
the function re
turns an object containing properties whose values indicate how many of the senders are in each state.
...) { case "new": case "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; case "failed": results.failed++; break; default: results.unknown++; break; } } }); re
turn results; } note that in this code, the new and connecting states are being treated as a single connectionpending status in the re
turned object.
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.
... re
turn value a newly-created rtcicecandidate object, optionally configured based on the specified object based on the rtcicecandidateinit dictionary.
RTCIceCandidate.address - Web APIs
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.
...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.
RTCIceCandidate.candidate - Web APIs
the read-only property candidate on the rtcicecandidate interface re
turns a domstring describing the candidate in detail.
... 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.
RTCIceCandidate.relatedAddress - Web APIs
for relay candidates, the related address and port are set to the mapped address selected by the
turn server.
... case "srflx": console.log("server reflexive candidate's base address is " + candidate.relatedaddress + "; reachable at " + candidate.ip); break; case "prflx": console.log("peer reflexive candidate's base address is " + candidate.relatedaddress + "; reachable at " + candidate.ip); break; case "relay": console.log("relay candidate's address assigned by the
turn server is " + candidate.relatedaddress + "; reachable at " + candidate.ip); break; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.relatedaddress' in that specification.
RTCIceCandidate. toJSON() - Web APIs
syntax json = rtcicecandidate.tojson(); re
turn value an object conforming to the rtcicecandidateinit dictionary, whose members' values are set to the corresponding values in the rtcicecandidate object.
... you can then get a stringified version of the object by calling stringify() on the re
turned object.
RTCIceCandidate.type - Web APIs
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.
RTCIceCandidate - Web APIs
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.
... 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.
RTCIceCandidatePairStats.selected - Web APIs
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; } }); } re
turn currentpair; } specifications not part of any specification.
RTCIceCandidatePairStats - Web APIs
usage notes the currently-active ice candidate pair—if any—can be obtained by calling the rtcicetransport method getselectedcandidatepair(), which re
turns an rtcicecandidatepair object, or null if there isn't a pair selected.
... any candidate pair that isn't the active pair of candidates for a transport gets deleted if the rtcicetransport performs an ice restart, at which point the state of the ice transport re
turns to new and negotiation starts once again.
RTCIceCandidateStats.candidateType - Web APIs
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.
RTCIceCandidateType - Web APIs
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.
RTCIceTransport.getLocalCandidates() - Web APIs
the rtcicetransport method getlocalcandidates() re
turns an array of rtcicecandidate objects, one for each of the candidates that have been gathered by the local device during the current ice agent session.
... 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.
RTCInboundRtpStreamStats.qpSum - Web APIs
example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp 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.
RTCOutboundRtpStreamStats.qpSum - Web APIs
example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp 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.
RTCOutboundRtpStreamStats - Web APIs
these retransmitted bytes comprise the packets included in the value re
turned by retransmittedpacketssent.
...these retransmitted packets are included in the value re
turned by packetssent.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
the read-only rtcpeerconnection property cantrickleicecandidates re
turns a boolean which indicates whether or not the remote peer can accept trickled ice candidates.
...pc.setremotedescription(remoteoffer) .then(_ => pc.createanswer()) .then(answer => pc.setlocaldescription(answer)) .then(_ => if (pc.cantrickleicecandidates) { re
turn pc.localdescription; } re
turn new promise(r => { pc.addeventlistener('icegatheringstatechange', e => { if (e.target.icegatheringstate === 'complete') { r(pc.localdescription); } }); }); }) .then(answer => sendanswertopeer(answer)) // signaling message .catch(e => handleerror(e)); pc.addeventlistener('icecandidate', e => { if (pc.cantrickl...
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.
...these values are re
turned by the connectionstate property.
RTCPeerConnection.currentLocalDescription - Web APIs
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.
... syntax sessiondescription = rtcpeerconnection.currentlocaldescription; re
turn value the current description of the local end of the connection, if one has been set.
RTCPeerConnection.currentRemoteDescription - Web APIs
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.
... syntax sessiondescription = rtcpeerconnection.currentremotedescription; re
turn value the current description of the remote end of the connection, if one has been set.
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.
... re
turn value a reference to an rtccertificate object.
RTCPeerConnection.getTransceivers() - Web APIs
the rtcpeerconnection interface's gettransceivers() method re
turns a list of the rtcrtptransceiver objects being used to send and receive data on the connection.
... re
turn value an array of the rtcrtptransceiver objects representing the transceivers handling sending and receiving all media on the rtcpeerconnection.
RTCPeerConnection.iceGatheringState - Web APIs
the read-only property rtcpeerconnection.icegatheringstate re
turns an enum of type rtcicegatheringstate that describes connection's ice gathering state.
... rtcicegatheringstate enum the rtcicegatheringstate enum defines string constants which reflect the current status of ice gathering, as re
turned using the rtcpeerconnection.icegatheringstate property.
RTCPeerConnection.localDescription - Web APIs
the read-only property rtcpeerconnection.localdescription re
turns an rtcsessiondescription describing the session for the local end of the connection.
... syntax var sessiondescription = peerconnection.localdescription; on a more fundamental level, the re
turned value is the value of rtcpeerconnection.pendinglocaldescription if that property isn't null; otherwise, the value of rtcpeerconnection.currentlocaldescription is re
turned.
RTCPeerConnection: negotiationneeded event - Web APIs
pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => re
turn pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }, false); after creating the offer, the local end is configured by calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share tha...
... 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.
RTCPeerConnection.onnegotiationneeded - Web APIs
pc.onnegotiationneeded = function() { pc.createoffer().then(function(offer) { re
turn pc.setlocaldescription(offer); }) .then(function() { // send the offer to the remote peer through the signaling server }); }) .catch(reporterror); } first, it creates the offer by calling createoffer().
...once that's succeeded in
turn, the offer can be sent to the signaling server for delivery to the remote peer.
RTCPeerConnection.restartIce() - Web APIs
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.
... re
turn value undefined.
RTCPeerConnection: track event - Web APIs
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.
... 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.
RTCRtpReceiveParameters - Web APIs
the rtcrtpreceiveparameters dictionary, based upon the rtcrtpparameters dictionary, is re
turned by the the rtcrtpreceiver method getparameters().
... 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.
RTCRtpReceiver.getContributingSources() - Web APIs
the getcontributingsources() method of the rtcrtpreceiver interface re
turns an array of rtcrtpcontributingsource instances, each corresponding to one csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... re
turn value an array of rtcrtpcontributingsource instances.
RTCRtpReceiver.getSynchronizationSources() - Web APIs
the getsynchronizationsources() method of the rtcrtpreceiver interface re
turns an array of rtcrtpcontributingsource instances, each corresponding to one ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... re
turn value an array of rtcrtpsynchronizationsource instances.
RTCRtpSender.dtmf - Web APIs
the read-only dtmf property on the rtcrtpsender interface re
turns a rtcdtmfsender object which can be used to send dtmf tones over the rtcpeerconnection .
... see using dtmf for details on how to make use of the re
turned rtcdtmfsender object.
RTCRtpSender.setParameters() - Web APIs
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.
RTCRtpStreamStats.qpSum - Web APIs
example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcrtpstreamstats object, 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.
RTCRtpTransceiver.setCodecPreferences() - Web APIs
if codecs is empty, the codec configurations are all re
turned to the user agent's defaults.
... re
turn value undefined exceptions invalidaccesserror the codecs list includes one or more codecs which are not supported by the transceiver.
RTCRtpTransceiver.stop() - Web APIs
note: until recently, the stopped property was provided to re
turn true if the connection is stopped.
... re
turn value undefined exceptions invalidstateerror the rtcpeerconnection of which the transceiver is a member is closed.
RTCSessionDescription - Web APIs
rtcsessiondescription() this constructor re
turns a new rtcsessiondescription.
... rtcsessiondescription.tojson() re
turns a json description of the object.
RTCTrackEvent() - Web APIs
the rtctrackevent() constructor creates and re
turns a new rtctrackevent object, configured to describe the track which has been added to the rtcpeerconnection.
... re
turn value a new rtctrackevent describing a track which has been added to the rtcpeerconnection.
RadioNodeList.value - Web APIs
on retrieving the value property, the value of the currently checked radio button is re
turned as a string.
... if the collection does not contain any radio buttons or none of the radio buttons in the collection is in checked state, the empty string is re
turned.
RadioNodeList - Web APIs
on retrieving the value property, the value of the currently checked radio button is re
turned as a string.
... if the collection does not contain any radio buttons or none of the radio buttons in the collection is in checked state, the empty string is re
turned.
Range.cloneRange() - Web APIs
the range.clonerange() method re
turns a range object with boundary points identical to the cloned range.
... the re
turned clone is copied by value, not reference, so a change in either range does not affect the other.
Range.collapsed - Web APIs
the range.collapsed read-only property re
turns a boolean flag indicating whether the start and end points of the range are at the same position.
... it re
turns true if the start and end boundary points of the range are the same point in the dom, false if not.
Range.getBoundingClientRect() - Web APIs
the range.getboundingclientrect() method re
turns a domrect object that bounds the contents of the range; this is a rectangle enclosing the union of the bounding rectangles for all the elements in the range.
...see element.getboundingclientrect() for details on the re
turned value.
Range.isPointInRange() - Web APIs
the range.ispointinrange() method re
turns a boolean indicating whether the given point is in the range.
... it re
turns true if the point (cursor position) at offset within referencenode is within this range.
ReadableByteStreamController - Web APIs
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.
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.
...}); 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.
ReadableStreamBYOBReader.read() - Web APIs
the read() method of the readablestreambyobreader interface re
turns a promise providing access to the next chunk in the byte stream's internal queue.
... re
turn value a promise, which fulfills/rejects with a result depending on the state of the stream.
ReadableStreamBYOBReader.releaseLock() - Web APIs
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.
... re
turn value undefined.
ReadableStreamDefaultReader.releaseLock() - Web APIs
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 readablestreamdefaultreader.read() method has not finished.
... re
turn value undefined.
Report.type - Web APIs
the type read-only property of the report interface re
turns the type of report generated, e.g.
... syntax let reporttype = reportinstance.type re
turns a string representing the type of the report.
Report.url - Web APIs
the url read-only property of the report interface re
turns the url of the document that generated the report.
... syntax let reporturl = reportinstance.url re
turns a string representing the url of the document that generated the report.
ReportingObserver.takeRecords() - Web APIs
the takerecords() method of the reportingobserver interface re
turns the current list of reports contained in the observer's report queue, and empties the queue.
... syntax reportingobserverinstance.takerecords() re
turn value an array of report objects.
ReportingObserver - Web APIs
reportingobserver.takerecords() re
turns the current list of reports contained in the observer's report queue, and empties the queue.
...after the first time we call reportingobserver.takerecords(), which re
turns the first generated report and empties the queue.
Request.destination - Web APIs
the destination read-only property of the request interface re
turns a string describing the type of content being requested.
... 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.
Request.referrer - Web APIs
(e.g., client, no-referrer, or a url.) note: if referrer's value is no-referrer, it re
turns an empty string.
... example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // re
turns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification.
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.
... 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.
Response.redirect() - Web APIs
the redirect() method of the response interface re
turns a response resulting in a redirect to the specified url.
... status optional an optional status code for the response (e.g., 302.) re
turn value a response object.
Response.redirected - Web APIs
fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.innerhtml = ""; } re
turn response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("a...
...wesome-picture.jpg", { redirect: "error" }).then(function(response) { re
turn response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specification.
Response.useFinalURL - Web APIs
in other contexts it will re
turn undefined.
... 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.
targetElement - Web APIs
if no target element is being animated (for example, because the href attribute specifies an unknown element), the value re
turned is null.
... editor's draft added null as re
turn value in case that no target element is being animated.
SVGGeometryElement.getTotalLength() - Web APIs
the svggeometryelement.gettotallength() method re
turns the user agent's computed value for the total length of the path in user units.
... syntax float someelement.gettotallength(); re
turn value a float indicating the total length of the path in user units.
SVGGeometryElement - Web APIs
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.
SVGImageElement.decode - Web APIs
the decode() method of the svgimageelement interface initiates asynchronous decoding of an image, re
turning a promise that resolves once the image data is ready for use.
... re
turn value a promise which resolves once the image data is ready to be used, such as by appending it to the dom, replacing an existing image, and so forth.
SVGImageElement - Web APIs
svgimageelement.decoding re
turns a domstring representing a hint given to the browser on how it should decode the image.
...re
turns a promise which resolves once the image data is ready to be used.
SVGPathElement.getPointAtLength() - Web APIs
the svgpathelement.getpointatlength() method re
turns the point at a given distance along the path.
... re
turn value an svgpoint indicating the point at a given distance along the path.
SVGPathElement.getTotalLength() - Web APIs
the svgpathelement.gettotallength() method re
turns the user agent's computed value for the total length of the path in user units.
... syntax float someelement.gettotallength(); re
turn value a float indicating the total length of the path in user units.
SVGPoint - Web APIs
syntax retobject = svgsvgelement.createsvgpoint() value the re
turned value is an svgpoint object.
... example // create an svgpoint in the user coordinate system let s = document.getelementbyid("svg-elementid").createsvgpoint(); // then, set the x and y values of the re
turned svgpoint object // (which is the variable `s`) s.y = 10; s.x = 10; ...
SVGStylable - Web APIs
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.
SVGUseElement - Web APIs
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.
...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.
Screen.colorDepth - Web APIs
the screen.colordepth read-only property re
turns the color depth of the screen.
... per the cssom, some implementations re
turn 24 for compatibility reasons.
Screen.height - Web APIs
the screen.height read-only property re
turns the height of the screen in pixels.
...it will only re
turn the real height of the screen if the zoom is set to 100%.
Screen.pixelDepth - Web APIs
re
turns the bit depth of the screen.
... per the cssom, some implementations re
turn 24 for compatibility reasons.
Screen.width - Web APIs
re
turns the width of the screen.
...it will only re
turn the real width of the screen if the zoom is set to 100%.
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.
...if the selection begins with the first character in the selection.anchornode, 0 is re
turned.
Selection.containsNode() - Web APIs
partialcontainment optional when true, containsnode() re
turns true when a part of the node is part of the selection.
... when false, containsnode() only re
turns true when the entire node is part of the selection.
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.
...if the selection ends with the first character in the selection.focusnode, 0 is re
turned.
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.
...in that scenario, calling a selection object's getrangeat() method may re
turn a range object which is collapsed.
Selection.type - Web APIs
the type read-only property of the selection interface re
turns a domstring describing the type of the current selection.
...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.
Selection API - Web APIs
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.
... 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.
ServiceWorker.state - Web APIs
the state read-only property of the serviceworker interface re
turns a string representing the current state of the service worker.
...the code listens for any change in the serviceworker.state and re
turns its value.
ServiceWorkerContainer.controller - Web APIs
the controller read-only property of the serviceworkercontainer interface re
turns a serviceworker object if its state is activated (the same object re
turned by serviceworkerregistration.active).
... this property re
turns null if the request is a force refresh (shift + refresh) or if there is no active worker.
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...
...ients.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('/'); })); }; specifications specification status notifications apithe definition of 'onnotificationclick' in that specification.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
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 the re
turned promise is resolved, we receive the new subscription.
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); re
turns a promise that immediately resolves with undefined.
... self.addeventlistener('install', function(event) { // the promise that skipwaiting() re
turns can be safely ignored.
ServiceWorkerRegistration.unregister() - Web APIs
the unregister() method of the serviceworkerregistration interface unregisters the service worker registration and re
turns a promise.
... re
turn value promise resolves with a boolean indicating whether the service worker has unregistered or not.
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.
... // 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.
SharedWorkerGlobalScope.applicationCache - Web APIs
the applicationcache read-only property of the sharedworkerglobalscope interface re
turns the applicationcache object for the worker (see using the application cache).
... 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.
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.
... 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.
SourceBuffer.appendBufferAsync() - Web APIs
it re
turns a promise which is fulfilled once the buffer has been appended.
... 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.
SourceBuffer.removeAsync() - Web APIs
a promise is re
turned, which is fulfilled when the buffers in the specified time range have been removed.
... re
turn value a promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the sourcebuffer.
SpeechGrammar.src - Web APIs
the src property of the speechgrammar interface sets and re
turns a string containing the grammar from within in the speechgrammar object.
...| orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should re
turn the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should re
turn 1 - the same as the weight set in line 4.
SpeechGrammar.weight - Web APIs
the optional weight property of the speechgrammar interface sets and re
turns the weight of the speechgrammar object.
...| orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should re
turn the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should re
turn 1 - the same as the weight set in line 4.
SpeechGrammarList.length - Web APIs
the length read-only property of the speechgrammarlist interface re
turns the number of speechgrammar objects contained in the speechgrammarlist.
...live | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; speechrecognitionlist.length; // should re
turn 1.
SpeechRecognition.abort() - Web APIs
the abort() method of the web speech api stops the speech recognition service from listening to incoming audio, and doesn't attempt to re
turn a speechrecognitionresult.
... syntax myspeechrecognition.abort(); re
turns void.
SpeechRecognition.interimResults - Web APIs
the interimresults property of the speechrecognition interface controls whether interim results should be re
turned (true) or not (false.) interim results are results that are not yet final (e.g.
...true means interim results are re
turned, and false means they aren't.
SpeechRecognition.onnomatch - Web APIs
the onnomatch property of the speechrecognition interface represents an event handler that will run when the speech recognition service re
turns a final result with no significant recognition (when the nomatch event fires.) this may involve some degree of recognition, which doesn't meet or exceed the confidence threshold.
... note: the onnomatch handler does not yet work properly in firefox — the speech recognition system always re
turns a positive match, and then guesses at what item in the grammar it found.
SpeechRecognition.stop() - Web APIs
the stop() method of the web speech api stops the speech recognition service from listening to incoming audio, and attempts to re
turn a speechrecognitionresult using the audio captured so far.
... syntax myspeechrecognition.stop(); re
turns void.
SpeechRecognitionError - Web APIs
speechrecognitionerror.error read only re
turns the type of error raised.
... speechrecognitionerror.message read only re
turns a message describing the error in more detail.
SpeechRecognitionErrorEvent - Web APIs
speechrecognitionerrorevent.error read only re
turns the type of error raised.
... speechrecognitionerrorevent.message read only re
turns a message describing the error in more detail.
SpeechRecognitionEvent.emma - Web APIs
the emma read-only property of the speechrecognitionevent interface re
turns an extensible multimodal annotation markup language (emma) — xml — representation of the result.
...if the speech recognition system does not supply emma data then the user agent will re
turn null.
SpeechRecognitionEvent.resultIndex - Web APIs
the resultindex read-only property of the speechrecognitionevent interface re
turns the lowest index value result in the speechrecognitionresultlist "array" that has actually changed.
... examples recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.resultindex); // re
turns 0 if there is only one result } specifications specification status comment web speech apithe definition of 'resultindex' in that specification.
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.
...}; 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.
SpeechSynthesis.paused - Web APIs
the paused read-only property of the speechsynthesis interface is a boolean that re
turns true if the speechsynthesis object is in a paused state, or false if not.
... examples var synth = window.speechsynthesis; synth.pause(); var amipaused = synth.paused; // will re
turn true specifications specification status comment web speech apithe definition of 'paused' in that specification.
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.
...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.
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.
...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.
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.
... 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.
StereoPannerNode.pan - Web APIs
syntax var audioctx = new audiocontext(); var pannode = audioctx.createstereopanner(); pannode.pan.value = -0.5; re
turned value an a-rate audioparam containing the panning to apply.
... note: though the audioparam re
turned is read-only, the value it represents is not.
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.
... re
turn value a promise that resolves to a boolean.
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.
... re
turns a promise that resolves to a boolean.
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.
... re
turns a reference to a storageinfo object.
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.
... re
turns a reference to a storageinfo object.
StylePropertyMapReadOnly.entries() - Web APIs
the stylepropertymapreadonly.entries() method 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).
... re
turn value an array of the given stylepropertymapreadonly object's own enumerable property [key, value] pairs.
StylePropertyMapReadOnly.getAll() - Web APIs
the getall() method of the stylepropertymapreadonly interface re
turns an array of cssstylevalue objects containing the values for the provided property.
... re
turn value an array of cssstylevalue objects.
StylePropertyMapReadOnly.keys() - Web APIs
the stylepropertymapreadonly.keys() method re
turns a new array iterator containing the keys for each item in stylepropertymapreadonly syntax stylepropertymapreadonly.keys() parameters none.
... re
turn value a new array.
StylePropertyMapReadOnly.values() - Web APIs
the stylepropertymapreadonly.values() method re
turns a new array iterator containing the values for each index in the stylepropertymapreadonly object.
... re
turn value a new array.
Stylesheet.href - Web APIs
the href property of the stylesheet interface re
turns the location of the style sheet.
... 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.
StyleSheet.ownerNode - Web APIs
the ownernode property of the stylesheet interface re
turns the node that associates this style sheet with the document.
... this is usually an html <link> or <style> element, but can also re
turn a processing instruction node in the case of <?xml-stylesheet ?>.
StyleSheet.parentStyleSheet - Web APIs
the parentstylesheet property of the stylesheet interface re
turns the style sheet, if any, that is including the given style sheet.
... syntax objref = stylesheet.parentstylesheet example // find the top level stylesheet if (stylesheet.parentstylesheet) { sheet = stylesheet.parentstylesheet; } else { sheet = stylesheet; } notes this property re
turns null if the current stylesheet is a top-level stylesheet or if stylesheet inclusion is not supported.
SubmitEvent() - Web APIs
the submitevent() constructor creates and re
turns a new submitevent object, which is used to represent a submit event fired at an html form.
... re
turn value a submitevent object configured using the given inputs.
SyncEvent - Web APIs
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.
SyncManager.getTags() - Web APIs
the syncmanager.gettags method of the syncmanager interface re
turns a list of developer-defined identifiers for syncmanager registrations.
...}) re
turns a promise that resolves to an array of domstrings containing developer-defined identifiers for syncmanager registrations.
SyncManager.register() - Web APIs
the syncmanager.register method of the syncmanager interface re
turns a promise that resolves to a syncregistration instance.
...}) re
turns a promise that resolves to an instance of syncregistration.
SyncManager - Web APIs
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.
Text.replaceWholeText() - Web APIs
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.
Text.splitText() - Web APIs
the newly created node is re
turned to the caller.
... re
turn value re
turns a newly created text node that contains the text after the specified offset point.
TextDecoder - Web APIs
constructor textdecoder() re
turns a newly constructed textdecoder that will generate a code point stream with the decoding method specified in parameters.
... textdecoder.prototype.decode() re
turns a domstring containing the text decoded with the method of the specific textdecoder object.
TextEncoder.prototype.encode() - Web APIs
the textencoder.prototype.encode() method takes a usvstring as input, and re
turns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object.
... re
turn value a uint8array object.
TextTrack - Web APIs
texttrack.inbandmetadatatrackdispatchtype read only re
turns a domstring which indicates the track's in-band metadata track dispatch type.
... needs details texttrack.kind read only re
turns a domstring indicating what kind of text track the texttrack describes.
TextTrackList - Web APIs
gettrackbyid() re
turns the texttrack found within the texttracklist whose id matches the specified string.
... if no match is found, null is re
turned.
TimeRanges.end() - Web APIs
re
turns the time offset at which a specified time range ends.
... syntax endtime = timeranges.end(index) parameters index is the range number to re
turn the ending time for.
TimeRanges.start() - Web APIs
re
turns the time offset at which a specified time range begins.
... syntax starttime = timeranges.start(index) parameters index is the range number to re
turn the starting time for.
msManipulationViewsEnabled - Web APIs
the msmanipulationviewsenabled read-only property re
turns true if manipulation features are support available, such as touch panning and zooming using css rules.
... value re
turns true if manipulation features are support available, such as touch panning and zooming using css rules.
Touch.clientX - Web APIs
the touch.clientx read-only property re
turns the x coordinate of the touch point relative to the viewport, not including any scroll offset.
... syntax touchitem.clientx; re
turn value a long representing the x coordinate of the touch point relative to the viewport, not including any scroll offset.
Touch.clientY - Web APIs
the touch.clienty read-only property re
turns the y coordinate of the touch point relative to the browser's viewport, not including any scroll offset.
... syntax touchitem.clienty; re
turn value a long value representing the y coordinate of the touch point relative to the viewport, not including any scroll offset.
Touch.identifier - Web APIs
the touch.identifier re
turns a value uniquely identifying this point of contact with the touch surface.
... syntax touchitem.identifier; re
turn value a long that represents the unique id of the touch object.
Touch.pageX - Web APIs
the touch.pagex read-only property re
turns the x coordinate of the touch point relative to the viewport, including any scroll offset.
... syntax touchitem.pagex; re
turn value a long representing the x coordinate of the touch point relative to the viewport, including any scroll offset.
Touch.pageY - Web APIs
the touch.pagey read-only property re
turns the y coordinate of the touch point relative to the viewport, including any scroll offset.
... syntax touchitem.pagey; re
turn value a long value that representes the y coordinate of the touch point relative to the viewport, including any scroll offset.
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.
... 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.
Touch.rotationAngle - Web APIs
summary re
turns the rotation angle, in degrees, of the contact area ellipse defined by touch.radiusx and touch.radiusy.
... 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.
Touch.screenX - Web APIs
summary re
turns the x coordinate of the touch point relative to the screen, not including any scroll offset.
... syntax var x = touchitem.screenx; re
turn value x the x coordinate of the touch point relative to the screen, not including any scroll offset.
Touch.screenY - Web APIs
summary re
turns the y coordinate of the touch point relative to the screen, not including any scroll offset.
... syntax var y = touchitem.screeny; re
turn value y the y coordinate of the touch point relative to the screen, not including any scroll offset.
Touch.target - Web APIs
summary re
turns the element (eventtarget) on which the touch contact started when it was first placed on the surface, even if the touch point has since moved outside the interactive area of that element or even been removed from the document.
... syntax var el = touchpoint.target; re
turn value el the target element of the touch object.
TouchList.identifiedTouch() - Web APIs
the identifiedtouch() method re
turns the first touch item in the touchlist that matches the specified identifier.
... re
turn value touchitem a touch object matching the specified id.
TouchList - Web APIs
methods touchlist.identifiedtouch() re
turns the first touch item in the list whose identifier matches a specified value.
... touchlist.item() re
turns the touch object at the specified index in the list.
TrackDefaultList - Web APIs
constructor trackdefaultlist() constructs and re
turns a new trackdefaultlist object.
... trackdefaultlist.length read only re
turns the number of trackdefault objects in the list.
TrackEvent() - Web APIs
the trackevent() constructor creates and re
turns a new trackevent object describing an event which occurred on a list of tracks (audiotracklist, videotracklist, or texttracklist).
... re
turn value a newly-created trackevent object, initialized as described by the inputs to the constructor.
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.
... 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.
TreeWalker.filter - Web APIs
the treewalker.filter read-only property re
turns a nodefilter that is the filtering object associated with the treewalker.
... 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.
TreeWalker.root - Web APIs
the treewalker.root read-only property re
turns the node that is the root of what the treewalker traverses.
... syntax root = treewalker.root; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); root = treewalker.root; // document.body in this case specifications specification status comment domthe definition of 'treewalker.root' in that specification.
TreeWalker.whatToShow - Web APIs
the treewalker.whattoshow read-only property re
turns an unsigned long being a bitmask made of constants describing the types of node that must to be presented.
... 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.
UIEvent.isChar - Web APIs
the uievent.ischar read-only property re
turns a boolean indicating whether the event produced a key character or not.
...when this is the case, ischar re
turns false.
sourceCapabilities - Web APIs
the uievent.sourcecapabilities read-only property re
turns an instance of the inputdevicecapabilities interface which provides information about the physical device responsible for generating a touch event.
... if no input device was responsible for the event, it re
turns null.
URL.origin - Web APIs
the origin read-only property of the url interface re
turns a usvstring containing the unicode serialization of the origin of the represented url.
... 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".
URLSearchParams() - Web APIs
the urlsearchparams() constructor creates and re
turns a new urlsearchparams object.
... re
turn value a urlsearchparams object instance.
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.
... re
turn value re
turns an iterator.
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.
... re
turn value a boolean.
URLSearchParams.keys() - Web APIs
the keys() method of the urlsearchparams interface re
turns an iterator allowing iteration through all keys contained in this object.
... re
turn value re
turns an iterator.
URLSearchParams.set() - Web APIs
re
turn value void.
...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 ...
URLSearchParams.sort() - Web APIs
the urlsearchparams.sort() method sorts all key/value pairs contained in this object in place and re
turns undefined.
... re
turn value undefined.
URLSearchParams.values() - Web APIs
the values() method of the urlsearchparams interface re
turns an iterator allowing iteration through all values contained in this object.
... re
turn value re
turns an iterator.
URLUtilsReadOnly.host - Web APIs
the urlutilsreadonly.host read-only property re
turns a domstring containing the host, that is the hostname, a ':', and the port of the url.
... syntax string = object.host; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.host var result = window.self.host; // re
turns:'developer.mozilla.org:80' specifications specification status comment urlthe definition of 'urlutilsreadonly.host' in that specification.
URLUtilsReadOnly.hostname - Web APIs
the urlutilsreadonly.hostname read-only property re
turns a domstring containing the domain of the url.
... syntax string = object.hostname; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.hostname var result = window.self.hostname; // re
turns:'developer.mozilla.org' specifications specification status comment urlthe definition of 'urlutilsreadonly.hostname' in that specification.
URLUtilsReadOnly.href - Web APIs
the urlutilsreadonly.href read-only property is a stringifier that re
turns a domstring containing the whole url.
... syntax string = object.href; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.href; // re
turns:'https://developer.mozilla.org/urlutilsreadonly.href' specifications specification status comment urlthe definition of 'urlutilsreadonly.href' in that specification.
URLUtilsReadOnly.pathname - Web APIs
the urlutilsreadonly.pathname read-only property re
turns a domstring containing an initial '/' followed by the path of the url.
... syntax string = object.pathname; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.pathname var result = window.self.pathname; // re
turns:'/urlutilsreadonly.pathname' specifications specification status comment urlthe definition of 'urlutilsreadonly.pathname' in that specification.
URLUtilsReadOnly.port - Web APIs
the urlutilsreadonly.port read-only property re
turns a domstring containing the port number of the url.
... syntax string = object.port; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.port var result = window.self.port; // re
turns:'80' specifications specification status comment urlthe definition of 'urlutilsreadonly.port' in that specification.
URLUtilsReadOnly.protocol - Web APIs
the urlutilsreadonly.protocol read-only property re
turns a domstring containing the protocol scheme of the url, including the final ':'.
... syntax string = object.protocol; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.protocol; // re
turns:'https:' specifications specification status comment urlthe definition of 'urlutilsreadonly.protocol' in that specification.
URLUtilsReadOnly.search - Web APIs
the urlutilsreadonly.search read-only property re
turns a domstring containing a '?' followed by the parameters of the url.
... syntax string = object.search; examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.href?t=67 var result = window.self.search; // re
turns:'?t=67' specifications specification status comment urlthe definition of 'urlutilsreadonly.search' in that specification.
URLUtilsReadOnly.toString() - Web APIs
the urlutilsreadonly.tostring() stringifier method re
turns a domstring containing the whole url.
... syntax string = object.tostring(); examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.tostring(); // re
turns:'https://developer.mozilla.org/urlutilsreadonly.href' browser compatibility the compatibility table in this page is generated from structured data.
USB.getDevices() - Web APIs
the getdevices method of the usb interface re
turns a promise that resolves with an array of usbdevice objects for paired attached devices.
... re
turn value a promise that resolves with an array of usbdevice objects.
USB.requestDevice() - Web APIs
the requestdevice() method of the usb interface re
turns a promise that resolves with an instance of usbdevice if the specified device is found.
...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.
USB - Web APIs
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.
USBDevice.claimInterface() - Web APIs
the claiminterface() method of the usbdevice interface re
turns a promise that resolves when the requested interface is claimed for exclusive access.
... re
turn value a promise.
USBDevice.clearHalt() - Web APIs
the clearhalt() method of the usbdevice interface re
turns a promise that resolves when a halt condition is cleared.
... re
turn value a promise.
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.
... re
turn value a promise.
USBDevice.controlTransferIn() - Web APIs
the controltransferin() method of the usbdevice interface re
turns a promise that resolves with a usbintransferresult when the result of a command or status request has been received from the usb device.
... re
turn value promise that resolves with a usbintransferresult.
USBDevice.controlTransferOut() - Web APIs
the controltransferout() method of the usbdevice interface re
turns a promise that resolves with a usbouttransferresult when a command or status operation has been transmitted to the usb device.
... re
turn value a promise that resolves with a usbouttransferresult.
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.
... re
turn value a promise that resolves with a usbisochronousintransferresult specifications specification status comment webusbthe definition of 'isochronoustransferin()' in that specification.
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.
... re
turn value a promise that resolves with a usbisochronousouttransferresult.
USBDevice.open() - Web APIs
the open() method of the usbdevice interface re
turns a promise that resolves when a device session has started.
... re
turn value a promise.
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.
... re
turn value a promise.
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.
... re
turn value a promise.
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.
... re
turn value a promise that resolves with a usbtransferinresult.
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.
... re
turn value a promise that resolves with a usbtransferoutresult.
USBInTransferResult - Web APIs
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.
USBIsochronousInTransferPacket - Web APIs
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.
USBIsochronousInTransferResult - Web APIs
properties usbisochronousintransferresult.dataread only re
turns a dataview object containing the data received from the device.
... usbisochronousintransferresult.packetsread only re
turns an array of usbisochronousintransferpacket objects containing the result of each request to receive a packet from the device.
USBIsochronousOutTransferPacket - Web APIs
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.
USBOutTransferResult - Web APIs
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.
VRStageParameters - Web APIs
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.
VTTCue() - Web APIs
the vttcue() constructor creates and re
turns a new vttcue object.
... re
turn value a new vttcue object representing a cue which will be presented during the time span given.
VideoTrack - Web APIs
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().
VideoTrackList - Web APIs
gettrackbyid() re
turns the videotrack found within the videotracklist whose id matches the specified string.
... if no match is found, null is re
turned.
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
the webgl_compressed_texture_astc.getsupportedprofiles() method re
turns an array of strings containing the names of the astc profiles supported by the implementation.
... syntax sequence<domstring> ext.getsupportedprofiles(); re
turn value an array of domstring elements indicating which astc profiles are supported by the implementation.
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
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.
WakeLock.request() - Web APIs
the request() method of the wakelock interface re
turns a promise that resolves with a wakelocksentinel object, which allows control over screen dimming and locking.
... re
turn value a promise that resolves with a wakelocksentinel object.
WakeLockSentinel.release() - Web APIs
the release() method of the wakelocksentinel interface releases the wakelocksentinel, re
turning a promise that is resolved once the sentinel has been successfully released.
... re
turn value re
turns a promise that resolves with undefined exceptions no exceptions are thrown.
WakeLockSentinel.type - Web APIs
the read-only type property of the wakelocksentinel interface re
turns a string representation of the currently acquired wakelocksentinel type.
... type read only re
turn values are: 'screen': a screen wake lock.
WebGL2RenderingContext.getFragDataLocation() - Web APIs
the webgl2renderingcontext.getfragdatalocation() method of the webgl 2 api re
turns the binding of color numbers to user-defined varying out variables.
... re
turn value a glint indicating the assigned color number binding, or -1 otherwise.
WebGL2RenderingContext.isQuery() - Web APIs
the webgl2renderingcontext.isquery() method of the webgl 2 api re
turns true if the passed object is a valid webglquery object.
... re
turn value a glboolean indicating whether the given object is a valid webglquery object (true) or not (false).
WebGL2RenderingContext.isSampler() - Web APIs
the webgl2renderingcontext.issampler() method of the webgl 2 api re
turns true if the passed object is a valid webglsampler object.
... re
turn value a glboolean indicating whether the given object is a valid webglsampler object (true) or not (false).
WebGL2RenderingContext.isSync() - Web APIs
the webgl2renderingcontext.issync() method of the webgl 2 api re
turns true if the passed object is a valid webglsync object.
... re
turn value a glboolean indicating whether the given object is a valid webglsync object (true) or not (false).
WebGL2RenderingContext.isTransformFeedback() - Web APIs
the webgl2renderingcontext.istransformfeedback() method of the webgl 2 api re
turns true if the passed object is a valid webgltransformfeedback object.
... re
turn value a glboolean indicating whether the given object is a valid webgltransformfeedback object (true) or not (false).
WebGL2RenderingContext.isVertexArray() - Web APIs
the webgl2renderingcontext.isvertexarray() method of the webgl api re
turns true if the passed object is a valid webglvertexarrayobject object.
... re
turn value a glboolean indicating whether the given object is a valid webglvertexarrayobject object (true) or not (false).
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.
... re
turn value none.
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.
... examples a webglactiveinfo object is re
turned by: webglrenderingcontext.getactiveattrib() webglrenderingcontext.getactiveuniform() or webgl2renderingcontext.gettransformfeedbackvarying() webglactiveinfo?
WebGLRenderingContext.activeTexture() - Web APIs
re
turn value none.
... 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.
WebGLRenderingContext.blendEquation() - Web APIs
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.
WebGLRenderingContext.blendEquationSeparate() - Web APIs
re
turn value none.
... 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.
WebGLRenderingContext.blendFunc() - Web APIs
re
turn value none.
... 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.
WebGLRenderingContext.blendFuncSeparate() - Web APIs
re
turn value none.
... 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.
WebGLRenderingContext.depthRange() - Web APIs
re
turn value none.
... examples gl.depthrange(0.2, 0.6); to check the current depth range, query the depth_range constant which re
turns a float32array gl.getparameter(gl.depth_range); // float32array[0.2, 0.6] specifications specification status comment webgl 1.0the definition of 'depthrange' in that specification.
WebGLRenderingContext.getAttachedShaders() - Web APIs
the webglrenderingcontext.getattachedshaders() method of the webgl api re
turns a list of webglshader objects attached to a webglprogram.
... re
turn value an array of webglshader objects that are attached to the given webglprogram.
WebGLRenderingContext.getProgramInfoLog() - Web APIs
the webglrenderingcontext.getprograminfolog re
turns the information log for the specified webglprogram object.
... re
turn value a domstring that contains diagnostic messages, warning messages, and other information about the last linking or validation operation.
WebGLRenderingContext.getShaderInfoLog() - Web APIs
the webglrenderingcontext.getshaderinfolog re
turns the information log for the specified webglshader object.
... re
turn value a domstring that contains diagnostic messages, warning messages, and other information about the last compile operation.
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
the webglrenderingcontext.getshaderprecisionformat() method of the webgl api re
turns a new webglshaderprecisionformat object describing the range and precision for the specified shader numeric format.
... re
turn value a webglshaderprecisionformat object or null, if an error occurs.
WebGLRenderingContext.getUniform() - Web APIs
the webglrenderingcontext.getuniform() method of the webgl api re
turns the value of a uniform variable at a given location.
... re
turn value the re
turned type depends on the uniform type: uniform type re
turned type webgl 1 only boolean glboolean int glint float glfloat vec2 float32array (with 2 elements) ivec2 int32array (with 2 elements) bvec2 array of glboolean (with 2 elements) vec3 float32array (with 3 elements) ivec3 int32array (with 3 elements) bvec3 array of glboolean (with 3 elements) vec4 float32array (with 4 elements) ivec4 int32array ...
WebGLRenderingContext.isBuffer() - Web APIs
the webglrenderingcontext.isbuffer() method of the webgl api re
turns true if the passed webglbuffer is valid and false otherwise.
... re
turn value a glboolean indicating whether or not the buffer is valid.
WebGLRenderingContext.isContextLost() - Web APIs
the webglrenderingcontext.iscontextlost() method re
turns a boolean indicating whether or not the webgl context has been lost and must be re-established before rendering can resume.
... syntax let islost = gl.iscontextlost(); re
turn value a boolean which is true if the context is lost, or false if not.
WebGLRenderingContext.isFramebuffer() - Web APIs
the webglrenderingcontext.isframebuffer() method of the webgl api re
turns true if the passed webglframebuffer is valid and false otherwise.
... re
turn value a glboolean indicating whether or not the frame buffer is valid.
WebGLRenderingContext.isProgram() - Web APIs
the webglrenderingcontext.isprogram() method of the webgl api re
turns true if the passed webglprogram is valid, false otherwise.
... re
turn value a glboolean indicating whether or not the program is valid.
WebGLRenderingContext.isRenderbuffer() - Web APIs
the webglrenderingcontext.isrenderbuffer() method of the webgl api re
turns true if the passed webglrenderbuffer is valid and false otherwise.
... re
turn value a glboolean indicating whether or not the renderbuffer is valid.
WebGLRenderingContext.isShader() - Web APIs
the webglrenderingcontext.isshader() method of the webgl api re
turns true if the passed webglshader is valid, false otherwise.
... re
turn value a glboolean indicating whether or not the shader is valid.
WebGLRenderingContext.isTexture() - Web APIs
the webglrenderingcontext.istexture() method of the webgl api re
turns true if the passed webgltexture is valid and false otherwise.
... re
turn value a glboolean indicating whether or not the texture is valid.
WebGLShaderPrecisionFormat - Web APIs
the webglshaderprecisionformat interface is part of the webgl api and represents the information re
turned by calling the webglrenderingcontext.getshaderprecisionformat() method.
... examples a webglshaderprecisionformat object is re
turned by the webglrenderingcontext.getshaderprecisionformat() method.
Clearing by clicking - Web APIs
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.
... function getrandomcolor() { re
turn [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
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...
...ndex] = !mask[index]; if (mask[index] === true) evt.target.innerhtml="on"; else evt.target.innerhtml="off"; gl.colormask(mask[0], mask[1], mask[2], true); drawanimation(); }; function drawanimation () { var color = getrandomcolor(); gl.clearcolor(color[0], color[1], color[2], 1.0); gl.clear(gl.color_buffer_bit); } function getrandomcolor() { re
turn [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Simple color animation - Web APIs
opanimation({type: "click"}); var gl; function drawanimation () { if (!gl) { var canvas = document.getelementbyid("canvas-view"); gl = canvas.getcontext("webgl") ||canvas.getcontext("experimental-webgl"); if (!gl) { clearinterval(timer); 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.
... function getrandomcolor() { re
turn [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Compressed texture formats - Web APIs
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).
...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
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.
...if the browser does not support webgl, getcontext() will re
turn null in which case we display a message to the user and exit.
Taking still photos with WebRTC - Web APIs
it re
turns a promise which we attach success and failure callbacks to.
...as it
turns out, any css filters you apply to the element using the filter property affect the captured photo.
Using WebRTC data channels - Web APIs
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.
...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.
Writing a WebSocket server in Java - Web APIs
public class websocket { public static void main(string[] args) throws ioexception, 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.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
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.
... 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.
Basic concepts behind Web Audio API - Web APIs
it won't
turn you into a master sound engineer, but it will give you enough background to understand why the web audio api works like it does.
... 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.
Web audio spatialization basics - Web APIs
the baseaudiocontext (the interface the audiocontext is extended from) has a listener property that re
turns an audiolistener object.
...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
the attestation is re
turned through the webauthn api as the authenticatorattestationresponse.
... the assertion is re
turned through the webauthn api as the authenticatorassertionresponse.
Web Workers API - Web APIs
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.
Window.back() - Web APIs
the obsolete and non-standard method back() on the window interface re
turns the window to the previous item in the history.
... re
turn value undefined.
window.cancelIdleCallback() - Web APIs
syntax window.cancelidlecallback(handle); parameters handle the id value re
turned by window.requestidlecallback() when the callback was established.
... re
turn value undefined.
Window.confirm() - Web APIs
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.
Window.content - Web APIs
re
turns a window object for the primary content window.
...in such cases, content re
turns a reference to the window object for the document currently displayed in the browser.
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.
... re
turn value a point object specifying a point in the page's coordinate system.
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.
... re
turn value a point object describing the specified location in the node's coordinate system.
Window.crypto - Web APIs
the read-only window.crypto property re
turns the crypto object associated to the global object.
... although window.crypto is available on all windows, the re
turned crypto object only has one usable feature in insecure contexts: the getrandomvalues() method.
Window.devicePixelRatio - Web APIs
the devicepixelratio of window interface re
turns the ratio of the resolution in physical pixels to the resolution in css pixels for the current display device.
...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.
Window.event - Web APIs
the read-only window property event re
turns the event which is currently being handled by the site's code.
... note: this property can be fragile, in that there may be situations in which the re
turned event is not the expected value.
Window.frames - Web APIs
re
turns the window itself, which is an array-like object, listing the direct sub-frames of the current window.
... for more details about the re
turned value, refer to this thread on mozilla.dev.platform.
Window.innerHeight - Web APIs
the read-only innerheight property of the window interface re
turns the interior height of the window in pixels, including the height of the horizontal scroll bar, if present.
... 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.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.
Privileged features - Web APIs
on mac systems, dialog windows have a different window border and they may get
turned into a sheet.
...the user cannot re
turn to the main window until the modal window is closed.
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.
... the corresponding pagexoffset property, which re
turns the number of pixels scrolled along the horizontal axis (left and right), is an alias for scrollx.
Window.requestAnimationFrame() - Web APIs
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.
Window.requestFileSystem() - Web APIs
the re
turned filesystem is then available for use with the other file system apis.
... 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.
Window.screenLeft - Web APIs
the window.screenleft read-only property re
turns the horizontal distance, in css pixels, from the left border of the user's browser viewport to the left side of the screen.
... syntax leftwindowpos = window.screenleft re
turns a number equal to the number of css pixels from the left edge of the browser viewport to the left edge of the screen.
Window.screenTop - Web APIs
the window.screentop read-only property re
turns the vertical distance, in css pixels, from the top border of the user's browser viewport to the top side of the screen.
... syntax topwindowpos = window.screentop re
turns a number equal to the number of css pixels from the top edge of the browser viewport to the top edge of the screen.
Window.screenX - Web APIs
the window.screenx read-only property re
turns the horizontal distance, in css pixels, of the left border of the user's browser viewport to the left side of the screen.
... syntax leftwindowpos = window.screenx re
turns a number equal to the number of css pixels from the left edge of the browser viewport to the left edge of the screen.
Window.screenY - Web APIs
the window.screeny read-only property re
turns the vertical distance, in css pixels, of the top border of the user's browser viewport to the top edge of the screen.
... syntax topwindowpos = window.screeny re
turns a number equal to the number of css pixels from the top edge of the browser viewport to the top edge of the screen.
Window.sidebar - Web APIs
re
turns a sidebar object which contains several methods for registering add-ons with the browser.
... methods the sidebar object re
turned has the following methods: method description (seamonkey) description (firefox) addpanel(title, contenturl, "") adds a sidebar panel.
Window.top - Web APIs
re
turns a reference to the topmost window in the window hierarchy.
... syntax var topwindow = window.top; notes where the window.parent property re
turns the immediate parent of the current window, window.top re
turns the topmost window in the hierarchy of window objects.
WindowClient.navigate() - Web APIs
the navigate() method of the windowclient interface loads a specified url into a controlled client page then re
turns a promise that resolves to the existing windowclient.
... re
turn value a promise that resolves to the existing windowclient.
WindowOrWorkerGlobalScope.caches - Web APIs
the caches read-only property of the windoworworkerglobalscope interface re
turns the cachestorage object associated with the current context.
... this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { re
turn cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); }); specificat...
self.createImageBitmap() - Web APIs
it accepts a variety of different image sources, and re
turns a promise which resolves to an imagebitmap.
... re
turn value a promise which resolves to an imagebitmap object containing bitmap data from the given rectangle.
WindowOrWorkerGlobalScope.origin - Web APIs
the origin read-only property of the windoworworkerglobalscope interface re
turns the origin of the global scope, serialized as a string.
...via file:// url), origin will re
turn the string "null".
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.
...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.
WorkerGlobalScope.navigator - Web APIs
the navigator read-only property of the workerglobalscope interface re
turns the workernavigator associated with the worker.
...acintosh; intel mac os x 10_10_1) applewebkit/537.36 (khtml, like gecko) chrome/40.0.2214.93 safari/537.36" hardwareconcurrency: 4 online: true platform: "macintel" product: "gecko" useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) applewebkit/537.36 (khtml, like gecko) chrome/40.0.2214.93 safari/537.36" __proto__: object you could use this navigator object to re
turn more information about the runtime envinronment, as you might do with a normal navigator object.
Worklet.addModule() - Web APIs
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.
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.
... 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.
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.
... // re
turn stream's desired size let size = writer.desiredsize; specifications specification status comment streamsthe definition of 'desiredsize' in that specification.
Sending and Receiving Binary Data - Web APIs
}; oreq.send(); receiving binary data in older browsers the load_binary_resource() function shown below loads binary data from the specified url, re
turning it to the caller.
... function load_binary_resource(url) { var req = new xmlhttprequest(); req.open('get', url, false); //xhr binary charset opt by marcus granado 2006 [http://mgran.blogspot.com] req.overridemimetype('text\/plain; charset=x-user-defined'); req.send(null); if (req.status != 200) re
turn ''; re
turn req.responsetext; } the magic happens in line 5, which overrides the mime type, forcing the browser to treat it as plain text, using a user-defined character set.
XMLHttpRequest.responseURL - Web APIs
the read-only xmlhttprequest.responseurl property re
turns the serialized url of the response or the empty string if the url is null.
... if the url is re
turned, any url fragment present in the url will be stripped away.
XMLSerializer - Web APIs
methods serializetostring() re
turns the serialized subtree of a string.
... 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.
XPathException - Web APIs
properties xpathexception.code read only re
turns a short that contains one of the error code constants.
... type_err 52 if the expression cannot be converted to re
turn the specified type.
XPathResult.booleanValue - Web APIs
the read-only booleanvalue property of the xpathresult interface re
turns the boolean value of a result with xpathresult.resulttype being boolean_type.
... syntax var value = result.booleanvalue; re
turn value the re
turn value is the boolean value of the xpathresult re
turned by document.evaluate().
XPathResult.invalidIteratorState - Web APIs
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.
... syntax var iteratorstate = result.invaliditeratorstate; re
turn value a boolean value indicating whether the iterator has become invalid.
XPathResult.numberValue - Web APIs
the read-only numbervalue property of the xpathresult interface re
turns the numeric value of a result with xpathresult.resulttype being number_type.
... syntax var value = result.numbervalue; re
turn value the re
turn value is the numeric value of the xpathresult re
turned by document.evaluate().
XPathResult.singleNodeValue - Web APIs
the read-only singlenodevalue property of the xpathresult interface re
turns a node value or null in case no node was matched of a result with xpathresult.resulttype being any_unordered_node_type or first_ordered_node_type.
... syntax var value = result.singlenodevalue; re
turn value the re
turn value is the node value of the xpathresult re
turned by document.evaluate().
XPathResult.snapshotItem() - Web APIs
the snapshotitem() method of the xpathresult interface re
turns an item of the snapshot collection or null in case the index is not within the range of nodes.
... syntax var node = result.snapshotitem(i); re
turn value the node at the given index within the node set of the xpathresult.
XPathResult.stringValue - Web APIs
the read-only stringvalue property of the xpathresult interface re
turns the string value of a result with xpathresult.resulttype being string_type.
... syntax var value = result.stringvalue; re
turn value the re
turn value is the string value of the xpathresult re
turned by document.evaluate().
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.
... re
turn value an xrpose object specifying the position and orientation, relative to the xrspace indicated by basespace.
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.
... re
turn value a xrviewerpose describing the viewer's position and orientation relative to the specified reference space.
XRFrame - Web APIs
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.
XRFrameRequestCallback - Web APIs
syntax function xrframerequestcallback(time, xrframe){ // process xrframe here } xrsession.requestanimationframe(xrframerequestcallback) parameters domhighrestimestamp a timestamp corresponding to the re
turned xrframe.
... re
turn value none.
XRInputSource.gripSpace - Web APIs
the read-only xrinputsource property gripspace re
turns an xrspace whose native origin tracks the pose used to render virtual objects so they appear to be held in (or part of) the user's hand.
...if a valid pose is re
turned, a method mydrawmeshusingtransform() is called to draw the controller's mesh transformed using the grip pose's transform matrix.
XRInputSourceArray.entries() - Web APIs
the xrinputsourcearray interface's entries() method re
turns a javascript iterator which can then be used to iterate over the key/value pairs in the input source array.
... re
turn value an iterator which can be used to walk through the list of xrinputsource objects included in the input source array.
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.
... re
turn value a new xrinputsourceevent object representing the event described by the given type and eventinitdict.
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.
... re
turn value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided.
XRPermissionDescriptor - Web APIs
when the re
turned promise resolves, we check the re
turned status.
...and for any other re
turned state—which is almost certainly denied, which is the only other option as of this article's writing—we do nothing, since we can't use webxr.
XRRenderState.baseLayer - Web APIs
the read-only baselayer property of the xrrenderstate interface re
turns the xrwebgllayer instance that is the source of bitmap images and a description of how the image is to be rendered in the device.
... 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.
XRSession.cancelAnimationFrame() - Web APIs
syntax xrsession.cancelanimationframe(handle); parameters handle the unique value re
turned by the call to requestanimationframe() that previously scheduled the animation callback.
... re
turn value none.
XRSession.end() - Web APIs
the end() method shuts down the xrsession on which it's called, re
turning a promise which resolves once the session has fully shut down.
... re
turn value a promise that resolves without a value after any platform-specific steps related to shutting down the session have completed.
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.
...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.
XRSession: selectend event - Web APIs
mybegintracking() re
turns an object representing the object the user has begun to drag.
... xrsession.addeventlistener("selectstart", onselectionevent); 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.matr...
XRSession: selectstart event - Web APIs
mybegintracking() re
turns an object representing the object the user has begun to drag.
... xrsession.addeventlistener("selectstart", onselectionevent); 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.matr...
XRSession: squeezeend event - Web APIs
mybegintracking() re
turns an object representing the object the user has begun to drag.
... xrsession.addeventlistener("squeezestart", 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.m...
XRSession: squeezestart event - Web APIs
mybegintracking() re
turns an object representing the object the user has begun to drag.
... xrsession.addeventlistener("squeezestart", 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.m...
XRSessionEvent() - Web APIs
the webxr device api's xrsessionevent() constructor creates and re
turns a new xrsessionevent object.
... re
turn value a newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter.
XRSessionInit - Web APIs
optionalfeatures optional an array of values identifying features which the re
turned xrsession may optionally support.
... requiredfeatures optional an array of values which the re
turned xrsession must support.
msGetPropertyEnabled - Web APIs
the msgetpropertyenabled re
turns whether a given property in the style object is enabled.
... re
turn value type: boolean if false, the property is not enabled.
msGetRegionContent - Web APIs
the msgetregioncontent re
turns an array of range instances corresponding to the content from the region flow that is positioned in the region.
... re
turn value type: boolean re
turned ranges are sorted by document position and do not overlap.
Alerts - Accessibility
a value of -1 or less is re
turned if the index of the search term could not be found within the value.
... in both cases, when re
turning focus to the field in question, your screen reader should tell you that this field is invalid.
Accessibility: What users can do to browse more safely - Accessibility
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.
...
turn off animations in the operating system in the windows10 operating system, the user has an ability to
turn off animations.
Understandable - Accessibility
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.
...client-side validation is too easy to
turn off or otherwise get around, so it can't be relied on alone.
prefers-color-scheme - CSS: Cascading Style Sheets
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.
prefers-reduced-motion - CSS: Cascading Style Sheets
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.
... in windows 7: control panel > ease of access > make the computer easier to see >
turn off all unnecessary animations (when possible).
Using feature queries - CSS: Cascading Style Sheets
the following rule will only re
turn true if both shape-outside: circle() and display: grid are supported by the browser.
...if the property and value pair is understood by the browser it re
turns a positive response.
Variable fonts guide - CSS: Cascading Style Sheets
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.
...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.
Basic Concepts of grid layout - CSS: Cascading Style Sheets
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.
...if we re
turn to our example with items positioned by line number, we can change this to make two items overlap.
Computed value - CSS: Cascading Style Sheets
however, for some properties (those where percentages are relative to something that may require layout to determine, such as width, margin-right, text-indent, and top), percentage-specified values
turn into percentage-computed values.
... 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.
counter() - CSS: Cascading Style Sheets
the counter() css function re
turns a string representing the current value of the named counter, if there is one.
...the counter() function (and counters() function) is what makes it useful by re
turning developer defined strings (or images).
counters() - CSS: Cascading Style Sheets
the counters() css function enables nested counters, re
turning a concatenated string representing the current values of the named counters, if there are any.
...the counters() function (and counter() function) is what makes it useful by re
turning developer defined content.
<display-box> - CSS: Cascading Style Sheets
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.
display - CSS: Cascading Style Sheets
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.
font-smooth - CSS: Cascading Style Sheets
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.
... 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.
grid-auto-flow - CSS: Cascading Style Sheets
values row items are placed by filling each row in
turn, adding new rows as necessary.
... column items are placed by filling each column in
turn, adding new columns as necessary.
image-orientation - CSS: Cascading Style Sheets
it is rounded to the nearest 90deg (0.25
turn).
... formal definition initial value0degapplies toall elementsinheritedyescomputed valuean <angle>, rounded to the next quarter
turn from 0deg and normalized, that is moduloing the value by 1
turnanimation typediscrete formal syntax from-image | <angle> | [ <angle>?
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 position of the gradient line's starting point.
text-justify - CSS: Cascading Style Sheets
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.
scale() - CSS: Cascading Style Sheets
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.
Common (exsl) - EXSLT
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.
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.
... re
turns a node-set containing the nodes that have unique string values.
Video player styling basics - Developer guides
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.
...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
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.
...stfullscreen(); else if (videocontainer.webkitrequestfullscreen) videocontainer.webkitrequestfullscreen(); else if (videocontainer.msrequestfullscreen) videocontainer.msrequestfullscreen(); setfullscreendata(true); } } first of all the function checks if the browser is already in fullscreen mode by calling another function isfullscreen: var isfullscreen = function() { re
turn !!(document.fullscreen || document.webkitisfullscreen || document.mozfullscreen || document.msfullscreenelement || document.fullscreenelement); } this function checks all the various browser prefixed versions to try and determine the correct result.
Audio and Video Delivery - Developer guides
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.
Audio and video manipulation - Developer guides
var processor = { timercallback: function() { if (this.video.paused || this.video.ended) { re
turn; } this.computeframe(); var self = this; settimeout(function () { self.timercallback(); }, 16); // roughly 60 frames per second }, doload: function() { this.video = document.getelementbyid("my-video"); this.c1 = document.getelementbyid("my-canvas"); this.ctx1 = this.c1.getcontext("2d"); var self = this; this.video.addeventlistener("play", functi...
...; var frame = this.ctx1.getimagedata(0, 0, this.width, this.height); var l = frame.data.length / 4; for (var i = 0; i < l; i++) { var grey = (frame.data[i * 4 + 0] + frame.data[i * 4 + 1] + frame.data[i * 4 + 2]) / 3; frame.data[i * 4 + 0] = grey; frame.data[i * 4 + 1] = grey; frame.data[i * 4 + 2] = grey; } this.ctx1.putimagedata(frame, 0, 0); re
turn; } }; once the page has loaded you can call processor.doload() result this is a pretty simple example showing how to manipulate video frames using a canvas.
Challenge solutions - Developer guides
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.
... button.setattribute("disabled", "true"); settimeout(cleardemo, 2000, button); } function cleardemo (button) { var square = document.getelementbyid("square"); square.style.backgroundcolor = "transparent"; square.style.marginleft = "0em"; button.removeattribute("disabled"); } svg and css change color of inner petals 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.
HTML5 Parser - Developer guides
it controls how your html source code is
turned into web pages and, as such, changes to it are rare.
... the html5 specification provides a more detailed description than previous html standards of how to
turn a stream of bytes into a dom tree.
HTML5 - Developer guides
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.
...incidentally, you also need to know when your application has re
turned to an online status again.
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
the value can be specified in any <angle> unit supported by css, including degrees (deg), radians (rad), gradians (grad), or
turns (
turn).
...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...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
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.
...t("the <dialog> api is not supported by this browser"); } }); // "favorite animal" input sets the value of the submit button selectel.addeventlistener('change', function onselect(e) { confirmbtn.value = selectel.value; }); // "confirm" button of form triggers "close" on dialog because of [method="dialog"] favdialog.addeventlistener('close', function onclose() { outputbox.value = favdialog.re
turnvalue + " button clicked - " + (new date()).tostring(); }); result specifications specification status comment html living standardthe definition of '<dialog>' in that specification.
<input type="email"> - HTML: Hypertext Markup Language
the text must not include carriage re
turns or line feeds.
...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="image"> - HTML: Hypertext Markup Language
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.
...the server-side code then works out what location was clicked on, and re
turns information about places nearby.
<input type="number"> - HTML: Hypertext Markup Language
the text must not include carriage re
turns or line feeds.
...placeholder="x10" step="10" min="0" max="100" id="number"> then we add some css to narrow the width of the element with the id selector #number: #number { width: 3em; } the result looks like this: offering suggested values you can provide a list of default options from which the user can select by specifying the list attribute, which contains as its value the id of a <datalist>, which in
turn contains one <option> element per suggested value.
<select>: The HTML Select element - HTML: Hypertext Markup Language
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.
... 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.
HTML elements reference - HTML: Hypertext Markup Language
<br> the html <br> element produces a line break in text (carriage-re
turn).
... <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.
Browser detection using the user agent - HTTP
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 assu...
...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.
Configuring servers for Ogg media - HTTP
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.
Feature Policy - HTTP
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.
Access-Control-Allow-Origin - HTTP
if the server supports clients from multiple origins, it must re
turn the origin for the specific client making the request.
... 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".
If-Match - HTTP
if it doesn't match, then a 416 (range not satisfiable) response is re
turned.
...if the request cannot be fulfilled, the 412 (precondition failed) response is re
turned.
HTTP headers - HTTP
content-location indicates an alternate location for the re
turned data.
... range indicates the part of a document that the server should re
turn.
A typical HTTP session - HTTP
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.
... structure of a server response after the connected agent has sent its request, the web server processes it, and ultimately re
turns a response.
204 No Content - HTTP
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.
Introduction - JavaScript
variables, parameters, and function re
turn types are not explicitly typed.
...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.
Groups and ranges - JavaScript
string.match() won't re
turn groups if the /.../g flag is set.
... (?<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>.
extends - JavaScript
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.
... 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...
...t', '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
'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.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
"use strict"; function archiver() { var temperature = null; object.defineproperty(this, 'temperature', { get: function() { console.log('get!'); re
turn temperature; } }); } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 30; // typeerror: setting getter-only property "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 tempe...
...rature = 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 }] ...
RangeError: invalid date - JavaScript
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.
SyntaxError: Malformed formal parameter - JavaScript
examples invalid cases var f = function('x y', 're
turn x + y;'); // syntaxerror (missing a comma) var f = function('x,', 're
turn x;'); // syntaxerror (extraneous comma) var f = function(37, "alert('ok')"); // syntaxerror (numbers can't be argument names) valid cases var f = function('x, y', 're
turn x + y;'); // correctly punctuated var f = function('x', 're
turn x;'); // if you can, avoid using function - this is much faster var f = function(x...
...) { re
turn x; }; ...
TypeError: "x" is not a constructor - JavaScript
to do this, you would write the following function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } 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.
... this is not legal (the promise constructor is not being called correctly) and will throw a typeerror: this is not a constructor exception: re
turn new promise.resolve(true); instead, use the promise.resolve() or promise.reject() static methods: // this is legal, but unnecessarily long: re
turn new promise((resolve, reject) => { resolve(true); }) // instead, re
turn the static method: re
turn promise.resolve(true); re
turn promise.reject(false); ...
ReferenceError: "x" is not defined - JavaScript
variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function function numbers() { var num1 = 2, num2 = 3; re
turn num1 + num2; } console.log(num1); // referenceerror num1 is not defined.
... var num1 = 2, num2 = 3; function numbers() { re
turn num1 + num2; } console.log(numbers()); // 5 ...
TypeError: Reduce of empty array with no initial value - JavaScript
this error is raised when an empty array is provided because no initial value can be re
turned in that case.
... 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.
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
examples function statement in this case, the function sum has default parameters 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; }; })(); 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); }; })(); ...
SyntaxError: Unexpected token - JavaScript
other expression: for (let i = 0; i < 5; ++i) { console.log(i); } not enough brackets sometimes, you leave out brackets around if statements: 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: expected expression, 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; } } ...
JavaScript error reference - JavaScript
operatorsyntaxerror: missing variable namesyntaxerror: missing } after function bodysyntaxerror: missing } after property listsyntaxerror: redeclaration of formal parameter "x"syntaxerror: re
turn not in functionsyntaxerror: test for equality (==) mistyped as assignment (=)?syntaxerror: unterminated string literaltypeerror: "x" has no propertiestypeerror: "x" is (not) "y"typeerror: "x" is not a constructortypeerror: "x" is not a functiontypeerror: "x" is not a non-null objecttypeerror: "x" is read-onlytypeerror: 'x' is not iterabletypeerror: more arguments neededtypeerror: reduce of empty ...
...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
const obja = { method() {} } new obja.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.entries() - JavaScript
the entries() method re
turns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax array.entries() re
turn value a new array iterator object.
Array.prototype.keys() - JavaScript
the keys() method re
turns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() re
turn value a new array iterator object.
Array.of() - JavaScript
re
turn value a new array instance.
... 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.push() - JavaScript
the push() method adds one or more elements to the end of an array and re
turns the new length of the array.
... re
turn value the new length property of the object upon which the method was called.
Array.prototype.unshift() - JavaScript
the unshift() method adds one or more elements to the beginning of an array and re
turns the new length of the array.
... re
turn value the new length property of the object upon which the method was called.
Array.prototype.values() - JavaScript
the values() method re
turns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() re
turn value a new array iterator object.
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.
... re
turn value a new arraybuffer object.
Atomics.isLockFree() - JavaScript
it re
turns true, if the given size is one of the bytes_per_element property of integer typedarray types.
... re
turn value a boolean indicating whether the operation is lock free.
Atomics.load() - JavaScript
the static atomics.load() method re
turns a value at a given position in the array.
... re
turn value the value at the given position (typedarray[index]).
Atomics.store() - JavaScript
the static atomics.store() method stores a given value at the given position in the array and re
turns that value.
... re
turn value the value that has been stored.
BigInt.prototype.valueOf() - JavaScript
the valueof() method re
turns the wrapped primitive value of a bigint object.
... syntax bigintobj.valueof() re
turn value a bigint representing the primitive value of the specified bigint object.
Boolean.prototype.valueOf() - JavaScript
the valueof() method re
turns the primitive value of a boolean object.
... 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.
Boolean - JavaScript
instance methods boolean.prototype.tostring() re
turns a string of either true or false depending upon the value of the object.
... boolean.prototype.valueof() re
turns the primitive value of the boolean object.
DataView() constructor - JavaScript
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.
Date() constructor - JavaScript
if you simply call the date object directly, such as now = date(), the re
turned value is a string rather than a date object.
... 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.
Date.prototype.getDate() - JavaScript
the getdate() method re
turns the day of the month for the specified date according to local time.
... syntax dateobj.getdate() re
turn value an integer number, between 1 and 31, representing the day of the month for the given date according to local time.
Date.prototype.getDay() - JavaScript
the getday() method re
turns the day of the week for the specified date according to local time, where 0 represents sunday.
... 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.
Date.prototype.getHours() - JavaScript
the gethours() method re
turns the hour for the specified date, according to local time.
... syntax dateobj.gethours() re
turn value an integer number, between 0 and 23, representing the hour for the given date according to local time.
Date.prototype.getMilliseconds() - JavaScript
the getmilliseconds() method re
turns the milliseconds in the specified date according to local time.
... syntax dateobj.getmilliseconds() re
turn value a number, between 0 and 999, representing the milliseconds for the given date according to local time.
Date.prototype.getMinutes() - JavaScript
the getminutes() method re
turns the minutes in the specified date according to local time.
... syntax dateobj.getminutes() re
turn value an integer number, between 0 and 59, representing the minutes in the given date according to local time.
Date.prototype.getMonth() - JavaScript
the getmonth() method re
turns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).
... syntax dateobj.getmonth() re
turn value an integer number, between 0 and 11, representing the month in the given date according to local time.
Date.prototype.getSeconds() - JavaScript
the getseconds() method re
turns the seconds in the specified date according to local time.
... syntax dateobj.getseconds() re
turn value an integer number, between 0 and 59, representing the seconds in the given date according to local time.
Date.prototype.getTime() - JavaScript
the gettime() method re
turns the number of milliseconds* since the unix epoch.
... syntax dateobj.gettime() re
turn value a number representing the milliseconds elapsed between 1 january 1970 00:00:00 utc and the given date.
Date.prototype.getUTCDate() - JavaScript
the getutcdate() method re
turns the day (date) of the month in the specified date according to universal time.
... syntax dateobj.getutcdate() re
turn value an integer number, between 1 and 31, representing the day of the month in the given date according to universal time.
Date.prototype.getUTCDay() - JavaScript
the getutcday() method re
turns the day of the week in the specified date according to universal time, where 0 represents sunday.
... syntax dateobj.getutcday() re
turn value an integer number corresponding to the day of the week for the given date, according to universal time: 0 for sunday, 1 for monday, 2 for tuesday, and so on.
Date.prototype.getUTCHours() - JavaScript
the getutchours() method re
turns the hours in the specified date according to universal time.
... syntax dateobj.getutchours() re
turn value an integer number, between 0 and 23, representing the hours in the given date according to universal time.
Date.prototype.getUTCMilliseconds() - JavaScript
the getutcmilliseconds() method re
turns the milliseconds portion of the time object's value.
... syntax dateobj.getutcmilliseconds() re
turn value an integer number, between 0 and 999, representing the milliseconds portion of the given date object.
Date.prototype.getUTCMinutes() - JavaScript
the getutcminutes() method re
turns the minutes in the specified date according to universal time.
... syntax dateobj.getutcminutes() re
turn value an integer number, between 0 and 59, representing the minutes in the given date according to universal time.
Date.prototype.getUTCMonth() - JavaScript
the getutcmonth() re
turns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).
... 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.
Date.prototype.getUTCSeconds() - JavaScript
the getutcseconds() method re
turns the seconds in the specified date according to universal time.
... syntax dateobj.getutcseconds() re
turn value an integer number, between 0 and 59, representing the seconds in the given date according to universal time.
Date.prototype.setMinutes() - JavaScript
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.
Date.prototype.setSeconds() - JavaScript
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.
Date.prototype.setUTCFullYear() - JavaScript
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.
Date.prototype.setUTCMinutes() - JavaScript
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.
Date.prototype.setUTCMonth() - JavaScript
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.
Date.prototype.setUTCSeconds() - JavaScript
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.
Error - JavaScript
instance methods error.prototype.tostring() re
turns a string representing the specified object.
... function customerror(foo, message, filename, linenumber) { var instance = new error(message, filename, linenumber); instance.name = 'customerror'; instance.foo = foo; object.setprototypeof(instance, object.getprototypeof(this)); if (error.capturestacktrace) { error.capturestacktrace(instance, customerror); } re
turn instance; } customerror.prototype = object.create(error.prototype, { constructor: { value: error, enumerable: false, writable: true, configurable: true } }); if (object.setprototypeof){ object.setprototypeof(customerror, error); } else { customerror.__proto__ = error; } try { throw new customerror('baz', 'bazmessage'); } catch(e){ console.error(e.name); //customerro...
Function.arguments - JavaScript
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.
Function.displayName - JavaScript
the function.displayname property re
turns the display name of the function.
... by entering the following in a console, it should display as something like "function my function()": var a = function() {}; a.displayname = 'my function'; a; // "function my function()" when defined, the displayname property re
turns the display name of a function: function dosomething() {} console.log(dosomething.displayname); // "undefined" var popup = function(content) { console.log(content); }; popup.displayname = 'show popup'; console.log(popup.displayname); // "show popup" defining a displayname in function expressions you can define a function with a display name in a function expression: var object = { somemethod: function() {} }; object...
Intl.Collator.prototype.resolvedOptions() - JavaScript
the intl.collator.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and collation options computed during initialization of this collator object.
... 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.
Intl.Collator - JavaScript
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.
... intl.collator.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and collation options computed during initialization of the object.
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
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(fmt.formatrange(date1, date2)); // > '10:00 – 11:00 am' fmt.formatrangetoparts(date1, date2); // re
turn value: // [ // { type: 'hour', value: '10', source: "startrange" }, // { type: 'literal', value: ':', source: "startrange" }, // { type: 'minute', value: '00', source: "startrange" }, // { type: 'literal', value: ' – ', source: "shared" }, // { type: 'hour', value: '11', source: "endrange" }, // { type: 'literal', value: ':', source: "endrange" }, // { typ...
Intl.DisplayNames.prototype.of() - JavaScript
the of() method receives a code and re
turns a string based on the locale and options provided when instantiating intl.displaynames.
... re
turn value a language-specific formatted string.
Intl​.ListFormat.prototype​.format() - JavaScript
the format() method re
turns a string with a language-specific representation of the list.
... syntax listformat.format([list]); parameters list an iterable object, such as an array re
turn value a language-specific formatted string representing the elements of the list description the format() method re
turns a string that has been formatted based on parameters provided in the intl.listformat object.
Intl.Locale.prototype.calendar - JavaScript
the intl.locale.prototype.calendar property is an accessor property which re
turns the type of calendar used in the locale.
... description the calendar property re
turns the part of the locale that indicates the locale's calendar era.
Intl.Locale.prototype.language - JavaScript
the intl.locale.prototype.language property is an accessor property that re
turns the language associated with the locale.
...the language property of a locale re
turns strictly the locale's language subtag.
Intl.Locale.prototype.maximize() - JavaScript
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.
...for instance, given the language id "en", the algorithm would re
turn "en-latn-us", since english can only be written in the latin script, and is most likely to be used in the united states, as it is the largest english-speaking country in the world.
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.
... 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.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
the intl.pluralrules.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and plural formatting options computed during initialization of this pluralrules object.
... syntax pluralrule.resolvedoptions() re
turn value a new object with properties reflecting the locale and plural formatting options computed during the initialization of the given pluralrules object.
Intl.PluralRules.select() - JavaScript
the intl.pluralrules.prototype.select method re
turns a string indicating which plural rule to use for locale-aware formatting.
... re
turn value a string representing the pluralization category of the number, can be one of zero, one, two, few, many or other.
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.
... 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.
Intl.getCanonicalLocales() - JavaScript
the intl.getcanonicallocales() method re
turns an array containing the canonical locale names.
... re
turn value an array containing the canonical locale names.
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.
... syntax mymap.entries() re
turn value a new map iterator object.
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.
... syntax mymap.keys() re
turn value a new map iterator object.
Map.prototype.set() - JavaScript
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.
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.
... syntax mymap.values() re
turn value a new map iterator object.
Math.exp() - JavaScript
the math.exp() function re
turns ex, where x is the argument, and e is euler's number (also known as napier's constant), the base of the natural logarithms.
... re
turn value a number representing ex, where e is euler's number and x is the argument.
Math.round() - JavaScript
the math.round() function re
turns the value of a number rounded to the nearest integer.
... re
turn value the value of the given number rounded to the nearest integer.
NaN - JavaScript
there are five different types of operations that re
turn nan: number cannot be parsed (e.g.
... 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'); /...
Number.NEGATIVE_INFINITY - JavaScript
you might use the number.negative_infinity property to indicate an error condition that re
turns a finite number in case of success.
... 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
you might use the number.positive_infinity property to indicate an error condition that re
turns a finite number in case of success.
... 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
re
turn value a boolean indicating whether or not the given value is a number that is a safe integer.
... polyfill number.issafeinteger = number.issafeinteger || function (value) { re
turn number.isinteger(value) && math.abs(value) <= number.max_safe_integer; }; examples using issafeinteger number.issafeinteger(3); // true number.issafeinteger(math.pow(2, 53)); // false number.issafeinteger(math.pow(2, 53) - 1); // true number.issafeinteger(nan); // false number.issafeinteger(infinity); // false number.issafeinteger('3'); // false number.issafeinteger(3.1); // false number.issafeinteger(3.0); // true specifications specification ecmascript (ecma-262)the definition of 'number.issafeinteger' in that specification.
Number.prototype.toExponential() - JavaScript
the toexponential() method re
turns a string representing the number object in exponential notation.
... 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.
Number.prototype.valueOf() - JavaScript
the valueof() method re
turns the wrapped primitive value of a number object.
... syntax numobj.valueof() re
turn value a number representing the primitive value of the specified number object.
Object.prototype.__defineGetter__() - JavaScript
re
turn value undefined.
... 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.is() - JavaScript
re
turn value a boolean indicating whether or not the two arguments are the same value.
... polyfill if (!object.is) { object.is = function(x, y) { // samevalue algorithm if (x === y) { // steps 1-5, 7-10 // steps 6.b-6.e: +0 != -0 re
turn x !== 0 || 1 / x === 1 / y; } else { // step 6.a: nan == nan re
turn x !== x && y !== y; } }; } examples using object.is object.is('foo', 'foo'); // true object.is(window, window); // true object.is('foo', 'bar'); // false object.is([], []); // false var foo = { a: 1 }; var bar = { a: 1 }; object.is(foo, foo); // true object.is(foo, bar); ...
Object.isExtensible() - JavaScript
re
turn value a boolean indicating whether or not the given object is extensible.
...in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply re
turn false.
handler.apply() - JavaScript
re
turn value the apply() method can re
turn any value.
... 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.
handler.deleteProperty() - JavaScript
re
turn value the deleteproperty() method must re
turn a boolean indicating whether or not the property has been successfully deleted.
... 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 ...
Proxy() constructor - JavaScript
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
re
turn value a newly created revocable proxy object is re
turned.
... examples using proxy.revocable var revocable = proxy.revocable({}, { get: function(target, name) { re
turn "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke(); console.log(proxy.foo); // typeerror is thrown proxy.foo = 1 // typeerror again delete proxy.foo; // still typeerror typeof proxy // "object", typeof doesn't trigger any trap specifications specification ecmascript (ecma-262)the de...
Reflect.get() - JavaScript
re
turn value the value of the property.
... 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 let x = {p: 1}; let obj = new proxy(x, { get(t, k, r) { re
turn k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //proxy with get handler and receiver let x = {p: 1, foo: 2}; let y = {foo: 3}; let obj = new proxy(x, { get(t, prop, receiver) { re
turn receiver[prop] + 'bar' } }) reflect.get(obj, 'foo', y) // "3bar" specifications specification ecmascript (ecma-262)the definition of 'reflect.get' in that specification.
Reflect.has() - JavaScript
re
turn value a boolean indicating whether or not the target has the property.
... 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 ...
RegExp.prototype.flags - JavaScript
the flags property re
turns a string consisting of the flags of the current regular expression object.
... 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.
RegExpInstance.lastIndex - JavaScript
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.
SharedArrayBuffer.prototype.slice() - JavaScript
the sharedarraybuffer.prototype.slice() method re
turns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive.
... re
turn value a new sharedarraybuffer containing the extracted elements.
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.
... syntax str[symbol.iterator] re
turn value a new iterator object.
String.prototype.matchAll() - JavaScript
the matchall() method re
turns an iterator of all results matching a string against a regular expression, including capturing groups.
... re
turn value an iterator (which is not a restartable iterable).
String.prototype.normalize() - JavaScript
the normalize() method re
turns the unicode normalization form of the string.
... re
turn value a string containing the unicode normalization form of the given string.
String.prototype.padEnd() - JavaScript
if the value is lower than str.length, the current string will be re
turned as-is.
... re
turn value a string of the specified targetlength with the padstring applied at the end of the current str.
String.prototype.trimEnd() - JavaScript
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.
Symbol.prototype[@@toPrimitive] - JavaScript
syntax symbol()[symbol.toprimitive](hint) re
turn value the primitive value of the specified symbol object.
... description the [@@toprimitive]() method of symbol re
turns the primitive value of a symbol object as a symbol data type.
Symbol.iterator - JavaScript
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.
... [1, 2, 3] or iterables can be defined directly inside a class or object using a computed property: class foo { *[symbol.iterator] () { yield 1; yield 2; yield 3; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } [...new foo] // [ 1, 2, 3 ] [...someobj] // [ 'a', 'b' ] non-well-formed iterables if an iterable's @@iterator method does not re
turn an iterator object, then it is a non-well-formed iterable.
Symbol.matchAll - JavaScript
the symbol.matchall well-known symbol re
turns an iterator, that yields matches of the regular expression against a string.
...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.
Symbol.search - JavaScript
the symbol.search well-known symbol specifies the method that re
turns the index within a string that matches the regular expression.
... 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.
Symbol.toStringTag - JavaScript
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'); 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.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.
... syntax arr.entries() re
turn value a new array iterator object.
TypedArray.prototype.keys() - JavaScript
the keys() method re
turns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() re
turn value a new array iterator object.
TypedArray.prototype.map() - JavaScript
re
turn value a new 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.subarray() - JavaScript
the subarray() method re
turns a new typedarray on the same arraybuffer store and with the same element types as for this typedarray object.
... re
turn value a new typedarray object.
TypedArray.prototype.values() - JavaScript
the values() method re
turns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() re
turn value a new array iterator object.
WeakRef.prototype.deref() - JavaScript
the deref method re
turns the weakref instance's target object, or undefined if the target object has been garbage-collected.
... syntax obj = ref.deref(); re
turn value the target object of the weakref, or undefined if the object has been garbage-collected.
WebAssembly.Memory() constructor - JavaScript
its buffer property will re
turn an arraybuffer.
...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.
WebAssembly.Memory.prototype.grow() - JavaScript
re
turn value the previous size of the memory, in units of webassembly pages.
... 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.
WebAssembly.Module.imports() - JavaScript
the webassembly.imports() function re
turns an array containing descriptions of all the declared imports of the given module.
... re
turn value an array containing objects representing the imported functions of the given module.
WebAssembly.Table.prototype.set() - JavaScript
re
turn value void.
...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).
WebAssembly.Table - JavaScript
instance properties table.prototype.length re
turns the length of the table, i.e.
... 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).
WebAssembly.instantiateStreaming() - JavaScript
re
turn value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module.
... note: for this to work, .wasm files should be re
turned with an application/wasm mime type by the server.
WebAssembly.validate() - JavaScript
the webassembly.validate() function validates a given typed array of webassembly binary code, re
turning whether the bytes form a valid wasm module (true) or not (false).
... re
turn value a boolean that specifies whether buffersource is valid wasm code (true) or not (false).
decodeURIComponent() - JavaScript
re
turn value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component.
... function decodequeryparam(p) { re
turn decodeuricomponent(p.replace(/\+/g, ' ')); } decodequeryparam('search+query%20%28correct%29'); // 'search query (correct)' specifications specification ecmascript (ecma-262)the definition of 'decodeuricomponent' in that specification.
encodeURI() - JavaScript
re
turn value a new string representing the provided string encoded as a uri.
...d800')); // lone low surrogate throws "urierror: malformed uri sequence" console.log(encodeuri('\udfff')); encoding for ipv6 if one wishes to follow the more recent rfc3986 for urls, which makes square brackets reserved (for ipv6) and thus not encoded when forming something which could be part of a url (such as a host), the following code snippet may help: function fixedencodeuri(str) { re
turn encodeuri(str).replace(/%5b/g, '[').replace(/%5d/g, ']'); } specifications specification ecmascript (ecma-262)the definition of 'encodeuri' in that specification.
isFinite() - JavaScript
re
turn value false if the argument is positive or negative infinity or nan or undefined; otherwise, true.
...if the argument is nan, positive infinity, or negative infinity, this method re
turns false; otherwise, it re
turns true.
undefined - JavaScript
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.
Standard built-in objects - JavaScript
standard objects by category value properties these global properties re
turn a simple value.
... 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.
Conditional (ternary) operator - JavaScript
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 ?
...value3 : value4; } // equivalent to: function example(…) { if (condition1) { re
turn value1; } else if (condition2) { re
turn value2; } else if (condition3) { re
turn value3; } else { re
turn value4; } } specifications specification ecmascript (ecma-262)the definition of 'conditional operator' in that specification.
Less than (<) - JavaScript
the less than operator (<) re
turns true if the left operand is less than the right operand, and false otherwise.
... if either value is nan, the operator re
turns false.
Object initializer - JavaScript
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 __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.
Unsigned right shift (>>>) - JavaScript
unlike the other bitwise operators, zero-fill right shift re
turns an unsigned 32-bit integer.
...unlike the other bitwise operators, zero-fill right shift re
turns an unsigned 32-bit integer.
async function expression - JavaScript
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 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.
Function expression - JavaScript
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 function re
turns the square of its argument: var x = function(y) { re
turn y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is created and called: (function() { console.log('code runs!') })(); specifica...
super - JavaScript
class rectangle { constructor(height, width) { this.name = 'rectangle'; this.height = height; this.width = width; } sayname() { console.log('hi, i am a ', this.name + '.'); } get area() { re
turn this.height * this.width; } set area(value) { this._area = value; } } class square extends rectangle { constructor(length) { this.height; // referenceerror, super needs to be called first!
... 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 r...
continue - JavaScript
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.
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...
... using the default export if we want to export a single value or to have a fallback value for your module, you could use a default export: // module "my-module.js" export default function cube(x) { re
turn x * x * x; } then, in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) t...
for...in - JavaScript
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.
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.
...} 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.
import - JavaScript
you need to destructure and rename the "default" key from the re
turned object.
...when used this way, it re
turns a promise.
JavaScript typed arrays - JavaScript
however, typed arrays are not to be confused with normal arrays, as calling array.isarray() on a typed array re
turns false.
...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.
Web video codec guide - Web media technologies
eventually the point of diminishing re
turns is reached.
... 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 "codecs" parameter in common media types - Web media technologies
these coefficients are in
turn used with the equations found in that same section.
... 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
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.
...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.
Understanding latency - Web Performance
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.
... disk latency is the time it takes from the moment a computer, usually a server, receives a request, to the time the computer re
turns the response.
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...
...n(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-cyberspace', name: 'lost in cyberspace', author: 'zosia and bartek', twitter: 'bartaz', website: '', github: 'github.com/bartaz/lost-in-cyberspace' }, { slug: 'vernissage', name: 'vernissage', author: 'platane', twitter: 'platane_', website: 'github.com/platane', github: 'github.co...
The building blocks of responsive design - Progressive web apps (PWAs)
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.
...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.
Structural overview of progressive web apps - Progressive web apps (PWAs)
self.addeventlistener('install', function(e) { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then(function(cache) { console.log('[service worker] caching all: app shell and content'); re
turn cache.addall(contenttocache); }) ); }); with 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 w...
...orker] 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 javascript source file called games.js.
rotate - SVG: Scalable Vector Graphics
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.
shape-rendering - SVG: Scalable Vector Graphics
this option will sometimes cause the user agent to
turn off shape anti-aliasing.
...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.
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...
... implementation status unknown auto as initial value for width and height attributes of <svg> implementation status unknown baseprofile and version attributes removed from <svg> implementation status unknown svgsvgelement.forceredraw() deprecated
turned into a no-op (bug 733764) svgsvgelement.deselectall() deprecated not yet deprecated (bug 1302705) <switch> not affecting <style> implementation status unknown requiredfeatures attribute removed implementation status unknown svgsvgelement.currentview and svgsvgelement.usecurrentview removed svgsvgelement.currentview was never implemented, svgsvgele...
boolean - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the boolean function evaluates an expression and re
turns true or false.
... re
turns boolean true or false after evaluating expression.
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.
... re
turns the nearest integer greater than or equal to number.
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.
... re
turns a single string that is the concatenation of all the strings passed to the function as arguments.
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.
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.
... re
turns an integer representing the number of nodes in a node-set.
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.
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.
... re
turns the nearest integer less than or equal to number.
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.
... re
turns a string representing the number in the new format.
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.
... re
turns boolean true or false.
generate-id - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the generate-id function generates a unique id for the first node in a given node-set and re
turns a string containing that id.
... re
turns a string containing the generated id.
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.
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.
... re
turns the normalized string.
number - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the number function converts an object to a number and re
turns the number.
... re
turns the resulting number after converting the object.
position - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the position function re
turns a number equal to the context position from the expression evaluation context.
... syntax position() re
turns an integer equal to the context position from the expression evaluation context.
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.
... re
turns the nearest integer less then, greater than, or equal todecimal.
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.
... re
turns true if haystack starts with needle.
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.
... re
turns an integer equal to the number of characters in the string.
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.
... re
turns the translated string.
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.
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.
... re
turns the uri of the unparsed entity retrieved from the dtd, if it exists.
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
transformtodocument xsltprocessor.transformtodocument() takes one argument, the source node to transform, and re
turns a new document with the results of the transformation: var newdocument = processor.transformtodocument(domtobetransformed); the resultant object depends on the output method of the stylesheet: html - htmldocument xml - xmldocument text - xmldocument with a single root element <transformiix:result> with the text as a child transformtofragment you can also use xsltprocessor.transformtof...
...ragment() which will re
turn a documentfragment node.
Loading and running WebAssembly code - WebAssembly
}); aside on instantiate() overloads the webassembly.instantiate() function has two overload forms — the one shown above takes the byte code to compile as an argument and re
turns a promise that resolves to an object containing both the compiled module object, and an instantiated instance of it.
... 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.
Cross-domain Content Scripts - Archive of obsolete content
f.port.on("show", function () { var request = new xmlhttprequest(); request.open("get", url, true); request.onload = function () { var jsonresponse = json.parse(request.responsetext); var summary = getsummary(jsonresponse); var element = document.getelementbyid("forecast_summary"); element.textcontent = summary; }; request.send(); }); function getsummary(forecast) { re
turn forecast.regionalfcst.fcstperiods.period[0].paragraph[0].$; } finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } content permissions and unsafewindow if you use "cross-domain-content", then javascript values in content scripts will not be available from pages.
Content Scripts - Archive of obsolete content
ent.target.tostring()); event.stoppropagation(); event.preventdefault(); }, false); self.port.on('warning', function(message) { window.alert(message); }); in the add-on above there are two messages: click is sent from the page-mod to the add-on, when the user clicks an element in the page warning sends a silly string back to the page-mod from tab.attach() the tab.attach() method re
turns the worker you can use to communicate with the content script(s) you attached.
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...
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/...
Customizing the download progress bar - Archive of obsolete content
mydownloadmanager.defaultcreatedownloaditem = window.createdownloaditem; window.createdownloaditem = function(aattrs) { var dl = mydownloadmanager.defaultcreatedownloaditem(aattrs); if (dl) { if (...whatever condition you use to decide whether to change this download...) { dl.setattribute("myspecialdownload", "true"); } } re
turn dl; } } }; window.addeventlistener("load", function(e) { mydownloadmanager.init(); }, false); in your css file, change richdownloaditem (both occurrences) to richdownloaditem[myspecialdownload="true"].
Progress Listeners - Archive of obsolete content
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...
SVG General - Archive of obsolete content
attr_map[attribute] : attribute); var value = attributes[attribute]; if (attribute in ns_map) elem.setattributens(ns_map[attribute], name, value); else elem.setattribute(name, value); } re
turn elem; } attributes are packed in a literal object and the helper script unpacks them and adds them to the element.
Tree - Archive of obsolete content
= document.getelementbyid("my-tree"); var cellindex = 0; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getelementbyid("my-tree").view; var sel = view.selection.currentindex; //re
turns -1 if the tree is not focused var treeitem = view.getitematindex(sel); note that the current index may be unselected (for example, a multi-select tree).
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;...
Common Pitfalls - Archive of obsolete content
s_error_malformed_uri for some applications } c++: nsresult rv; nscomptr<nsiioservice> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->newuri(uristring, uricharset, baseuri, getter_addrefs(uriobj)); if (ns_failed(rv)) { // may want to handle ns_error_malformed_uri for // some applications re
turn rv; } or, if the code can include nsnetutil.h: nscomptr<nsiuri> uriobj; nsresult rv = ns_newuri(getter_addrefs(uriobj), uristring, uricharset, baseuri); in all cases the baseuri can be null if the uristring should be treated as an absolute uri and uricharset can be null if there is no clear origin charset for the string (e.g.
Displaying web content in an extension without security issues - Archive of obsolete content
this can be done as well, by placing the event handler on the frame tag (meaning that it is outside the restricted document and can execute without restrictions): <iframe type="content" onclick="handleclick(event);"/> and the event handler would look like that: function handlebrowserclick(event) { // only react to left mouse clicks if (event.button != 0) re
turn; // default action on link clicks is to go to this link, cancel it event.preventdefault(); if (event.target instanceof htmlanchorelement && event.target.href) openlinkinbrowser(event.target.href); } safe html manipulation functions when it comes to displaying the data, it is tempting to generate some html code and to insert it into the document via innerhtml.
Hiding browser chrome - Archive of obsolete content
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.
Install Manifests - Archive of obsolete content
<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.
Listening to events in Firefox extensions - Archive of obsolete content
it is used to update the ui for many different reasons: update the progress bar and status messages as pages load
turn on and off the throbber as pages load set the site icon when available update the address bar as the user navigates hide notification bars when appropriate as the user navigates apply the site zoom preferences to newly loading pages update the bookmarking star button ui update the identity display as the site's security changes tabsprogresslistener this object is a tabs progress listener...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
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.
Handling Preferences - Archive of obsolete content
get count() { re
turn this._prefservice.getintpref("extensions.xulschoolhello.message.count"); }, increment : function() { let currentcount = this._prefservice.getintpref("extensions.xulschoolhello.message.count"); this._prefservice.setintpref("extensions.xulschoolhello.message.count", currentcount + 1); } one important thing to keep in mind is that the "get" methods of the service can throw an exception i...
Signing an XPI - Archive of obsolete content
-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.
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...
Chromeless - Archive of obsolete content
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.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
ile(file, "components"); } } else if (aprop.equals("mozbind") || aprop.equals("curprocd") || aprop.equals("comsd") || aprop.equals("profd")) { 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.
Abc Assembler Tests - Archive of obsolete content
* * ***** end license block ***** */ function main() { getlocal0 pushscope findproperty start pushstring "instructions that start with the letter l" callpropvoid start 1 newfunction .function_id(runtest) getlocal0 call 0 findproperty end callpropvoid end 0 re
turnvoid } function runtest() { // test null <= null == true findproperty compare_stricteq pushstring "null lessequals null" // testname pushtrue // expected pushnull pushnull lessequals // actual callpropvoid compare_stricteq 3 // use .try / .catch to catch typeerror // convert_o null .try { pushnull convert_o pop findprop...
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...
Running Tamarin performance tests - Archive of obsolete content
e phone the executable must be 'avmshell' $ adb push avmshell /data/app/avmshell $ adb shell chmod 777 /data/app/avmshell copy android_runner.sh, if it doesn't already exist on the phone in /data/app $ adb push tamarin-redux/platform/android/android_runner.sh /data/app/android_runner.s $ adb shell chmod 777 /data/app/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.h hello.abc hello exitcode=0 running performance tests to run performance tests on android you don't need to pass --androidthreads or --threads=1 as with the acceptance tests; in fact, a usage error will result.
Tamarin build documentation - Archive of obsolete content
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.
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
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.
Tuning Pageload - Archive of obsolete content
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.
Venkman Introduction - Archive of obsolete content
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.
File.macAlias - Archive of obsolete content
xpisrc = "miscellaneous program"; var vi = "1.1.1.1"; initinstall( "macintosh alias", "misc", vi, 0); f = getfolder("program"); g = getfolder("mac desktop"); addfile( "filemacalias", "2.2.2.2", xpisrc, f, xpisrc, true); err = file.macalias(f, xpisrc, g, xpisrc + " alias"); logcomment("file.macalias re
turns: " + err); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
loadTabs - Archive of obsolete content
« xul reference home loadtabs( uris, loadinbackground, replace ) loadtabs( uris, params ) re
turn type: no re
turn value loads a set of uris, specified by the array uris, into tabs.
loadURI - Archive of obsolete content
(this one has no post data parameter, see loaduriwithflags for a version that does) loaduri( uri, referrer, charset ) re
turn type: no re
turn value load a url into the document, with the given referrer and character set.
loadURIWithFlags - Archive of obsolete content
« xul reference home loaduriwithflags( uri, flags, referrer, charset, postdata ) re
turn type: no re
turn value load a url into the document, with the specified load flags, the given referrer, character set, and post data.
moveByOffset - Archive of obsolete content
« xul reference home movebyoffset( offset , isselecting, isselectingrange) re
turn type: no re
turn value if offset is positive, adjusts the focused item forward by that many items.
moveTo - Archive of obsolete content
« xul reference home moveto( x, y ) re
turn type: no re
turn value moves the popup to a new location defined by screen coordinates (and not client coordinates).
More Event Handlers - Archive of obsolete content
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.
More Menu Features - Archive of obsolete content
the example below demonstrates this: example 3 : source view <toolbox> <menubar id="planets-menubar"> <menu id="planet-menu" label="planet"> <menupopup> <menuitem id="jupiter" label="jupiter" type="radio" name="ringed"/> <menuitem id="sa
turn" label="sa
turn" type="radio" name="ringed" checked="true"/> <menuitem id="uranus" label="uranus" type="radio" name="ringed"/> <menuseparator/> <menuitem id="earth" label="earth" type="radio" name="inhabited" checked="true"/> <menuitem id="moon" label="moon" type="radio" name="inhabited"/> </menupopup> </menu> </menubar> </toolbox> if you try this examp...
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 ...
XUL Parser in Python/source - Archive of obsolete content
def strip(snip): t = re.sub('http://.*?\s', '', snip) re
turn t class xulparser(xmllib.xmlparser): def unknown_starttag(self, t, a): name = strip(t) if name not in el_list: el_list[name] = {} for attr,val in a.items(): el_list[name][strip(attr)] = strip(val) def syntax_error(self, message): pass p = xulparser() cmd = 'dir /s /b *.xul' chrome_dir = 'c:\program files\netscape\netscape 6\chrome' os.chdir(chrome_dir) files = os.popen(cmd).readlines() for file i...
XUL controls - Archive of obsolete content
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.
assign - Archive of obsolete content
for more information, see xml_assignments attributes expr, var examples (example needed) attributes expr type: string for xml queries, an xpath expression which re
turns results.
notification - Archive of obsolete content
schildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), 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.
toolbargrippy - Archive of obsolete content
rtafter, 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.
Application Update - Archive of obsolete content
anding the update process uses branding information, setup branding for your application as described here: xulrunner tips icons the updater process for linux systems requires updater.png to be in your <application folder>/icons/, see https://bugzilla.mozilla.org/show_bug.cgi?id=706846 preferences // whether or not app updates are enabled pref("app.update.enabled", true); // this preference
turns on app.update.mode and allows automatic download and // install to take place.
Deploying XULRunner - Archive of obsolete content
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.
XULRunner tips - Archive of obsolete content
; pref("browser.download.manager.opendelay", 0); pref("browser.download.manager.focuswhenstarting", false); pref("browser.download.manager.flashcount", 2); // pref("alerts.slideincrement", 1); pref("alerts.slideincrementtime", 10); pref("alerts.totalopentime", 4000); pref("alerts.height", 50); if you are missing preferences that a dialog requires, you will get the following errors: component re
turned failure code: 0x8000ffff (ns_error_unexpected) [nsiprefbranch.getboolpref] error: dialog has no properties source file: chrome://mozapps/content/downloads/u...ontenttype.xul line: 1 enabling password manager these preferences seem to be the default in firefox, however, they are missing in xulrunner.
calICalendarViewController - Archive of obsolete content
related interfaces calicalendarview calidecoratedview example code var myviewcontroller = { queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.calicalendarviewcontroller) && !aiid.equals(components.interfaces.nsisupports)) { throw components.results.ns_error_no_interface; } re
turn this; }, createnewevent: function (acalendar, astarttime, aendtime) { // if we're given both times, skip the dialog if (astarttime && aendtime && !astarttime.isdate && !aendtime.isdate) { var event = createevent(); event.startdate = astarttime; event.enddate = aendtime; event.title = "new event"; acalendar.addite...
2006-10-06 - Archive of obsolete content
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.
2006-11-10 - Archive of obsolete content
t on fc3 with the following options: ./configure --enable-application=browser --prefix=$prefix --enable-extensions=default,spatialnavigation then he tried running "make" and received the following error: /usr/bin/ld: testtarray.o(.text+0x2237): unresolvable relocation against symbol `nstarray_base::semptyhdr' /usr/bin/ld: final link failed: nonrepresentable section on output collect2: ld re
turned 1 exit status gmake[3]: *** [testtarray] error 1 gmake[3]: leaving directory `/usr/mozilla2/src/mozilla/xpcom/tests' gmake[2]: *** [libs] error 2 gmake[2]: leaving directory `/usr/mozilla2/src/mozilla/xpcom' gmake[1]: *** [tier_2] error 2 gmake[1]: leaving directory `/usr/mozilla2/src/mozilla' make: *** [default] error 2 he is not sure what is wrong with his build, and is asking for help on h...
2006-11-24 - Archive of obsolete content
"component re
turned failure code: 0x80570016 (ns_error_xpc_gs_re
turned_failure) [nsijscid.getservice]" nsresult: "0x80570016 (ns_error_xpc_gs_re
turned_failure)" location: "js frame :: chrome://modzilla/content/js/pkg_zillacom.js :: <top_level> :: line 1202" data: no] he is running xulrunner v1.8.0.4.
Scratchpad - Archive of obsolete content
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.
Using workers in extensions - Archive of obsolete content
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.
::-ms-fill - Archive of obsolete content
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.
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...
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.
Enumerator.moveFirst - Archive of obsolete content
s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } re
turn(s); } 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 internet explorer 10 standards.
Enumerator.moveNext - Archive of obsolete content
s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } re
turn(s); } 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 internet explorer 10 standards.
forEach - Archive of obsolete content
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().
Writing JavaScript for XHTML - Archive of obsolete content
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.
Popup Window Controls - Archive of obsolete content
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.
XQuery - Archive of obsolete content
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.
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...
Bounding volume collision detection with THREE.js - Game development
e of vector3 on every check three.sphere.__closest = new three.vector3(); three.sphere.prototype.intersectsbox = function (box) { // get box closest point to sphere center by clamping three.sphere.__closest.set(this.center.x, this.center.y, this.center.z); three.sphere.__closest.clamp(box.min, box.max); var distance = this.center.distancetosquared(three.sphere.__closest); re
turn distance < (this.radius * this.radius); }; demos we have prepared some live demos to demonstrate these techniques, with source code to examine.
Tiles and tilemaps overview - Game development
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, h...
Build the brick field - Game development
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.
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
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.
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
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.
ICE - MDN Web Docs Glossary: Definitions of Web-related terms
the framework algorithm looks for the lowest-latency path for connecting the two peers, trying these options in order: direct udp connection (in this case—and only this case—a stun server is used to find the network-facing address of a peer) direct tcp connection, via the http port direct tcp connection, via the https port indirect connection via a relay/
turn server (if a direct connection fails, e.g., if one peer is behind a firewall that blocks nat traversal) learn more general knowledge webrtc, the principal web-related protocol which uses ice webrtc protocols technical reference rfc 5245, the ietf specification for ice rtcicecandidate, the interface representing a ice candidate ...
Parameter - MDN Web Docs Glossary: Definitions of Web-related terms
output/re
turn parameters primarily re
turn multiple values from a function, but not recommended since they cause confusion learn more general knowledge difference between parameter and argument on wikipedia technical reference function declaration function expression ...
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.
How CSS is structured - Learn web development
<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.
What are browser developer tools? - Learn web development
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.
HTML forms in legacy browsers - Learn web development
input { /* this rule
turns off the default rendering for the input types that have a border, including buttons defined with an input element */ border: 1px solid #ccc; } input[type="button"] { /* this does not restore the default rendering */ border: none; } input[type="button"] { /* these don't either!
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
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.
Sending form data - Learn web development
from flask import flask, render_template, request app = flask(__name__) @app.route('/', methods=['get', 'post']) def form(): re
turn render_template('form.html') @app.route('/hello', methods=['get', 'post']) def hello(): re
turn render_template('greeting.html', say=request.form['say'], to=request.form['to']) if __name__ == "__main__": app.run() the two templates referenced in the above code are as follows (these need to be in a subdirectory called templates in the same directory as the python-example.py file, if you ...
HTML table advanced features and accessibility - Learn web development
re
turning to our spending costs example, the previous two snippets could be rewritten like this: <thead> <tr> <th id="purchase">purchase</th> <th id="location">location</th> <th id="date">date</th> <th id="evaluation">evaluation</th> <th id="cost">cost (€)</th> </tr> </thead> <tbody> <tr> <th id="haircut">haircut</th> <td headers="location haircut">hairdresser</td> <td h...
Client-side web APIs - Learn web development
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.
Object building practice - Learn web development
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.
Ember resources and troubleshooting - Learn web development
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.
Beginning our React todo list - Learn web development
the jsx copy the following snippet to your clipboard, then paste it into app.js so that it replaces the existing app() function: function app(props) { re
turn ( <div classname="todoapp stack-large"> <h1>todomatic</h1> <form> <h2 classname="label-wrapper"> <label htmlfor="new-todo-input" classname="label__lg"> what needs to be done?
Focus management with Vue refs - Learn web development
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.
Cross browser testing - Learn web development
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.
Command line crash course - Learn web development
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").
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
both of these functions re
turn unique pointers and should be treated as opaque by the caller.
Theme concepts
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.
Adding a new CSS property
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.
Browser chrome tests
call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has re
turned.
Continuous Integration
each talos suite contains a set of tests or pages, some of these in
turn have sub-tests.
Creating a Login Manager storage module
getservice(ci.nsiconsoleservice); re
turn this.__logservice; }, log: function (message) { dump("sampleloginmanager: " + message + "\n"); this._logservice.logstringmessage("sampleloginmanager: " + message); }, // logs function name and arguments for debugging stub: function(arguments) { var args = []; for (let i = 0; i < arguments.length; i++) args.push(arguments[i]) this.log("called " + arguments.calle...
Debugging Frame Reflow
the display of the following frames can be
turned on by adding a line with the frame name and 1 or
turned off by adding a line with the frame name and 0: short name layout tag area area block block br br bullet bullet button gfxbuttoncontrol hr hr framei htmlframeinner ...
Debugging JavaScript
in extensions you can print the callstack using components.stack like this: function getstackdump() { var lines = []; for (var frame = components.stack; frame; frame = frame.caller) { lines.push(frame.filename + " (" + frame.linenumber + ")"); } re
turn lines.join("\n"); } see also debugging mozilla with gdb setting up an extension development environment (particularly development preferences and development extensions) original document information author(s): ben bucksch created date: september 12, 2005, last updated date: november 10, 2009 copyright information: portions of this content are © 1998–2007 by individual mozilla.or...
Debugging OpenGL
this flushes out each call, essentially
turning opengl into a synchronous api.
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
getid() on the *dummy* breakpoint appears to be re
turning # the breakpoint index instead of its id.
Debugging
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.
Configuring Build Options
you will see (diminishing) re
turns up to a value approximately 1.5× to 2.0× the number of cores on your system.
Makefiles - Best practices and suggestions
amps ts=.ts ##################################################### ## extra dep needed to synchronize parallel execution ##################################################### $(ts): $(ts)/.done $(ts)/.done: $(mkdir) -p $(dir $@) touch $@ # "clean" target garbage_dirs += $(ts) maintain clean targets - makefiles should be able to remove all content that is generated so "make clean" will re
turn the sandbox/directory back to a clean state.
Callgraph
for instance, given the c++ code: int foo() { re
turn good(); } int good() { re
turn evil() ?
Eclipse CDT
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.
Gecko Logging
debug 4 a debug message, useful for debugging but too verbose to be
turned on normally.
Deferred
a deferred object is re
turned by the promiseutils.defer() method to provide a new promise along with methods to change its state.
PromiseUtils.jsm
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.
Using JavaScript code modules
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.
JavaScript code modules
promiseworker.jsm a version of chromeworker which uses promises to re
turn the worker's result instead of using an event to do so.
L10n testing with xcode
the accessibility inspector remains active until you
turn it off, even if you quit and restart ios simulator.
Basics
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.
Mozilla Port Blocking
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 Style System Documentation
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").
BloatView
bytes per-inst - the number of bytes re
turned if you were to write sizeof(class).
GC and CC logs
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).
Profile Manager
ability to reset a profile (re
turn it to a default state excluding bookmarks and passwords).
PR_cnvtf
on re
turn, the result is written to the buffer pointed to by buf of size bufsz.
PR_htonl
re
turns the value of the conversion parameter in network byte order.
PR_htons
re
turns the value of the conversion parameter in network byte order.
PR_ntohl
re
turns the value of the conversion parameter in host byte order.
PR_ntohs
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...
CERT_FindCertByDERCert
re
turns a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found.
CERT_FindCertByIssuerAndSN
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.
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
one might expect the api defines a simple function that accepts the uri and data to be sent, and re
turns the result data.
HTTP delegation
one might expect the api defines a simple function that accepts the uri and data to be sent, and re
turns the result data.
JSS FAQ
ssl_getclientauthdatahook sets a callback to re
turn the local certificate for ssl client auth.
JSS 4.4.0 Release Notes
bugs fixed in jss 4.4.0 this bugzilla query re
turns all the bugs fixed in nss 4.4.0: https://bugzilla.mozilla.org/buglist.cgi?product=jss&target_milestone=4.4&target_milestone=4.4&bug_status=resolved&resolution=fixed documentation build instructions for jss at https://hg.mozilla.org/projects/jss/file/tip/readme platform information you can check out the source from mercurial via hg clone -r 055aa3ce8a61 https://hg.mozilla.org/projects/...
NSS_3.12.2_release_notes.html
valid session handle 0 bug 205434: fully implement new libpkix cert verification api from bug 294531 bug 302670: use the installed libz.so where available bug 305693: shlibsign generates pqg for every run bug 311483: exposing includecertchain as a parameter to sec_pkcs12addcertandkey bug 390527: get rid of pkixerrormsg variable in pkix_error bug 391560: libpkix does not consistently re
turn pkix_validatenode tree that truly represent failure reasons bug 408260: certutil usage doesn't give enough information about trust arguments bug 412311: replace pr_interval_no_wait with pr_interval_no_timeout in client initialization calls bug 423839: add multiple pkcs#11 token password command line option to nss tools.
NSS 3.12.6 release notes
new functions for sni (see ssl.h for more information): sslsnisocketconfig re
turn values: ssl_sni_current_config_is_used: libssl must use the default cert and key.
NSS 3.12.9 release notes
bug 536485: crash during ssl handshake in [@ intel_aes_decrypt_cbc_256] bug 444367: nss 3.12 softoken re
turns the certificate type of a certificate object as ckc_x_509_attr_cert.
NSS 3.14.1 release notes
bugs fixed in nss 3.14.1 the following bugzilla query re
turns all of the bugs fixed in nss 3.14.1: https://bugzilla.mozilla.org/buglist.cgi?list_id=5216669;resolution=fixed;query_format=advanced;bug_status=resolved;bug_status=verified;target_milestone=3.14.1;product=nss compatability nss 3.14.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.14 release notes
bugs fixed in nss 3.14 this bugzilla query re
turns all the bugs fixed in nss 3.14: https://bugzilla.mozilla.org/buglist.cgi?list_id=4643675;resolution=fixed;classification=components;query_format=advanced;product=nss;target_milestone=3.14 ...
NSS 3.15.3 release notes
bug 925100 - (cve-2013-1741) ensure a size is <= half of the maximum pruint32 value bug 934016 - (cve-2013-5605) handle invalid handshake packets bug 910438 - (cve-2013-5606) re
turn the correct result in cert_verifycert on failure, if a verifylog isn't used new in nss 3.15.3 new functionality no new major functionality is introduced in this release.
NSS 3.15.4 release notes
bug 919877 - (cve-2013-1740) when false start is enabled, libssl will sometimes re
turn unencrypted, unauthenticated data from pr_recv new in nss 3.15.4 new functionality implemented ocsp querying using the http get method, which is the new default, and will fall back to the http post method.
NSS 3.16.1 release notes
bugs fixed in nss 3.16.1 this bugzilla query re
turns all the bugs fixed in nss 3.16.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.16.1 ...
NSS 3.16.2 release notes
bugs fixed in nss 3.16.2 this bugzilla query re
turns all the bugs fixed in nss 3.16.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.16.2 ...
NSS 3.16.4 release notes
bugs fixed in nss 3.16.4 this bugzilla query re
turns all the bugs fixed in nss 3.16.4: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.16.4 ...
NSS 3.17.1 release notes
bugs fixed in nss 3.17.1 this bugzilla query re
turns all the bugs fixed in nss 3.17.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.1 acknowledgements the nss development team would like to thank antoine delignat-lavaud, security researcher at inria paris in team prosecco, and the advanced threat research team at intel security, who both independently...
NSS 3.17.2 release notes
bugs fixed in nss 3.17.2 this bugzilla query re
turns all the bugs fixed in nss 3.17.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.2 compatibility nss 3.17.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.17.4 release notes
bugs fixed in nss 3.17.4 this bugzilla query re
turns all the bugs fixed in nss 3.17.4: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.4 compatibility nss 3.17.4 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.17 release notes
bugs fixed in nss 3.17 this bugzilla query re
turns all the bugs fixed in nss 3.17: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17 ...
NSS 3.19.1 release notes
the minimum size of keys that nss will generate, import, or use has been raised: the minimum modulus size for rsa keys is now 512 bits the minimum modulus size for dsa keys is now 1023 bits the minimum modulus size for diffie-hellman keys is now 1023 bits bugs fixed in nss 3.19.1 this bugzilla query re
turns all the bugs fixed in nss 3.19.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.19.1 acknowledgements the nss development team would like to thank matthew green and karthikeyan bhargavan for responsibly disclosing the issue in bug 1138554.
NSS 3.19.2 release notes
bugs fixed in nss 3.19.2 this bugzilla query re
turns all the bugs fixed in nss 3.19.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.19.2 compatibility nss 3.19.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.20 release notes
bugs fixed in nss 3.20 this bugzilla query re
turns all the bugs fixed in nss 3.20: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.20 compatibility nss 3.20 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.22 release notes
bugs fixed in nss 3.22 this bugzilla query re
turns all the bugs fixed in nss 3.22: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.22 compatibility nss 3.22 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.24 release notes
bugs fixed in nss 3.24 this bugzilla query re
turns all the bugs fixed in nss 3.24: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.24 acknowledgements the nss development team would like to thank yuval yarom for responsibly disclosing the cachebleed attack by providing advance copies of their research.
NSS 3.25 release notes
6:0e:b4 cn = opentrust root ca g2 sha-256 fingerprint: 27:99:58:29:fe:6a:75:15:c1:bf:e8:48:f9:c4:76:1d:b1:6c:22:59:29:25:7b:f4:0d:08:94:f2:9e:a8:ba:f2 cn = opentrust root ca g3 sha-256 fingerprint: b7:c3:62:31:70:6e:81:07:8c:36:7c:b8:96:19:8f:1e:32:08:dd:92:69:49:dd:8f:57:09:a4:10:f7:5b:62:92 bugs fixed in nss 3.25 this bugzilla query re
turns all the bugs fixed in nss 3.25: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.25 compatibility nss 3.25 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.26 release notes
root x1 sha-256 fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 npn is disabled, and alpn is enabled by default the nss test suite now completes with the experimental tls 1.3 code enabled several test improvements and additions, including a nist known answer test bugs fixed in nss 3.26 this bugzilla query re
turns all the bugs fixed in nss 3.26: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.26 compatibility nss 3.26 shared libraries are backwards compatible with all older nss 3.x shared libraries.
NSS 3.27 release notes
equifax secure ebusiness ca-1 sha-256 fingerprint: cf:56:ff:46:a4:a1:86:10:9d:d9:65:84:b5:ee:b5:8a:51:0c:42:75:b0:e5:f9:4f:40:bb:ae:86:5e:19:f6:73 cn = equifax secure global ebusiness ca-1 sha-256 fingerprint: 5f:0b:62:ea:b5:e3:53:ea:65:21:65:16:58:fb:b6:53:59:f4:43:28:0a:4a:fb:d1:04:d7:7d:10:f9:f0:4c:07 bugs fixed in nss 3.27 this bugzilla query re
turns all the bugs fixed in nss 3.27: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.27 compatibility nss 3.27 shared libraries are backwards compatible with all older nss 3.x shared libraries.
NSS 3.28 release notes
bugs fixed in nss 3.28 this bugzilla query re
turns all the bugs fixed in nss 3.28: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.28 compatibility nss 3.28 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.29 release notes
bugs fixed in nss 3.29 this bugzilla query re
turns all the bugs fixed in nss 3.29: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.29 compatibility nss 3.29 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.33 release notes
bugs fixed in nss 3.33 this bugzilla query re
turns all the bugs fixed in nss 3.33: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.33 compatibility nss 3.33 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.34.1 release notes
new in nss 3.34 new functionality none new functions bugs fixed in nss 3.34.1 this bugzilla query re
turns all the bugs fixed in nss 3.34.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.34.1 compatibility nss 3.34.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.34 release notes
new functions bugs fixed in nss 3.34 this bugzilla query re
turns all the bugs fixed in nss 3.34: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.34 compatibility nss 3.34 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.36.1 release notes
this bugzilla query re
turns all the bugs fixed in nss 3.36.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.36.1 compatibility nss 3.36.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.36.2 release notes
this bugzilla query re
turns all the bugs fixed in nss 3.36.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.36.2 compatibility nss 3.36.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.36 release notes
bugs fixed in nss 3.36 this bugzilla query re
turns all the bugs fixed in nss 3.36: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.36 compatibility nss 3.36 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.37.1 release notes
this bugzilla query re
turns all the bugs fixed in nss 3.37.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.37.1 compatibility nss 3.37.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.37 release notes
3 ca ii sha-256 fingerprint: 8d:a0:84:fc:f9:9c:e0:77:22:f8:9b:32:05:93:98:06:fa:5c:b8:11:e1:c8:13:f6:a1:08:c7:d3:36:b3:40:8e cn = tÜrktrust elektronik sertifika hizmet saÄŸlayıcısı h5 sha-256 fingerprint: 49:35:1b:90:34:44:c1:85:cc:dc:5c:69:3d:24:d8:55:5c:b2:08:d6:a8:14:13:07:69:9f:4a:f0:63:19:9d:78 bugs fixed in nss 3.37 this bugzilla query re
turns all the bugs fixed in nss 3.37: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.37 compatibility nss 3.37 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.38 release notes
bugs fixed in nss 3.38 this bugzilla query re
turns all the bugs fixed in nss 3.38: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.38 compatibility nss 3.38 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.39 release notes
rprint: 27995829fe6a7515c1bfe848f9c4761db16c225929257bf40d0894f29ea8baf2 cn = opentrust root ca g3 sha-256 fingerprint: b7c36231706e81078c367cb896198f1e3208dd926949dd8f5709a410f75b6292 bugs fixed in nss 3.39 bug 1483128 - nss responded to an sslv2-compatible clienthello with a serverhello that had an all-zero random (cve-2018-12384) this bugzilla query re
turns all the bugs fixed in nss 3.39: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.39 compatibility nss 3.39 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.40 release notes
the following ca certificates were removed: cn = visa ecommerce root sha-256 fingerprint: 69fac9bd55fb0ac78d53bbee5cf1d597989fd0aaab20a25151bdf1733ee7d122 bugs fixed in nss 3.40 bug 1478698 - ffdhe key exchange sometimes fails with decryption failure this bugzilla query re
turns all the bugs fixed in nss 3.40: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.40 compatibility nss 3.40 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.41.1 release notes
(cve-2018-18508) this bugzilla query re
turns all bugs fixed in 3.41.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.41.1 compatibility nss 3.41.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.41 release notes
y supported_signature_algorithms in certificate request in tls 1.2 bug 1485864 - cache side-channel variant of the bleichenbacher attack (cve-2018-12404) bug 1481271 - resend the same ticket in clienthello after helloretryrequest bug 1493769 - set session_id for external resumption tokens bug 1507179 - reject ccs after handshake is complete in tls 1.3 this bugzilla query re
turns all the bugs fixed in nss 3.41: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.41 compatibility nss 3.41 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.42.1 release notes
(cve-2018-18508) this bugzilla query re
turns all the bugs fixed in nss 3.42.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.42.1 compatibility nss 3.42.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.42 release notes
bug 1513913 - a fix for solaris where firefox 60 core dumps during start when using profile from version 52 this bugzilla query re
turns all the bugs fixed in nss 3.42: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.42 compatibility nss 3.42 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.43 release notes
this bugzilla query re
turns all the bugs fixed in nss 3.43: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.43 compatibility nss 3.43 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.44.2 release notes
bugs fixed in nss 3.44.2 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.44.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.44.2 compatibility nss 3.44.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.44.3 release notes
bugs fixed in nss 3.44.3 bug 1579060 - don't set the constructed bit for issueruniqueid and subjectuniqueid in mozilla::pkix cve-2019-11745 - encryptupdate should use maxout, not block size this bugzilla query re
turns all the bugs fixed in nss 3.44: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.44 compatibility nss 3.44.3 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.44 release notes
code 1549413 - android log lib is not included in build 1537927 - ipsec usage is too restrictive for existing deployments 1549608 - signature fails with dbm disabled 1549848 - allow building nss for ios using gyp 1549847 - nss's sqlite compilation warnings make the build fail on ios 1550041 - freebl not building on ios simulator 1542950 - macos cipher test timeouts this bugzilla query re
turns all the bugs fixed in nss 3.44: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.44 compatibility nss 3.44 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.46.1 release notes
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.
NSS 3.47.1 release notes
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.
NSS 3.48.1 release notes
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.
NSS 3.48 release notes
ete coverage bug 1590678 - remove -wmaybe-uninitialized warning in tls13esni.c bug 1588244 - nss changes for delegated credential key strength checks bug 1459141 - add more cbc padding tests that missed nss 3.47 bug 1590339 - fix a memory leak in btoa.c bug 1589810 - fix uninitialized variable warnings from certdata.perl bug 1573118 - enable tls 1.3 by default in nss 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 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.49.1 release notes
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.
NSS 3.49.2 release notes
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.
NSS 3.49 release notes
ello with message_seq of 1 as a second clienthello bug 1603027 - test that esni is regenerated after helloretryrequest bug 1593167 - intermittent mis-reporting potential security risk sec_error_unknown_issuer bug 1535787 - fix automation/release/nss-release-helper.py on macos bug 1594933 - disable building dbm by default bug 1562548 - improve gcm perfomance on aarch32 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 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.50 release notes
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.
NSS 3.51 release notes
read the fips_enabled flag on the machine unless nss was built with fips enabled bug 1431940 - fix a null pointer dereference in blake2b_update bug 1617387 - fix compiler warning in secsign.c bug 1618400 - fix a openbsd/arm64 compilation error: unused variable 'getauxval' bug 1610687 - fix a crash on unaligned cmaccontext.aes.keyschedule when using aes-ni intrinsics this bugzilla query re
turns all the bugs fixed in nss 3.51: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.51 compatibility nss 3.51 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.52 release notes
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.
NSS 3.53 release notes
modular inverse test bug 1629553 - rework and cleanup gmake builds bug 1438431 - remove mkdepend and "depend" make target bug 290526 - support parallel building of nss when using the makefiles bug 1636206 - hacl* update after changes in libintvector.h bug 1636058 - fix building nss on debian s390x, mips64el, and riscv64 bug 1622033 - add option to build without seed this bugzilla query re
turns all the bugs fixed in nss 3.53: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.53 compatibility nss 3.53 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.54 release notes
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.
NSS 3.55 release notes
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.
NSS 3.56 release notes
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.
NSS Developer Tutorial
miscellaneous goto can be used, to simplify resource deallocation, before re
turning from a function.
NSS Sample Code sample5
* publicvalue arg (4th) can be null for rsa key - i think it is even * ignored */ pk11_importderprivatekeyinfoandre
turnkey(slot, &der, null, null, pr_false, pr_true, ku_all, &pvtkey, null); secitem_freeitem(&der, pr_false); if (pvtkey == null) { fprintf(stderr, "couldn't extract private key (err %d)\n", pr_geterror()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } ...
nss tech note2
]: pinfo = 0xbffff340 1024[805ef10]: rv = 0x0 1024[805ef10]: c_getslotlist 1024[805ef10]: tokenpresent = 0x0 1024[805ef10]: pslotlist = 0x0 1024[805ef10]: pulcount = 0xbffff33c 1024[805ef10]: *pulcount = 0x2 1024[805ef10]: rv = 0x0 note that when a pkcs #11 function takes a pointer argument for which it will set a value (c_getslotlist above), this mode will display the value upon re
turn.
JSBool
jsbool is the re
turn type of many jsapi functions and callbacks.
JSCheckAccessOp
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.
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,...
JSErrorFormatString
description jserrorformatstring is a struct to represent error message and type, re
turned by js_reporterrornumber function.
JSExceptionState
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.
JSFreeOp
methods method description jsruntime *runtime() const re
turns a pointer to jsruntime passed to constructor.
JSHasInstanceOp
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.
JSID_IS_GCTHING
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_IS_INT
description jsid_is_int tests whether a specified js id, id, is an integer, and re
turns true if it's an integer.
JSID_IS_STRING
description jsid_is_string tests whether a specified js id, id, is a string, and re
turns true if it's a string.
JSID_IS_SYMBOL
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_VOID
a void jsid is not a valid id and only arises as an exceptional api re
turn value, such as in js_nextproperty.
JSIteratorOp
the callback should re
turn an iterator object or null if an error or exception occurred on cx.
JSObjectOps.dropProperty
description the following contract governs jsobjectops callers and implementations: whenever jsobjectops.lookupproperty re
turns a jsproperty pointer, the property is locked.
Retrieving part of the bookmarks tree
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.
Packaging WebLock
« previousnext » copyright (c) 2003 by doug
turner and ian oeschger.
Preface
next » copyright (c) 2003 by doug
turner and ian oeschger.
Resources
embedding mozilla current module owners xpinstall xul xpcom resources the xpcom project page xulplanet's online xpcom reference information on xpconnect and scriptable components the smart pointer guide xpidl xpidl compiler reference general development resources the world wide web consortium url specification at the w3 gnu make « previous copyright (c) 2003 by doug
turner and ian oeschger.
Making cross-thread calls using runnables
icallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call back immediately with an empty string which indicates failure callback(emptycstring()); re
turn; } nscomptr<nsirunnable> r = new picalculatetask(callback, digits); mythread->dispatch(r, nsieventtarget::dispatch_normal); // the result callback will shut down the worker thread, we can let it go here...
XPCOM hashtable guide
the hashtables that hold references to pointers (nsrefptrhashtable and nsinterfacehashtable) also have getweak methods that re
turn non-addrefed pointers.
Receiving startup notifications
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
you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will re
turn you the interface object for the nsisupportsarray interface.
Components.utils.Sandbox
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.
Components.utils.evalInSandbox
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.
nsIFeedContainer
note: the re
turned array will contain nsifeedcategory objects, except that interface has not been implemented yet.
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
re
turn value true if the device is ready and has a position available to re
turn; otherwise false.
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,...
nsIInterfaceRequestor
the main difference is that interfaces re
turned are not required to provide a way back to the object implementing nsiinterfacerequestor.
nsIJumpListItem
re
turn value true if items are the same, otherwise false ...
nsILocale
re
turn value the locale code to be used for the given category.
nsIMimeHeaders
methods extractheader() string extractheader( [const] in string headername, in boolean getallofthem ); parameters headername missing description getallofthem missing description re
turn value missing description exceptions thrown missing exception missing description initialize() void initialize( [const] in string allheaders, in long allheaderssize ); parameters allheaders insert the complete message content allheaderssize length of the passed in content exceptions thrown missing exception missing description rem...
Building an Account Manager Extension
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.
nsIMsgAccountManagerExtension
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.
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 ...
nsIWebNavigation
this attribute never re
turns null except for unexpected error situations.
nsIWebappsSupport
re
turn value true if the web application is installed, false if it's not installed.
nsIWinAccessNode
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
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.
nsIWorkerGlobalScope
onerror nsidomeventlistener self nsiworkerglobalscope re
turns the global scope object itself.
nsIXFormsNSInstanceElement
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.
nsIXFormsNSModelElement
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.
nsIXMLHttpRequest
; } }; let evf = f => ['load', 'error', 'abort'].foreach(f); evf(m => xhr.addeventlistener(m, handler, false)); xhr.mozbackgroundrequest = true; xhr.open('get', url, true); xhr.channel.loadflags |= ci.nsirequest.load_anonymous | ci.nsirequest.load_bypass_cache | ci.nsirequest.inhibit_persistent_caching; xhr.responsetype = "arraybuffer"; //dont set it, so it re
turns string, you dont want arraybuffer.
nsIXPCException
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.
nsIXULBuilderListener
example create an object which implements nsixulbuilderlistener: var mylistener = { queryinterface: function(aiid) { if (aiid.equals(components.interfaces.nsixulbuilderlistener) || aiid.equals(components.interfaces.nsisupports)) re
turn this; throw components.results.ns_nointerface; }, willrebuild : function(builder) {}, didrebuild : function(builder) { } } attach the listener to a element: myelement.addlistener(mylistener); ...
nsIXmlRpcFault
xml-rpc server fault codes are re
turned wrapped in this; access it using nsixpconnect.getpendingexception->data.
NS_ENSURE_ARG_POINTER
summary macro re
turns ns_error_invalid_pointer if the macro argument evaluates to false and shows a warning (ns_warning) in this case.
nsStaticModuleInfo
getmodule this member provides a function pointer of type nsgetmoduleproc that re
turns a nsimodule instance.
xptcall FAQ
this code also does the platform specific cleanup as the call re
turns.
XPCOM
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.
xpidl
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.
XUL Overlays
(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.
MailNews Filters
applyfilterstohdr will in
turn call the applyfilterhit method of the passed in nsimsgfilterhitnotify interface ptr.
Demo Addon
let query = gloda.newquery(gloda.noun_message); query.subjectmatches(searchterm); let mylistener = { /* called when new items are re
turned by the database query or freshly indexed */ onitemsadded: function mylistener_onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function mylistener_onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: funct...
Access Window
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.
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...
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
the following preferences: app.extensions.version, extensions.lastappversion versions re
turned by nsixulappinfo.
Zombie compartments
re
turn to about:memory and minimize memory and remeasure, multiple times if necessary.
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.
Structures - Plugins
npsaveddata block of instance information saved after the plug-in is deleted; can be re
turned to the plug-in.
Color vision simulation - Firefox Developer Tools
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.
DOM Inspector FAQ - Firefox Developer Tools
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".
Set an XHR breakpoint - Firefox Developer Tools
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.
Tutorial: Set a breakpoint - Firefox Developer Tools
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.
Eyedropper - Firefox Developer Tools
keyboard shortcuts command windows macos linux select the current color enter re
turn enter dismiss the eyedropper esc esc esc move by 1 pixel arrow keys arrow keys arrow keys move by 10 pixels shift + arrow keys shift + arrow keys shift + arrow keys ...
Monster example - Firefox Developer Tools
here's the code: var monster_count = 5000; var min_name_length = 2; var max_name_length = 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 = rando...
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
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.
Responsive Design Mode - Firefox Developer Tools
on the right end of the screen, three buttons allow you to: camera button - take a screenshot settings button - opens the rdm settings menu close button - closes rdm mode and re
turns to regular browsing the settings menu includes the following commands: left-align viewport - when checked moves the rdm viewport to the left side of the browser window show user agent - when checked displays the user agent string the final two options define when the page is reloaded: reload when touch simulation is toggled: when this option is enabled, the page is reloaded whenev...
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...
Firefox Developer Tools
(note: this feature is not
turned on by default and must be enabled in settings before the icon will appear.) toggles responsive design mode.
ANGLE_instanced_arrays - Web APIs
constants this extension exposes one new constant, which can be used in the gl.getvertexattrib() method: ext.vertex_attrib_array_divisor_angle re
turns a glint describing the frequency divisor used for instanced rendering when used in the gl.getvertexattrib() as the pname parameter.
Drawing text - Web APIs
measuretext() re
turns a textmetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style.
Optimizing canvas - Web APIs
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().
Using images - Web APIs
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.
Channel Messaging API - Web APIs
once created, the two ports of the channel can be accessed through the messagechannel.port1 and messagechannel.port2 properties (which both re
turn messageport objects.) the app that created the channel uses port1, and the app at the other end of the port uses port2 — you send a message to port2, and transfer the port over to the other browsing context using window.postmessage along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.) when these transferable objects are transferr...
ChildNode.after() - Web APIs
with(node) { after("foo"); } // referenceerror: after is not defined polyfill you can polyfill the after() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { re
turn; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ...
ChildNode.before() - Web APIs
with(node) { before("foo"); } // referenceerror: before is not defined polyfill you can polyfill the before() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { re
turn; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnod...
ChildNode.remove() - Web APIs
with(node) { remove(); } // referenceerror: remove is not defined polyfill you can polyfill the remove() method in internet explorer 9 and higher with the following code: // from:https://github.com/jserz/js_piece/blob/master/dom/childnode/remove()/remove().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('remove')) { re
turn; } object.defineproperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove() { this.parentnode.removechild(this); } }); }); })([element.prototype, characterdata.prototype, documenttype.prototype]); specifications specification status comment domthe definition of 'childnod...
ChildNode.replaceWith() - Web APIs
with(node) { replacewith("foo"); } // referenceerror: replacewith is not defined 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); } ...
Client.id - Web APIs
the id read-only property of the client interface re
turns the universally unique identifier of the client object.
Client.type - Web APIs
a document) function sendmessage(message) { re
turn new promise(function(resolve, reject) { // note that this is the serviceworker.postmessage version navigator.serviceworker.controller.postmessage(message); window.serviceworker.onmessage = function(e) { resolve(e.data); }; }); } // controlling service worker self.addeventlistener("message", function(e) { // e.source is a client object e.source.postmessage("hello!
Clients.openWindow() - Web APIs
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.
CrashReportBody - Web APIs
the crashreportbody interface of the reporting api represents the body of a crash report (the re
turn value of its report.body property).
Credential.id - Web APIs
the id property of the credential interface re
turns a domstring containing the credential's identifier.
Credential.name - Web APIs
the name property of the credential interface re
turns a domstring, containing the name associated with a credential.
Crypto.subtle - Web APIs
the crypto.subtle read-only property re
turns a subtlecrypto which can then be used to perform low-level cryptographic operations.
Crypto - Web APIs
crypto.subtle read only secure context re
turns a subtlecrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption.
CustomEvent() - Web APIs
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).
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 ...
DOMException.code - Web APIs
the code read-only property of the domexception interface re
turns a short that contains one of the error code constants, or 0 if none match.
DOMException.message - Web APIs
the message read-only property of the domexception interface re
turns a domstring representing a message or description associated with the given error name.
DOMException.name - Web APIs
the name read-only property of the domexception interface re
turns a domstring that contains one of the strings associated with an error name.
DOMImplementation.createDocumentType() - Web APIs
the domimplementation.createdocumenttype() method re
turns a documenttype object which can either be used with domimplementation.createdocument upon document creation or can be put into the document via methods like node.insertbefore() or node.replacechild().
DOMImplementation.createHTMLDocument() - Web APIs
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.
DOMMatrixReadOnly.flipX() - Web APIs
syntax dommatrix.flipx() re
turn value re
turns a dommatrix containing a new matrix being the result of the original matrix flipped about the x-axis, which is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0).
DOMMatrixReadOnly.scale() - Web APIs
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.
DOMPoint.DOMPoint() - Web APIs
the dompoint() constructor creates and re
turns a new dompoint object, given the values for some or all of its properties.
DOMPoint - Web APIs
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.
DOMPointInit.w - Web APIs
the dompointreadonly.tojson() method re
turns a dompointinit object that describes the same point as the original point.
DOMPointInit.x - Web APIs
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.
DOMPointInit.y - Web APIs
the dompointreadonly.tojson() method re
turns a dompointinit object that describes the same point as the original point.
DOMPointInit.z - Web APIs
the dompointreadonly.tojson() method re
turns a dompointinit object that describes the same point as the original point.
DOMRect.DOMRect() - Web APIs
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.
DOMRectReadOnly() - Web APIs
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.
Document.featurePolicy - Web APIs
the featurepolicy read-only property of the document interface re
turns the featurepolicy interface which provides a simple api for inspecting the feature policies applied to a specific document.
Document.fullscreen - Web APIs
function isdocumentinfullscreenmode() { re
turn document.fullscreen; } this next example, on the other hand, uses the current fullscreenelement property to determine the same thing: function isdocumentinfullscreenmode() { re
turn document.fullscreenelement !== null; } if fullscreenelement isn't null, this re
turns true, indicating that full-screen mode is in effect.
Document.head - Web APIs
the head read-only property of the document interface re
turns the <head> element of the current document.
Document.hidden - Web APIs
the document.hidden read-only property re
turns a boolean value indicating if the page is considered hidden or not.
Document: keydown event - Web APIs
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.
Document: keyup event - Web APIs
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.
Document.links - Web APIs
the links read-only property of the document interface re
turns a collection of all <area> elements and <a> elements in a document with a value for the href attribute.
Document.ononline - Web APIs
window.navigator.online re
turns boolean true if the browser is online and false if it is definitely offline (disconnected from the network).
HTMLElement.lang - Web APIs
the language code re
turned by this property is defined in the tags for identifying languages (bcp47) ietf document.
HTMLElement.offsetLeft - Web APIs
the htmlelement.offsetleft read-only property re
turns the number of pixels that the upper left corner of the current element is offset to the left within the htmlelement.offsetparent node.
HTMLElement: transitionend event - Web APIs
}); el.addeventlistener('transitionstart', function() { message.textcontent = 'transitionstart fired'; }); el.addeventlistener('transitioncancel', function() { message.textcontent = 'transitioncancel fired'; }); el.addeventlistener('transitionend', function() { message.textcontent = 'transitionend fired'; }); the transitionend event is fired in both directions: when the box finishes
turning and the opacity hits 0 or 1, depending on the direction.
HTMLHyperlinkElementUtils.hostname - Web APIs
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.
HTMLHyperlinkElementUtils.origin - Web APIs
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.
HTMLHyperlinkElementUtils.password - Web APIs
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.
HTMLHyperlinkElementUtils.pathname - Web APIs
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.
HTMLHyperlinkElementUtils.port - Web APIs
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.
HTMLHyperlinkElementUtils.protocol - Web APIs
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.
HTMLHyperlinkElementUtils.search - Web APIs
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.
HTMLHyperlinkElementUtils.username - Web APIs
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.
HTMLIFrameElement.featurePolicy - Web APIs
the featurepolicy read-only property of the htmliframeelement interface re
turns the featurepolicy interface which provides a simple api for introspecting the feature policies applied to a specific frame.
HTMLImageElement.complete - Web APIs
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; } /* ...
HTMLImageElement.useMap - Web APIs
consider a <map> that looks like this: <map name="mainmenu-map"> <area shape="circle" coords="25, 25, 75, 75" href="/index.html" alt="re
turn to home page"> <area shape="rect" coords="25, 25, 100, 150" href="/index.html" alt="shop"> </map> given the image map named mainmenu-map, the image which uses it should look something like the following: <img src="menubox.png" usemap="#mainmenu-map"> for additional examples (including interactive ones), see the articles about the <map> and <area> elements, as well as the guide to using imag...
HTMLInputElement.stepDown() - Web APIs
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.
HTMLInputElement.stepUp() - Web APIs
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.
HTMLKeygenElement - Web APIs
methods name & arguments re
turn description checkvalidity() boolean always re
turns true because keygen objects are never candidates for constraint validation.
HTMLLabelElement.control - Web APIs
the read-only htmllabelelement.control property re
turns a reference to the control (in the form of an object of type htmlelement or one of its derivatives) with which the <label> element is associated, or null if the label isn't associated with a control.
HTMLLinkElement.as - Web APIs
the as property of the htmllinkelement interface re
turns a domstring representing the type of content being loaded by the html link, one of "script", "style", "image", "video", "audio", "track", "font", "fetch".
HTMLLinkElement.relList - Web APIs
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.
HTMLLinkElement - Web APIs
linkstyle.sheet read only re
turns the stylesheet object associated with the given element, or null if there is none.
HTMLMediaElement.buffered - Web APIs
the htmlmediaelement.buffered read-only property re
turns a new 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.controlsList - Web APIs
the controlslist property of the htmlmediaelement interface re
turns a domtokenlist that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls.
HashChangeEvent - Web APIs
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...
History.state - Web APIs
the history.state property re
turns a value representing the state at the top of the history stack.
IDBCursor.continuePrimaryKey() - Web APIs
example here’s how you can resume an iteration of all articles tagged with "javascript" since your last visit: let request = articlestore.index("tag").opencursor(); let count = 0; let unreadlist = []; request.onsuccess = (event) => { let cursor = event.target.result; if (!cursor) { re
turn; } let lastprimarykey = getlastiteratedarticleid(); if (lastprimarykey > cursor.primarykey) { cursor.continueprimarykey("javascript", lastprimarykey); re
turn; } // update lastiteratedarticleid setlastiteratedarticleid(cursor.primarykey); // preload 5 articles into the unread list; unreadlist.push(cursor.value); if (++count < 5) { cursor.continue()...
IDBCursor.direction - Web APIs
the direction read-only property of the idbcursor interface is a domstring that re
turns the direction of traversal of the cursor (set using idbobjectstore.opencursor for example).
IDBCursor.key - Web APIs
the key read-only property of the idbcursor interface re
turns the key for the record at the cursor's position.
IDBDatabase.onerror - Web APIs
the onerror event handler of the idbdatabase interface handles the error event, fired when a request re
turns an error and bubbles up to the connection object.
IDBFactory.cmp() - Web APIs
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: ...
IntersectionObserverEntry.boundingClientRect - Web APIs
the intersectionobserverentry interface's read-only boundingclientrect property re
turns a domrectreadonly which in essence describes a rectangle describing the smallest rectangle that contains the entire target element.
InterventionReportBody - Web APIs
the interventionreportbody interface of the reporting api represents the body of an intervention report (the re
turn value of its report.body property).
KeyboardEvent.altKey - Web APIs
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.
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.keyCode - Web APIs
example window.addeventlistener("keydown", function (event) { if (event.defaultprevented) { re
turn; // should do nothing if the default action has been cancelled } var handled = false; if (event.key !== undefined) { // handle the event with keyboardevent.key and set handled true.
KeyboardEvent.shiftKey - Web APIs
syntax var shiftkeypressed = instanceofkeyboardevent.shiftkey re
turn value a boolean example <html> <head> <title>shiftkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "shift key pressed: " + e.shiftkey + "\n" + "alt key pressed: " + e.altkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the shift key.<br /> you can also use the shift key together with the alt key.</p> </body> </html> specifications sp...
KeyboardLayoutMap.entries - Web APIs
the entries read-only property of the keyboardlayoutmap interface 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 - Web APIs
the keys read-only property of the keyboardlayoutmap interface re
turns a new array iterator object that contains the keys for each index in the array.
KeyboardLayoutMap.values - Web APIs
the values read-only property of the keyboardlayoutmap interface re
turns a new array iterator object that contains the values for each index in the map.
KeyframeEffect.KeyframeEffect() - Web APIs
the keyframeeffect() constructor of the web animations api re
turns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance.
LinearAccelerationSensor.x - Web APIs
the x read-only property of the linearaccelerationsensor interface re
turns a double precision integer containing the linear acceleration of the device along the device's x axis.
LinearAccelerationSensor.y - Web APIs
the y read-only property of the linearaccelerationsensor interface re
turns a double precision integer containing the acceleration of the device along the device's y axis.
LinearAccelerationSensor.z - Web APIs
the z read-only property of the linearaccelerationsensor interface re
turns a double precision integer containing the acceleration of the device along the device's z axis.
LocalMediaStream - Web APIs
however, getusermedia() now re
turns a mediastream instead, and this interface has been removed from the specification.
Location: hostname - Web APIs
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.
Location: origin - Web APIs
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.
Location: password - Web APIs
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
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.
Location: port - Web APIs
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.
Location: protocol - Web APIs
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.
Location: search - Web APIs
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.
Location: username - Web APIs
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' ...
LockManager - Web APIs
lockmanager.query() re
turns a promise that resolves with a lockmanagersnapshot which contains information about held and pending locks.
LockedFile.abort() - Web APIs
syntax var request = instanceoflockedfile.abort(); re
turn a filerequest object to handle the success or failure of the operation.
LockedFile.flush() - Web APIs
syntax var request = instanceoflockedfile.flush(); re
turn a filerequest object to handle the success or failure of the operation.
MediaStreamTrack.kind - Web APIs
the mediastreamtrack.kind read-only property re
turns a domstring set to "audio" if the track is an audio track and to "video", if it is a video track.
MediaStreamTrack.label - Web APIs
the mediastreamtrack.label read-only property re
turns a domstring containing a user agent-assigned label that identifies the track source, as in "internal microphone".
MediaStreamTrack.muted - Web APIs
the muted read-only property of the mediastreamtrack interface re
turns a boolean value indicating whether or not the track is currently unable to provide media output.
MediaStreamTrack.remote - Web APIs
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.
MediaTrackConstraints.aspectRatio - Web APIs
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().
MediaTrackConstraints.autoGainControl - Web APIs
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().
MediaTrackConstraints.channelCount - Web APIs
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().
MediaTrackConstraints.echoCancellation - Web APIs
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().
MediaTrackConstraints.facingMode - Web APIs
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().
MediaTrackConstraints.frameRate - Web APIs
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().
MediaTrackConstraints.height - Web APIs
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().
MediaTrackConstraints.latency - Web APIs
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().
MediaTrackConstraints.noiseSuppression - Web APIs
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().
MediaTrackConstraints.sampleRate - Web APIs
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().
MediaTrackConstraints.sampleSize - Web APIs
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().
MediaTrackControls.volume - Web APIs
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().
MediaTrackConstraints.width - Web APIs
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().
MediaTrackSettings.aspectRatio - Web APIs
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().
MediaTrackSettings.autoGainControl - Web APIs
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().
MediaTrackSettings.channelCount - Web APIs
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().
MediaTrackSettings.cursor - Web APIs
the mediatracksettings dictionary's cursor property indicates whether or not the cursor should be captured as part of the video track included in the mediastream re
turned by getdisplaymedia().
MediaTrackSettings.echoCancellation - Web APIs
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().
MediaTrackSettings.facingMode - Web APIs
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().
MediaTrackSettings.frameRate - Web APIs
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().
MediaTrackSettings.groupId - Web APIs
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().
MediaTrackSettings.height - Web APIs
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().
MediaTrackSettings.latency - Web APIs
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().
MediaTrackSettings.noiseSuppression - Web APIs
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().
MediaTrackSettings.sampleRate - Web APIs
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().
MediaTrackSettings.sampleSize - Web APIs
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().
MediaTrackSettings.volume - Web APIs
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().
MediaTrackSettings.width - Web APIs
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().
MediaTrackSettings - Web APIs
the mediatracksettings dictionary is used to re
turn the current values configured for each of a mediastreamtrack's settings.
MediaTrackSupportedConstraints.aspectRatio - Web APIs
the mediatracksupportedconstraints dictionary's aspectratio property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the aspectratio constraint.
MediaTrackSupportedConstraints.autoGainControl - Web APIs
the mediatracksupportedconstraints dictionary's autogaincontrol property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the autogaincontrol constraint.
MediaTrackSupportedConstraints.channelCount - Web APIs
the mediatracksupportedconstraints dictionary's channelcount property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the channelcount constraint.
MediaTrackSupportedConstraints.deviceId - Web APIs
the mediatracksupportedconstraints dictionary's deviceid property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the deviceid constraint.
MediaTrackSupportedConstraints.echoCancellation - Web APIs
the mediatracksupportedconstraints dictionary's echocancellation property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the echocancellation constraint.
MediaTrackSupportedConstraints.facingMode - Web APIs
the mediatracksupportedconstraints dictionary's facingmode property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the facingmode constraint.
MediaTrackSupportedConstraints.frameRate - Web APIs
the mediatracksupportedconstraints dictionary's framerate property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the framerate constraint.
MediaTrackSupportedConstraints.groupId - Web APIs
the mediatracksupportedconstraints dictionary's groupid property is a read-only boolean value which is present (and set to true) in the object re
turned by mediadevices.getsupportedconstraints() if and only if the user agent supports the groupid constraint.
Node.nextSibling - Web APIs
the node.nextsibling read-only property re
turns the node immediately following the specified one in their parent's childnodes, or re
turns null if the specified node is the last child in the parent element.
Node.nodePrincipal - Web APIs
the node.nodeprincipal read-only property re
turns the nsiprincipal object representing current security context of the node.
Node.parentElement - Web APIs
the node.parentelement read-only property re
turns the dom node's parent element, or null if the node either has no parent, or its parent isn't a dom element.
Node.prefix - Web APIs
the node.prefix read-only property re
turns the namespace prefix of the specified node, or null if no prefix is specified.
Node.previousSibling - Web APIs
the node.previoussibling read-only property re
turns the node immediately preceding the specified one in its parent's childnodes list, or null if the specified node is the first in that list.
NodeIterator.detach() - Web APIs
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.
NodeIterator.root - Web APIs
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.
Notification.actions - Web APIs
the actions read-only property of the notification interface re
turns the list of notificationaction objects set using the actions option when creating the notification using the notification() constructor.
Notification.badge - Web APIs
the badge property of the notification interface re
turns the url of the image used to represent the notification when there is not enough space to display the notification itself.
PaintWorklet - Web APIs
properties paintworklet.devicepixelratio re
turns the current device's ratio of physical pixels to logical pixels.
PannerNode.coneInnerAngle - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation re
turn [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the a...
PannerNode.coneOuterAngle - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation re
turn [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the a...
PannerNode.coneOuterGain - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation re
turn [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the a...
PannerNode.orientationX - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation re
turn [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the a...
PannerNode.orientationY - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation re
turn [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the a...
PannerNode.orientationZ - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation re
turn [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the a...
ParentNode.replaceChildren() - Web APIs
syntax // [throws, unscopable] parentnode.replacechildren(...nodesordomstrings) // re
turns undefined parameters nodesordomstrings a set of node or domstring objects to replace the parentnode's existing children with.
PasswordCredential.idName - Web APIs
the idname property of the passwordcredential interface re
turns a usvstring, representing the name that will be used for the id field, when submitting the current object to a remote endpoint via fetch.
PasswordCredential.name - Web APIs
the name read-only property of the passwordcredential interface re
turns a usvstring containing a human-readable public name for display in a credential chooser.
PasswordCredential.passwordName - Web APIs
the passwordname property of the passwordcredential interface re
turns a usvstring, depicting the name used by the password field, when submitting the current object to a remote endpoint via fetch.
Path2D() - Web APIs
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.
PayerErrors.name - Web APIs
the name property is included in a payererrors object if the payername re
turned in the response couldn't be validated.
PayerErrors.phone - Web APIs
the phone property is found in a payererrors object if the payername re
turned in the response couldn't be validated as a valid phone number.
PaymentAddress.city - Web APIs
the city read-only property of the paymentaddress interface re
turns a string containing the city or town portion of the address.
PaymentAddress.organization - Web APIs
the organization read-only property of the paymentaddress interface re
turns a string containing the name of the organization, firm, company, or institution at the address.
PaymentAddress.phone - Web APIs
the read-only phone property of the paymentaddress interface re
turns a string containing the telephone number of the recipient or contact person.
PaymentAddress.postalCode - Web APIs
the postalcode read-only property of the paymentaddress interface re
turns a string containing a code used by a jurisdiction for mail routing, for example, the zip code in the united states or the postal index number (pin code) in india.
PaymentAddress.recipient - Web APIs
the read-only recipient property of the paymentaddress interface re
turns a string containing the name of the recipient, purchaser, or contact person at the payment address.
PaymentAddress - Web APIs
methods paymentaddress.tojson() a standard serializer that re
turns a json representation of the paymentaddress object's properties.
PaymentCurrencyAmount.value - Web APIs
currency: "gbp", value: "7.77" } this example specifies a price of 1000¥: let price = { currency: "jpy", value: "1000" } verifying a properly formatted price you can ensure that the value entered as a price is formatted correctly prior to submission by matching it against a simple regular expression: function checkpriceformat(price) { let validregex = /^-?[0-9]+(\.[0-9]+)?$/; re
turn validregex.test(price); } this function, checkpriceformat(), will re
turn true if the specified price string is formatted properly, or false if it's not.
PaymentDetailsBase - Web APIs
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.
PaymentDetailsUpdate - Web APIs
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.
PaymentMethodChangeEvent - Web APIs
re
turn value a newly-created paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property.
PaymentMethodChangeEvent - Web APIs
constructor paymentmethodchangeevent() creates and re
turns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary.
PaymentRequest.onmerchantvalidation - Web APIs
examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; re
turn await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
PaymentRequest.onshippingoptionchange - Web APIs
hipping to jp is supported } else if (addr.country === 'jp') { shippingoption.id = 'jp'; shippingoption.label = 'international shipping'; shippingoption.amount.value = '10.00'; details.total.amount.value = '65.00'; // shipping to elsewhere is unsupported } else { // empty array indicates rejection of the address details.shippingoptions = []; re
turn promise.resolve(details); console.log(details.error); } // hardcode for simplicity if (details.displayitems.length === 2) { details.displayitems[2] = shippingoption; } else { details.displayitems.push(shippingoption); } details.shippingoptions = [shippingoption]; re
turn promise.resolve(details); })(details, request.shippingaddress)); }); specific...
PaymentRequest.shippingType - Web APIs
the shippingtype read-only property of the paymentrequest interface re
turns one of "shipping", "delivery", "pickup", or null if one was not provided by the constructor.
PaymentRequestEvent.instrumentKey - Web APIs
the instrumentkey read-only property of the paymentrequestevent interface 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.
PaymentRequestEvent.methodData - Web APIs
the methoddata read-only property of the paymentrequestevent interface 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.
PerformanceTiming.connectEnd - Web APIs
the legacy performancetiming.connectend read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the connection is opened network.
PerformanceTiming.connectStart - Web APIs
the legacy performancetiming.connectstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the request to open a connection is sent to the network.
PerformanceTiming.domComplete - Web APIs
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.
PerformanceTiming.domContentLoadedEventEnd - Web APIs
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.
PerformanceTiming.domContentLoadedEventStart - Web APIs
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.
PerformanceTiming.domInteractive - Web APIs
the legacy performancetiming.dominteractive 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 'interactive' and the corresponding readystatechange event is thrown.
PerformanceTiming.domLoading - Web APIs
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.
PerformanceTiming.domainLookupEnd - Web APIs
the legacy performancetiming.domainlookupend read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup is finished.
PerformanceTiming.domainLookupStart - Web APIs
the legacy performancetiming.domainlookupstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup starts.
PerformanceTiming.fetchStart - Web APIs
the legacy performancetiming.fetchstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, the browser is ready to fetch the document using an http request.
PerformanceTiming.navigationStart - Web APIs
the legacy performancetiming.navigationstart read-only property re
turns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after the prompt for unload terminates on the previous document in the same browsing context.
PerformanceTiming.requestStart - Web APIs
the legacy performancetiming.requeststart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the browser sent the request to obtain the actual document, from the server or from a cache.
PerformanceTiming.responseEnd - Web APIs
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.
PerformanceTiming.responseStart - Web APIs
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.
Permissions - Web APIs
the permissions interface of the permissions api provides the core permission api functionality, such as methods for querying and revoking permissions methods permissions.query() re
turns the user permission status for a given api.
Using the Permissions API - Web APIs
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.
PhotoCapabilities.imageHeight - Web APIs
the imageheight read-only property of the photocapabilities interface re
turns a mediasettingsrange object indicating the image height range supported by the user agent.
imageWidth - Web APIs
the imagewidth read-only property of the photocapabilities interface re
turns a mediasettingsrange object indicating the image width range supported by the user agent.
PointerEvent.height - Web APIs
syntax var contactheight = pointerevent.height; re
turn value contactheight the height of the event's contact area (in css pixels).
PointerEvent.pressure - Web APIs
syntax var pressure = pointerevent.pressure; re
turn value pressure the normalized pressure of the pointer input in the range of 0 to 1, inclusive, where 0 and 1 represent the minimum and maximum pressure the hardware is capable of detecting, respectively.
PointerEvent.tangentialPressure - Web APIs
syntax var tanpressure = pointerevent.tangentialpressure; re
turn value a float representing the normalized tangential pressure of the pointer input in the range -1 to 1, inclusive, where 0 is the neutral position of the control.
PointerEvent.tiltX - Web APIs
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.
PointerEvent.tiltY - Web APIs
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.
PointerEvent.twist - Web APIs
syntax var twist = pointerevent.twist; re
turn value a long value representing the amount of twist, in degrees, applied to the transducer (pointer).
PointerEvent.width - Web APIs
syntax var contactwidth = pointerevent.width; re
turn value contactwidth the width of the event's contact area (in css pixels).
Multi-touch interaction - Web APIs
function get_cache(ev) { // re
turn the cache for this event's target element switch(ev.target.id) { case "target1": re
turn evcache1; case "target2": re
turn evcache2; case "target3": re
turn evcache3; default: log("error with cache handling",ev); } } function push_event(ev) { // save this event in the target's cache var cache = get_cache(ev); cache.push(ev); } function remove_event(ev) { // remove this event from...
Pinch zoom gestures - Web APIs
false : true; } function log(prefix, ev) { if (!logevents) re
turn; var o = document.getelementsbytagname('output')[0]; var s = prefix + ": pointerid = " + ev.pointerid + " ; pointertype = " + ev.pointertype + " ; isprimary = " + ev.isprimary; o.innerhtml += s + " "; } function clearlog(event) { var o = document.getelementsbytagname('output')[0]; o.innerhtml = ""; } ...
ProgressEvent() - Web APIs
the progressevent() constructor re
turns a newly created progressevent, representing the current completion of a long process.
PushEvent.PushEvent() - Web APIs
example var datainit = { data : 'some sample text' } var mypushevent = new pushevent('push', datainit); mypushevent.data.text(); // should re
turn 'some sample text' browser compatibility the compatibility table on this page is generated from structured data.
PushManager.hasPermission() - Web APIs
the pushmanager.haspermission() method of the pushmanager interface re
turns a promise that resolves to the pushpermissionstatus of the requesting webapp, which will be one of granted, denied, or default.
Request.credentials - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // re
turns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification.
Request.headers - Web APIs
ders.append; we then create a new request along with a 2nd init parameter, passing headers in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; var myrequest = new request('flowers.jpg', myinit); mycontenttype = myrequest.headers.get('content-type'); // re
turns 'image/jpeg' specifications specification status comment fetchthe definition of 'headers' in that specification.
Request.mode - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // re
turns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
ResizeObserverEntry.borderBoxSize - Web APIs
the borderboxsize read-only property of the resizeobserverentry interface re
turns an array containing the new border box size of the observed element when the callback is run.
Response.headers - Web APIs
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.
Response.ok - Web APIs
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.
Response.status - Web APIs
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.
Response.statusText - Web APIs
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.
Response.type - Web APIs
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.
ServiceWorkerContainer.ready - Web APIs
it re
turns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an active worker.
ServiceWorkerGlobalScope: activate event - Web APIs
globalscope.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { re
turn caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: globalscope.onactivate = function(event) { ...
ServiceWorkerGlobalScope: contentdelete event - Web APIs
self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { re
turn promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); you can also set up the event handler using the serviceworkerglobalscope.ondelete property: self.oncontentdelete = (event) => { ...
ServiceWorkerGlobalScope: install event - Web APIs
eevent event handler property serviceworkerglobalscope.oninstall examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { re
turn cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ); }) ); }); you can also set...
ServiceWorkerGlobalScope.onactivate - Web APIs
then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { re
turn caches.delete(cachename); } }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specification.
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { re
turn promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); specifications specification status comment unknownthe definition of 'contentdelete' in that specification.
ServiceWorkerGlobalScope.oninstall - Web APIs
}; examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { re
turn cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ); }) ); }); specifications ...
ServiceWorkerGlobalScope.onnotificationclick - 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('/'); })); }; specifications specification status comment notifications apithe definition of 'onnotificationclick' in that specification.
ServiceWorkerGlobalScope.onpush - Web APIs
the data payload of the push message is available in the event object's data property (pushevent.data, which contains a pushmessagedata object.) self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { re
turn; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notificati...
TextEncoder.encoding - Web APIs
the textencoder.encoding read-only property re
turns a domstring containing the name of the encoding algorithm used by the specific encoder.
TextMetrics.actualBoundingBoxAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.actualboundingboxascent; // 8; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxascent' in that specification.
TextMetrics.actualBoundingBoxDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.actualboundingboxdescent; // 0; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxdescent' in that specification.
TextMetrics.actualBoundingBoxLeft - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.actualboundingboxleft; // 0; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxleft' in that specification.
TextMetrics.actualBoundingBoxRight - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.actualboundingboxright; // 15.633333333333333; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxright' in that specification.
TextMetrics.alphabeticBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.alphabeticbaseline; // -0; specifications specification html living standardthe definition of 'textmetrics.alphabeticbaseline' in that specification.
TextMetrics.emHeightAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.emheightascent; // 7.59765625; specifications specification html living standardthe definition of 'textmetrics.emheightascent' in that specification.
TextMetrics.emHeightDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.emheightdescent; // -2.40234375; specifications specification html living standardthe definition of 'textmetrics.emheightdescent' in that specification.
TextMetrics.fontBoundingBoxAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.fontboundingboxascent; // 10; specifications specification html living standardthe definition of 'textmetrics.fontboundingboxascent' in that specification.
TextMetrics.fontBoundingBoxDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.fontboundingboxdescent; // 3; specifications specification html living standardthe definition of 'textmetrics.fontboundingboxdescent' in that specification.
TextMetrics.hangingBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.hangingbaseline; // 6.078125; specifications specification html living standardthe definition of 'textmetrics.hangingbaseline' in that specification.
TextMetrics.ideographicBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // re
turns textmetrics object text.ideographicbaseline; // -1.201171875; specifications specification html living standardthe definition of 'textmetrics.ideographicbaseline' in that specification.
TextTrackList.length - Web APIs
the read-only texttracklist property length re
turns the number of entries in the texttracklist, each of which is a texttrack representing one track in the media element.
USBDevice.configuration - Web APIs
the configuration read only property of the usbdevice interface re
turns a usbconfiguration object for the currently selected interface for a paired usb device.
USBIsochronousOutTransferResult - Web APIs
properties usbisochronousouttransferresult.packetsread only re
turns an array of usbisochronousouttransferpacket objects containing the result of each request to send a packet to the device.
USVString - Web APIs
usvstring maps to a string when re
turned in javascript; it's generally only used for apis that perform text processing and need a string of unicode scalar values to operate on.
UserDataHandler - Web APIs
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.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
the read-only droppedvideoframes property of the videoplaybackquality interface re
turns the number of video frames which have been dropped rather than being displayed since the last time the media was loaded into the htmlvideoelement.
VideoPlaybackQuality - Web APIs
a videoplaybackquality object is re
turned by the htmlvideoelement.getvideoplaybackquality() method and contains metrics that can be used to determine the playback quality of a video.
VideoTrack.sourceBuffer - Web APIs
the read-only videotrack property sourcebuffer re
turns the sourcebuffer that created the track, or 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.
VideoTrackList.length - Web APIs
the read-only videotracklist property length re
turns the number of entries in the videotracklist, each of which is a videotrack representing one video track in the media element.
VisualViewport.offsetTop - Web APIs
the offsettop read-only property of the visualviewport interface re
turns the offset of the top edge of the visual viewport from the top edge of the layout viewport in css pixels.
VisualViewport.offsetleft - Web APIs
the offsetleft read-only property of the visualviewport interface re
turns the offset of the left edge of the visual viewport from the left edge of the layout viewport in css pixels.
VisualViewport.pageLeft - Web APIs
the pageleft read-only property of the visualviewport interface re
turns the x coordinate of the left edge of the visual viewport relative to the initial containing block origin, in css pixels.
VisualViewport.pageTop - Web APIs
the pagetop read-only property of the visualviewport interface re
turns the y coordinate of the top edge of the visual viewport relative to the initial containing block origin, in css pixels.
VisualViewport.scale - Web APIs
the scale read-only property of the visualviewport interface re
turns the pinch-zoom scaling factor applied to the visual viewport.
Visual Viewport API - Web APIs
let pendingupdate = false; function viewporthandler(event) { if (pendingupdate) re
turn; pendingupdate = true; requestanimationframe(() => { pendingupdate = false; var layoutviewport = document.getelementbyid('layoutviewport'); // since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin.
WEBGL_debug_renderer_info - Web APIs
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_draw_buffers.drawBuffersWEBGL() - Web APIs
t.color_attachment3_webgl ext.color_attachment4_webgl ext.color_attachment5_webgl ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl re
turn value none.
WEBGL_draw_buffers - Web APIs
xt.draw_buffer0_webgl ext.draw_buffer1_webgl ext.draw_buffer2_webgl ext.draw_buffer3_webgl ext.draw_buffer4_webgl ext.draw_buffer5_webgl ext.draw_buffer6_webgl ext.draw_buffer7_webgl ext.draw_buffer8_webgl ext.draw_buffer9_webgl ext.draw_buffer10_webgl ext.draw_buffer11_webgl ext.draw_buffer12_webgl ext.draw_buffer13_webgl ext.draw_buffer14_webgl ext.draw_buffer15_webgl a glenum re
turning a draw buffer.
WakeLock - Web APIs
methods request requests a wakelocksentinel object, which re
turns a promise that resolves with a wakelocksentinel object.
WaveShaperNode.curve - Web APIs
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; }; ...
WaveShaperNode.oversample - Web APIs
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; }; ...
Basic scissoring - Web APIs
" + "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.
Canvas size and WebGL - Web APIs
" + "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.
Creating 3D objects using WebGL - Web APIs
= [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // back 8, 9, 10, 8, 10, 11, // top 12, 13, 14, 12, 14, 15, // bottom 16, 17, 18, 16, 18, 19, // right 20, 21, 22, 20, 22, 23, // left ]; // now send the element array to gl gl.bufferdata(gl.element_array_buffer, new uint16array(indices), gl.static_draw); re
turn { position: positionbuffer, color: colorbuffer, indices: indexbuffer, }; } the indices array defines each face like a pair of triangles, specifying each triangle's vertices as an index into the cube's vertex arrays.
Lighting in WebGL - Web APIs
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().
Using shaders to apply color in WebGL - Web APIs
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.
Lifetime of a WebRTC session - Web APIs
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.
WebSocket.bufferedAmount - Web APIs
the websocket.bufferedamount read-only property re
turns the number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
WebSocket.protocol - Web APIs
the websocket.protocol read-only property re
turns the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the websocket object, or the empty string if no connection is established.
window.requestIdleCallback() - Web APIs
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.
Window.screen - Web APIs
the window property screen re
turns a reference to the screen object associated with the window.
Window.scrollMaxX - Web APIs
the window.scrollmaxx read-only property re
turns the maximum number of pixels that the document can be scrolled horizontally.
Window.scrollMaxY - Web APIs
the window.scrollmaxy read-only property re
turns the maximum number of pixels that the document can be scrolled vertically.
Window.showModalDialog() - Web APIs
syntax re
turnval = window.showmodaldialog(uri[, arguments][, options]); re
turnval holds the re
turnvalue property as set by the document specified by uri.
Window.speechSynthesis - Web APIs
the speechsynthesis read-only property of the window object re
turns a speechsynthesis object, which is the entry point into using web speech api speech synthesis functionality.
Window.toolbar - Web APIs
the window.toolbar property re
turns the toolbar object, whose visibility can be toggled in the window.
Window.visualViewport - Web APIs
the visualviewport read-only property of the window interface re
turns a visualviewport object representing the visual viewport for a given window.
Window.window - Web APIs
thus, the following expressions all re
turn the same window object: window.window window.window.window window.window.window.window // ...
WindowClient.focused - Web APIs
vent.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) { if(!client.focused) re
turn client.focus(); } } } if (clients.openwindow) re
turn clients.openwindow('/'); })); }); specifications specification status comment service workersthe definition of 'windowclient: focused' in that specification.
WindowClient.visibilityState - Web APIs
example event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (let i = 0; i < clientlist.length; i++) { let client = clientlist[i]; if (client.url == '/' && 'focus' in client) { if (client.visibilitystate === 'hidden') re
turn client.focus(); } } } if (clients.openwindow) { re
turn clients.openwindow('/'); } })); }); specifications specification status comment service workersthe definition of 'visibilitystate' in that specification.
WritableStreamDefaultWriter.ready - Web APIs
the ready read-only property of the writablestreamdefaultwriter interface 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.
XDomainRequest - Web APIs
syntax var xdr = new xdomainrequest(); re
turns a new xdomainrequest object, which can then be used to make and manage these requests.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
let error = cc["@mozilla.org/dom-error;1"].createinstance(ci.nsidomdomerror); error.wrappedjsobject.init(errname); re
turn error; // xxx: errtype goes unused } function dumpsecurityinfo(xhr, error) { let channel = xhr.channel; try { dump("connection status:\n"); if (!error) { dump("\tsucceeded\n"); } else { dump("\tfailed: " + error.name + "\n"); } let secinfo = channel.securityinfo; // print general connection security state dump("security information:\n"); ...
Synchronous and asynchronous requests - Web APIs
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).
XMLHttpRequest.abort() - Web APIs
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().
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...
XRWebGLLayerInit.depth - Web APIs
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.
XRWebGLLayerInit - Web APIs
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.
ARIA live regions - Accessibility
<input type="text" id="year" value="1990" onblur="change(event)"/> </label> </div> <div id="date-output" aria-live="polite"> the set year is: <span id="year-output">1990</span> </div> function change(event) { var yearout = document.getelementbyid("year-output"); switch (event.target.id) { case "year": yearout.innerhtml = event.target.value; break; default: re
turn; } }; without aria-atomic="true" the screenreader announces only the changed value of year.
ARIA Screen Reader Implementors Guide - Accessibility
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.
Using the aria-describedby attribute - Accessibility
<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.
Using the slider role - Accessibility
<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.
ARIA: cell role - Accessibility
that row, in
turn, can be nested within an element with role="rowgroup", and should be nested within a grid, table or treegrid.
ARIA: document role - Accessibility
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.
ARIA: gridcell role - Accessibility
<div role="columnheader">number of moons</div> </div> </div> <div role="rowgroup"> <div role="row"> <div role="gridcell">jupiter</div> <div role="gridcell">142,984</div> <div role="gridcell">9.9</div> <div role="gridcell">778.6</div> <div role="gridcell">67</div> </div> </div> <div role="rowgroup"> <div role="row"> <div role="gridcell">sa
turn</div> <div role="gridcell">120,536</div> <div role="gridcell">10.7</div> <div role="gridcell">1433.5</div> <div role="gridcell">62</div> </div> </div> </div> accessibility concerns support for gridcell and certain gridcell-related aria roles and properties have poor support with assistive technologies.
ARIA: Navigation Role - Accessibility
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.
ARIA: button role - Accessibility
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.
ARIA: listbox role - Accessibility
<p id="listbox1label" role="label">select a color:</p> <div role="listbox" tabindex="0" id="listbox1" aria-labelledby="listbox1label" onclick="re
turn listitemclick(event);" onkeydown="re
turn listitemkeyevent(event);" onkeypress="re
turn listitemkeyevent(event);" aria-activedescendant="listbox1-1"> <div role="option" id="listbox1-1" class="selected" aria-selected="true">green</div> <div role="option" id="listbox1-2">orange</div> <div role="option" id="listbox1-3">red</div> <div role="option" id="listbox1-4">blue</div> <...
Basic form hints - Accessibility
"phone" id="phone" aria-required="false"/> </div> <div> <label for="email">* e-mail:</label> <input type="text" value="email" id="email" aria-required="true"/> </div> </form> the script that validates the form entry would look something like this: var validate = function () { var emailelement = document.getelementbyid(emailfieldid); var valid = emailvalid(formdata.email); // re
turns true if valid, false otherwise emailelement.setattribute("aria-invalid", !valid); setelementbordercolour(emailelement, valid); // sets the border to red if second arg is false }; providing helpful error messages read how to use aria alerts to enhance forms.
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 ...
Keyboard - Accessibility
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").
-webkit-touch-callout - CSS: Cascading Style Sheets
formal definition initial valuedefaultapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax default | none examples
turn off touch callout .example { -webkit-touch-callout: none; } specifications not part of any standard.
:active - CSS: Cascading Style Sheets
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.
:scope - CSS: Cascading Style Sheets
javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.call(selected, function (element) { re
turn '#' + element.getattribute('id'); }).join(', '); html <div id="context"> <div id="element-1"> <div id="element-1.1"></div> <div id="element-1.2"></div> </div> <div id="element-2"> <div id="element-2.1"></div> </div> </div> <p> selected elements ids : <span id="results"></span> </p> result specifications specification status com...
:visited - CSS: Cascading Style Sheets
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.
@media - CSS: Cascading Style Sheets
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.
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
iv { width: 300px; height: 300px; background: url('https://mdn.mozillademos.org/files/8543/br.png'), url('https://mdn.mozillademos.org/files/8545/tr.png'); background-blend-mode: luminosity; } description for each pixel among the layers to which it is applied, a blend mode takes the colors of the foreground and the background, perfoms a calculation on them, and re
turns a new color value.
hue-rotate() - CSS: Cascading Style Sheets
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.
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; ...
linear-gradient() - CSS: Cascading Style Sheets
syntax /* a gradient tilted 45 degrees, starting blue and finishing red */ linear-gradient(45deg, blue, red); /* a gradient going from the bottom right to the top left corner, starting blue and finishing red */ linear-gradient(to left top, blue, red); /* color stop: a gradient 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 gr...
offset-rotate - CSS: Cascading Style Sheets
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.
overflow-anchor - CSS: Cascading Style Sheets
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.
rotate - CSS: Cascading Style Sheets
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.
symbols() - CSS: Cascading Style Sheets
[ <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.
text-size-adjust - CSS: Cascading Style Sheets
one in other cases (and then not modifiable).applies toall elementsinheritedyespercentagesyes, refer to the corresponding size of the text fontcomputed valueas specifiedanimation typediscrete formal syntax none | auto | <percentage> examples basic disabling usage as hinted at above, on a properly designed responsive site the text-size-adjust behavior is not needed, so developers can elect to
turn it off by specifying a vlaue of none: p { -webkit-text-size-adjust: none; text-size-adjust: none; } specifications specification status comment css mobile text size adjustment module level 1the definition of 'text-size-adjust' in that specification.
<transform-function> - CSS: Cascading Style Sheets
orm: rotatex(90deg) translatez(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotatex(-90deg) translatez(50px); } .select-form { margin-top: 50px; } javascript const selectelem = document.queryselector('select'); const example = document.queryselector('#example-element'); selectelem.addeventlistener('change', () => { if(selectelem.value === 'choose a function') { re
turn; } else { example.style.transform = `rotate3d(1, 1, 1, 30deg) ${selectelem.value}`; settimeout(function() { example.style.transform = 'rotate3d(1, 1, 1, 30deg)'; }, 2000) } }) result specifications specification status comment css transforms level 2the definition of '<transform-function>' in that specification.
Math (math) - EXSLT
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.
Regular expressions (regexp) - EXSLT
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.
Strings (str) - EXSLT
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
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.
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(); ...
Using HTML sections and outlines - Developer guides
me"); </script> <![endif]--> <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> note: this code will also cause the html validator to re
turn errors.
Localizations and character encodings - Developer guides
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.
Writing forward-compatible websites - Developer guides
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.
Date and time formats used in HTML - HTML: Hypertext Markup Language
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.
<dfn>: The Definition element - HTML: Hypertext Markup Language
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>.
<input type="button"> - HTML: Hypertext Markup Language
r ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(0,0,0)'; ctx.fillrect(0,0,width,height); var colorpicker = document.queryselector('input[type="color"]'); var sizepicker = document.queryselector('input[type="range"]'); var output = document.queryselector('.output'); var clearbtn = document.queryselector('input[type="button"]'); // covert degrees to radians function degtorad(degrees) { re
turn degrees * math.pi / 180; }; // update sizepicker output value sizepicker.oninput = function() { output.textcontent = sizepicker.value; } // store mouse pointer coordinates, and whether the button is pressed var curx; var cury; var pressed = false; // update mouse pointer coordinates document.onmousemove = function(e) { curx = (window.event) ?
<input type="checkbox"> - HTML: Hypertext Markup Language
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.
<input type="hidden"> - HTML: Hypertext Markup Language
2; line-height: 2; text-align: right; padding-right: 20px; } input, textarea { flex: 7; font-family: sans-serif; font-size: 1.1rem; padding: 5px; } textarea { height: 60px; } the server would set the value of the hidden input with the id "postid" to the id of the post in its database before sending the form to the user's browser and would use that information when the form is re
turned to know which database record to update with modified information.
<input type="submit"> - HTML: Hypertext Markup Language
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.
<input type="time"> - HTML: Hypertext Markup Language
dding-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="time">, we create a new <input> element, try setting its type to time, then immediately check what its type is set to — non-supporting browsers will re
turn text, because the time type falls back to type text.
<ol>: The Ordered List element - HTML: Hypertext Markup Language
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>.
title - HTML: Hypertext Markup Language
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.
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).
Link types - HTML: Hypertext Markup Language
<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).
MIME types (IANA media types) - HTTP
examples include multipart/form-data (for data produced using the formdata api) and multipart/byteranges (defined in rfc 7233: 5.4.1 and used with http's 206 "partial content" response re
turned when the fetched data is only part of the content, such as is delivered using the range header).
HTTP conditional requests - HTTP
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.
Content negotiation - HTTP
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.
Access-Control-Allow-Credentials - HTTP
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.
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
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.
Content-Type - HTTP
in responses, a content-type header tells the client what the content type of the re
turned content actually is.
Feature-Policy: autoplay - HTTP
when this policy is enabled and there were no user gestures, the promise re
turned by htmlmediaelement.play() will reject with a domexception.
Feature-Policy: camera - HTTP
when this policy is enabled, the promise re
turned by mediadevices.getusermedia() will reject with a notallowederror.
Feature-Policy: midi - HTTP
when this policy is enabled, the promise re
turned by navigator.requestmidiaccess() will reject with a domexception.
Feature-Policy: screen-wake-lock - HTTP
the http feature-policy header screen-wake-lock directive controls whether the current document is allowed to use screen wake lock api to indicate that device should not dim or
turn off the screen.
Feature-Policy: xr-spatial-tracking - HTTP
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.
If-None-Match - HTTP
when the condition fails for get and head methods, then the server must re
turn http status code 304 (not modified).
Location - HTTP
location is a header associated with the response, while content-location is associated with the entity re
turned.
Server-Timing - HTTP
consider to control which metrics are re
turned when and to whom on the server side.
Strict-Transport-Security - HTTP
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.
X-DNS-Prefetch-Control - HTTP
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".
HEAD - HTTP
the http head method requests the headers that would be re
turned if the head request's url was instead requested with the http get method.
Protocol upgrade mechanism - HTTP
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.
Proxy servers and tunneling - HTTP
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
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.
Redirections in HTTP - HTTP
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.
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 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.
406 Not Acceptable - HTTP
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.
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.
501 Not Implemented - HTTP
the only methods that servers are required to support (and therefore that must not re
turn 501) are get and head.
HTTP
the client then re
turns the cookie's value with every request to the same server in the form of a cookie request header.
JavaScript data types and data structures - JavaScript
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.
TypeError: cyclic object value - JavaScript
the snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of json.stringify(): const getcircularreplacer = () => { const seen = new weakset(); re
turn (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { re
turn; } seen.add(value); } re
turn value; }; }; json.stringify(circularreference, getcircularreplacer()); // {"otherdata":123} ...
SyntaxError: missing formal parameter - JavaScript
all these function declarations fail, as they are providing 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) { retur...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
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.
arguments.length - JavaScript
*/) { 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
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).
AsyncFunction - JavaScript
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 });...
Greater than (>) - JavaScript
the greater than operator (>) re
turns true if the left operand is greater than the right operand, and false otherwise.
Logical nullish assignment (??=) - JavaScript
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
the remainder operator (%) re
turns the remainder left over when one operand is divided by a second operand.
Spread syntax (...) - JavaScript
however, an array can be easily used with new thanks to spread syntax: const datefields = [1970, 0, 1]; // 1 jan 1970 const d = 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...
Unary plus (+) - JavaScript
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 constructors and functions invoked using the new operator, new.target re
turns a reference to the constructor or function.
import.meta - JavaScript
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.
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...
JavaScript reference - JavaScript
webassembly.instance webassembly.memory webassembly.table webassembly.compileerror webassembly.linkerror webassembly.runtimeerror statements javascript statements and declarations control flowblock break continue empty if...else switch throw try...catch declarations var let const functions and classes function function* async function re
turn class iterations do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript expressions and operators.
JavaScript
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.
Web app manifests
ttps://play.google.com/store/apps/details?id=cheeaun.hackerweb" }] } deploying a manifest web app manifests are deployed in your html pages using a <link> element in the <head> of a document: <link rel="manifest" href="/manifest.webmanifest"> note: the .webmanifest extension is specified in the media type registration section of the specification (the response of the manifest file should re
turn content-type: application/manifest+json).
Authoring MathML - MathML
e following function verifies the mathml support by testing the mspace element (you may replace mspace with mpadded): function hasmathmlsupport() { var div = document.createelement("div"), box; div.innerhtml = "<math><mspace height='23px' width='77px'/></math>"; document.body.appendchild(div); box = div.firstchild.firstchild.getboundingclientrect(); document.body.removechild(div); re
turn math.abs(box.height - 23) <= 1 && math.abs(box.width - 77) <= 1; } alternatively, the following ua string sniffing will allow to detect the rendering engines with native mathml support (gecko and webkit).
MathML
newsgroup rss feed matrix chat room wiki used by mozilla contributors w3c math home www-math w3.org mail archive tools w3c validator mathzilla firefox add-on collection texzilla — javascript latex to mathml converter (live demo, firefox os webapp, firefox add-on, using in a web page, js program etc) latexml - convert latex documents into html+mathml web pages web equation -
turn handwritten equations into mathml or latex mathjax - cross-browser javascript display engine for mathematics.
Performance budgets - Web Performance
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.
class - SVG: Scalable Vector Graphics
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).
d - SVG: Scalable Vector Graphics
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.
Content type - SVG: Scalable Vector Graphics
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).
<script> - SVG: Scalable Vector Graphics
ewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <script> // <![cdata[ window.addeventlistener('domcontentloaded', () => { function getcolor () { const r = math.round(math.random() * 255).tostring(16).padstart(2,'0') const g = math.round(math.random() * 255).tostring(16).padstart(2,'0') const b = math.round(math.random() * 255).tostring(16).padstart(2,'0') re
turn `#${r}${g}${b}` } document.queryselector('circle').addeventlistener('click', (e) => { e.target.style.fill = getcolor() }) }) // ]]> </script> <circle cx="5" cy="5" r="4" /> </svg> attributes crossorigin this attribute defines cors settings as define for the html <script> element.
Scripting - SVG: Scalable Vector Graphics
representing an svg document is to look at htmliframeelement.contentdocument (if the document is presented in an <iframe>) or htmlobjectelement.contentdocument (if the document is presented in an <object> element), like this: var svgdoc = document.getelementbyid("iframe_element").contentdocument; in addition, the <iframe>, <embed>, and <object> elements offer a method, getsvgdocument(), which re
turns the xmldocument representing the element's embedded svg or null if the element doesn't represent an svg document.
Securing your site - Web security
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.
Subresource Integrity - Web security
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.
Tutorials
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.
Using shadow DOM - Web Components
= elementref.attachshadow({mode: 'closed'}); open means that you can access the shadow dom using javascript written in the main page context, for example using the element.shadowroot property: let myshadowdom = mycustomelem.shadowroot; if you attach a shadow root to a custom element with mode: closed set, you won't be able to access the shadow dom from the outside — mycustomelem.shadowroot re
turns null.
string - XPath
re
turns a string notes if the object is a node-set, the string value of the first node in the set is re
turned.
Compiling a New C/C++ Module to WebAssembly - WebAssembly
<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
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.