Search completed in 1.30 seconds.
7500 results for "turn":
Your results are loading. Please wait...
Function return values - Learn web development
previous overview: building blocks next there's one last essential concept about functions for us to discuss — return values.
... some functions don't return 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 return useful values.
...And 27 more matches
return - JavaScript
the return statement ends function execution and specifies a value to be returned to the function caller.
... syntax return [[expression]]; expression the expression whose value is to be returned.
... if omitted, undefined is returned instead.
...And 11 more matches
Error codes returned by Mozilla APIs
ns_error_factory_not_registered (0x80040154) returned when a service could not be found.
... ns_error_factory_register_again (0x80040155) this error is returned when registering a component and the registration should try registering again later.
...this error may be returned 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 return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.
... message warning: unreachable code after return statement (firefox) error type warning what went wrong?
... unreachable code after a return statement might occur in these situations: when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.
...And 5 more matches
Generator.prototype.return() - JavaScript
the return() method returns the given value and finishes the generator.
... syntax gen.return(value) parameters value the value to return.
... return value the value that is given as an argument.
...And 5 more matches
Components.returnCode
components.returncode is a property which can hold an xpcom return code additionally to the value returned by the return statement.
... note that components.returncode is currently non-functional due to bug 287107.
... usage components.returncode is a property that can be used to indicate to an xpcom caller of the javascript method that the method is returning a specific nsresult code.
...And 4 more matches
Event.returnValue - Web APIs
WebAPIEventreturnValue
the event property returnvalue indicates whether the default action for this event has been prevented or not.
... note: while returnvalue has been adopted into the dom standard, it is present primarily to support existing code.
... syntax event.returnvalue = bool; var bool = event.returnvalue; 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 returnvalue property of the htmldialogelement interface gets or sets the return value for the <dialog>, usually to indicate which button the user pressed to close it.
... syntax dialoginstance.returnvalue = 'myreturnvalue'; var myreturnvalue = dialoginstance.returnvalue; value a domstring representing the returnvalue 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.returnvalue = 'favanimal'; function opencheck(dialog) { if (dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } function handleuserinput(returnvalue) { if (returnvalue === 'cancel' || returnvalue == null) { // user canceled the dialog, do nothing } else if (returnvalue === 'confirm...
...And 3 more matches
SyntaxError: return not in function - JavaScript
the javascript exception "return (or yield) not in function" occurs when a return or yield statement is called outside of a function.
... message syntaxerror: 'return' statement outside of function (edge) syntaxerror: return not in function (firefox) syntaxerror: yield not in function (firefox) error type syntaxerror.
... a return or yield statement is called outside of a function.
...And 3 more matches
JS_SetCallReturnValue2
causes a native to return a reference value (as allowed by ecma 262-3 §11.2.3).
... syntax void js_setcallreturnvalue2(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 returned 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 ...
Return Codes - Archive of obsolete content
return codes the methods described in this chapter can return any of the following return codes.
How to turn off form autocompletion - Web security
this means that the criterion can be passed (by adding the relevant autocomplete attributes to individual form fields) even when autocompletion for the form itself has been turned off.
Index - Web APIs
WebAPIIndex
9 abortcontroller.signal api, abortcontroller, experimental, fetch, property, reference, signal the signal read-only property of the abortcontroller interface returns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired.
... 11 abortsignal.aborted api, abortsignal, experimental, property, reference, aborted the aborted read-only property returns 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 returns true if the range's start position and end position are the same.
...And 1675 more matches
Index
if so, int_fits_in_jsval returns true, and i can be cast to jsval by calling int_to_jsval(i).
... otherwise, int_fits_in_jsval returns false.
... 34 js::compileoptions jsapi reference, reference, référence(2), spidermonkey some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain.
...And 178 more matches
Index
MozillaTechXPCOMIndex
24 components.issuccesscode xpcom, xpcom:language bindings, xpconnect determines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.
... 28 components.returncode xpcom:language bindings, xpconnect no summary!
...it returns 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
returns the function returns one of these values: if successful, secsuccess.
... the policy flags for all cipher suites are turned off by default, disallowing all cipher suites.
... returns the function returns 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, returns 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 returns the node's owner document.
... the return 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 return the child index which then can be used when calling rowindex() and columnindex().
...this object attribute is obtained by parsing the attribute string returned 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 returned 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);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }return this;};if(c){d.implement(c);}return 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); return 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){return($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];}return 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];}}return b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}return 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
WebAPIDocument
document.anchorsread only returns a list of all of the anchors in the document.
... document.body returns the <body> or <frameset> node of the current document.
... document.charactersetread only returns the character set being used by the document.
...And 77 more matches
Shell global objects
timesaccessed returns 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 return '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 returns.
...And 73 more matches
Parser API
by default, the parsing returns 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 returned ast nodes.
...this string is not meaningful to the parsing process, but is produced as part of the source location information in the returned ast nodes.
...And 71 more matches
IAccessibleText
when a method doesn't implement this method it must return s_false.
... return value e_invalidarg if bad [in] passed.
...attributes() returns text() attributes.
...And 67 more matches
nsIDOMWindowUtils
imageanimationmode unsigned short returns the image animation mode of the window.
... imeisopen boolean returns the ime open state.
... imestatus unsigned long returns the current ime status.
...And 60 more matches
Window - Web APIs
WebAPIWindow
staticrange read only returns a staticrange() constructor which creates a staticrange object.
... window.console read only returns a reference to the console object which provides access to the browser's debugging console.
... window.controllers read only returns the xul controller objects for the current chrome window.
...And 56 more matches
Expressions and operators - JavaScript
(x = y) return value and chaining like most expressions, assignments like x = y have a return value.
...assigning the expression or logging it: const z = (x = y); // or equivalently: const z = x = y; console.log(z); // log the return value of the assignment x = y.
... console.log(x = y); // or log the return value directly.
...And 56 more matches
Debugger.Object - Firefox Developer Tools
this accessor returns 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, return an array with one element per parameter, each of which is undefined.
... if the referent is a function proxy, return 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: returns a reference to the parent <form> element.
... formaction string: returns / sets the element's formaction attribute, containing the uri of a program that processes information submitted by the element.
... formenctype string: returns / 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() returns the caption for the table.
... the returned 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 returned, else a null pointer is returned.
...And 50 more matches
Starting WebLock
ns_imethodimp weblock::observe(nsisupports *asubject, const char *atopic, const prunichar *adata) { return 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)) return 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)) return 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
WebAPINavigator
standard navigatorid.appcodename read only returns the internal "code" name of the current browser.
... do not rely on this property to return the correct value.
... navigatorid.appname read only returns 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]; return 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){ return (document.getelementbyid) ?
...the method returns 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 returned at some point in the future.
... there is no guarantee of exactly when the operation will complete and the result will be returned, but there is a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case.
... generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is.
...And 45 more matches
tabbrowser - Archive of obsolete content
selectedbrowser type: browser element this read-only property returns the currently displayed browser element.
... tabcontainer type: tabs element returns 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 ) return type: no return value add a progress listener to the browser which will monitor loaded documents.
...And 44 more matches
Debugger - Firefox Developer Tools
this function should return a resumption value, which determines how the debuggee should continue.
...most handler functions can return a resumption value indicating how the debuggee’s execution should proceed.
... this method’s return 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)) { return; } 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(); return false; } if (bend && binvert) { odmn.backw = !odmn.backw; odmn.reversals--; } return 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); return 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"); } return new this(octx, octx.perform, nrate || null, nlen || null, octx.create || null, octx.prepare || null); }; /* warning!
...And 42 more matches
Element - Web APIs
WebAPIElement
element.attributes read only returns a namednodemap object containing the assigned attributes of the corresponding html element.
... element.classlist read only returns a domtokenlist containing the list of class attributes.
... element.clientheight read only returns a number representing the inner height of the element.
...And 42 more matches
source-editor.jsm
return value true if there are changes that can be redone, otherwise false.
... return value true if there are changes that can be undone, otherwise false.
... return value returns 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
return value: a promise that is fulfilled with the toolbox instance once it has been initialized and the selected tool is loaded.
... return value: toolbox object or undefined if there's no toolbox for the given target..
... return 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)) return 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 returned 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) { return 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); return; } 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); return color; } function rgbacolor(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; return color; } function hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; return co...
...lor; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } 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) { return (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)) return ns_error_failure; // we are not setup??!!
... getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will return whether or not it is possible to call docommand.
... getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will return 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 returned 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) { return 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); return; } 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); return color; } function rgbacolor(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; return color; } function hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; return co...
...lor; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } 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) { return (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 returned 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 return the number parsed up to that point.
... if you query a non-existent array index, you'll get a value of undefined in return: 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
WebAPINode
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 return null or throw an exception, depending on circumstances.
... node.baseuriread only returns a domstring representing the base url of the document containing the node.
... node.childnodesread only returns 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) { return 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]; return 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 */); } return nidx; }; stringview.getutf8charlength = function (nchar) { return nchar < 0x80 ?
...And 35 more matches
Bytecode Descriptions
this is how we implement typeof step 2, making typeof nonexistingvariable return "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 return 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 returned 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 returning early.
... return value returns the id of the newly-inserted folder.
... return value returns the id of the newly-inserted folder.
...And 35 more matches
Math - JavaScript
static methods math.abs(x) returns the absolute value of x.
... math.acos(x) returns the arccosine of x.
... math.acosh(x) returns 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() returns the attributes specific to this iaccessible2 object, such as a cell's formula.
... [propget] hresult attributes( [out] bstr attributes ); parameters attributes return value s_false returned if there is nothing to return, [out] value is null.
...extendedrole() returns the extended role.
...And 34 more matches
lang/type - Archive of obsolete content
globals functions isundefined(value) returns true if value is undefined, false otherwise.
... returns boolean : boolean indicating if value is undefined.
... isnull(value) returns 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) return 1; // enter the new global object's compartment.
... if (!js_initstandardclasses(cx, global)) return 1; // your application code here.
... return 0; } int main(int argc, const char *argv[]) { // initialize the js engine.
...And 33 more matches
nsIHTMLEditor
returninparagraphcreatesnewparagraph boolean a boolean indicating if a return key pressed in a paragraph creates another paragraph or just inserts a <br> at the caret.
... boolean breakisvisible( in nsidomnode anode ); parameters anode return 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 return 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 returnstringonly); native code only!
... return 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 return 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 returns 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, return an array with one element per parameter, each of which is undefined.
... if the referent is a function proxy, return an empty array.
...And 33 more matches
lang/functional - Archive of obsolete content
globals functions method(lambda) takes a function and returns 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) { return target.number *= x; } function add (target, x) { return 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 returned.
... returns function : the wrapped lambda.
...And 32 more matches
Space Manager Detailed Design - Archive of obsolete content
*/ nsiframe* getframe() const { return mframe; } /** * translate the current origin by the specified (dx, dy).
... */ void translate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * returns the current translation from local coordinate space to * world coordinate space.
... */ void gettranslation(nscoord& ax, nscoord& ay) const { ax = mx; ay = my; } /** * returns 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 return 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) { return number * number; } the function square takes one parameter, called number.
... the function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself.
...And 32 more matches
Index - XPath
WebXPathIndex
18 boolean xslt, xslt_reference the boolean function evaluates an expression and returns true or false.
... 19 ceiling xslt, xslt_reference the ceiling function evaluates a decimal number and returns the smallest integer greater than or equal to the decimal number.
... 20 choose function, xpath, xslt the choose function returns one of the specified objects based on a boolean parameter.
...And 32 more matches
nsISessionStore
return value an nsidomnode representing the new tab, the content of which is a duplicate of atab.
... return value forgetclosedwindow() nsidomnode forgetclosedwindow( in unsigned long aindex ); parameters aindex is the index of the closed window to be removed (fifo ordered).
... return 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() returns 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 returns the number of milliseconds since 1 january, 1970, 00:00:00 utc, with leap seconds ignored.
...2 to 7) and returns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored.
...And 31 more matches
nsIVariant
return 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.) return value native code only!getasastring astring getasastring(); parameters none.
... return value the internal value is converted to a utf16 string.
...And 30 more matches
WebGLRenderingContext - Web APIs
webglrenderingcontext.getcontextattributes() returns a webglcontextattributes object that contains the actual context parameters.
... might return null, if the context is lost.
... webglrenderingcontext.iscontextlost() returns true if the context is lost, otherwise returns false.
...And 30 more matches
JSAPI Cookbook
} defining a function // javascript function justforfun() { return null; } /* jsapi */ bool justforfun(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); args.rval().setnull(); return true; } ...
... */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) return 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) return 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) return 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 returned.
... anode - the bookmark aiid - the return interface wanted.
... placesflavors generic_view_drop_types methods createfixeduri nsiuri createfixeduri(string aspec) takes in a spec and returns 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: returns / sets the element's accesskey attribute.
... autocapitalize string: returns / sets the element's capitalization behavior for user input.
... autocomplete autofocus boolean: returns / sets the element's autofocus attribute, indicating that the control should have input focus when the page loads cols unsigned long: returns / 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: return 'cat'.charat(1) // returns "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: return 'cat'[1] // returns "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) { return 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 returned 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 returns the currently focused item in the list box, which is only useful in a multiple selection list box.
... selectedcount type: integer returns the number of items that are currently selected.
... selectedindex type: integer returns the index of the currently selected item.
...And 28 more matches
richlistbox - Archive of obsolete content
currentitem type: listitem element returns the currently focused item in the list box, which is only useful in a multiple selection list box.
... selectedcount type: integer returns the number of items that are currently selected.
... selectedindex type: integer returns 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': return gen_csr; case 'e': return encrypt; case 'd': return decrypt; default: return 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; return secsuccess; } cleanup: if (data) { secitem_freeitem(data, pr_true); } return 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"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return 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"); } return 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) { return 1; } else { return 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)) { return null; } if (/^(?:true|false)$/i.test(svalue)) { return svalue.tolowercase() === "true"; } if (isfinite(svalue)) { return parsefloat(svalue); } if (isfinite(date.parse(svalue))) { return new date(svalue); } return svalue; } function jxontree (oxmlparent) { var nattrlen = 0, nlength = 0, scollectedtxt = ""; if (oxmlparent.haschildnodes()) { for (var onode, sprop, vcontent, nitem = ...
... jxontree.prototype.valueof = function () { return this.keyvalue; }; jxontree.prototype.tostring = function () { return string(this.keyvalue); }; jxontree.prototype.getitem = function (nitem) { if (nlength === 0) { return null; } var ncount = 0; for (var skey in this) { if (ncount === nitem) { return this[skey]; } ncount++; } return 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 return 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 returned for the popup to be displayed.
... minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number of results that must be returned for the popup to be displayed.
...And 27 more matches
Dict.jsm
items iterator returns an iterator over all of the items in the dictionary; each item is returned 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 returned is arbitrary, and may change without notice.
... keys iterator returns 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) return; 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) return; 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) return; 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) return; 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); return 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) return ui.displayerr...
...or(error); twitter.gettweetsfor(handle, funtion continuewith(error, tweets) { if (error) return 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 returns 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) { return ns_error_null_pointer; } *aresult = null; if (aiid.equals(kisupportsiid)) { *aresult = (void *) this; } if (!*aresult) { return ns_error_no_interface; } // add a reference addref(); return ns_ok; } ns_imethodimp_(nsrefcnt) sample::addref() { return ++mrefcnt; } ns_imethodimp_(nsrefcnt) sample::release() { if (--mrefcnt == 0) { delete this; return 0; } /...
.../ optional: return the reference count return mrefcnt; } object interface discovery inheritance is another very important topic in object oriented programming.
...in xpcom, all interface methods should return 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 returns an enumeration of the elements in a directory.
... parent nsifile this attribute returns the parent nsifile for this nsifile.
... example, this could return "/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 returns 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 returns 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 returns a domstring with the absolute url of the chosen media resource.
...And 26 more matches
Indexed collections - JavaScript
calling arr.length will return arraylength, but the array doesn't contain any elements.
...it always returns the index of the last element plus one.
... (in the example below, 'dusty' is indexed at 30, so cats.length returns 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 returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return 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)); return 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"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return 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"); } return rv; } /* * finalize macing.
...And 25 more matches
Proxy Auto-Configuration (PAC) file - HTTP
description returns a string describing the configuration.
... the format of this string is defined in return value format below.
... return value format the javascript function returns 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 returns undefined.
...And 25 more matches
Promise.prototype.then() - JavaScript
the then() method returns a promise.
...if the promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, the returned 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 returns the received argument).
...And 25 more matches
Modularization techniques - Archive of obsolete content
if the query is successful, queryinterface() will return ns_ok.
... if the object does not support the given interface, it will return ns_nointerface.
...a successful queryinterface() will call addref() on the requested interface before returning.
...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() { return "hello" }; hello(); the function returns "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 return 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 return 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 returns 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() return an nsiaccessible for a dom node in pres shell 0.
... return value the nsiaccessible for the given dom node.
... getaccessibleinshell() return 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 return false when the orientation is not drop_on.
... return 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 return false from candropbeforeafter().
...And 24 more matches
Comparing Reflect and Object methods - JavaScript
method name object reflect defineproperty() object.defineproperty() returns the object that was passed to the function.
... returns a typeerror if the property was not successfully defined on the object.
... reflect.defineproperty() returns 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 return to the panel, and destroy all other traces of the area within customizableui.
... parameters aproperties the specification for the widget return value a wrapper around the created widget.
... parameters awidgetid the id of the widget whose information you need return 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 return 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 returned that represents the requested cell regardless of whether the cell is currently visible (on the screen).
... return value an nsiaccessible object.
...And 23 more matches
nsIAnnotationService
return value returns a page annotation.
... return value returns an item annotation.
... return value returns a string value page annotation.
...And 23 more matches
nsIWindowMediator
return value pr_true if the position returned is different from the position given.
... getenumerator() return 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 returned 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 return 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 returns 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 return 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 returns 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 returns 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 returning one of the string values specified by the enum rtcpeerconnectionstate.currentlocaldescription read only the read-only property rtcpeerconnection.currentlocaldescription returns 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 returns 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 returns 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 returns a string representing the namespace uri associated with that prefix.
... resulttype: a constant that specifies the desired result type to be returned 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 returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return 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)); return 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"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return 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"); } return 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"); } return 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 returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return 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)); return 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"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return 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"); } return 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"); } return 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 * return 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); } return 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); } return 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 returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return 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)); return 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"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return 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"); } return 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"); } return 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 return "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 * return 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); } return 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 returns null if the value does not exist, or exists but is null.
... nsivariant get( in astring prop ); parameters prop property to return the value of.
... return value the property value as an nsivariant.
...And 22 more matches
io/file - Archive of obsolete content
returns the last component of the given path.
... for example, basename("/foo/bar/baz") returns "baz".
... if the path has no components, the empty string is returned.
...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 return codes need some memory var err; // error return codes when we try and install to the current browser var errblock1; // error return 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 return 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) return 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); return...
...And 21 more matches
Old Proxy API - Archive of obsolete content
calltrap is a variable-argument function(args) { return any; } that reifies “proxy(args)”.
... constructtrap is an optional variable-argument function(args) { return 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 return 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 returned 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 return any value.
... when newpromise is fulfilled, nothing happens, because no fulfillment callback is specified and the return value of the last then method is ignored.
...And 21 more matches
Microdata DOM API - Web APIs
it returns a nodelist containing the items with the specified types, or all types if no argument is specified.
...getitems( [ types ] ) returns 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 return 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 return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
... as the promise.prototype.then() and promise.prototype.catch() methods return promises, they can be chained.
...these methods also return 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 return 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 return true if there is another row afterwards at the same level.
... the getparentindex method is expected to return 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 returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return 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)); return 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"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return 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"); } return 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"); } return 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) return rv; rv = macupdate(ctxmac, ptext, ptextlen); if (rv != secsuccess) return rv; rv = macfinal(ctxmac, mac, maclen, maxlen); return 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 return the object that matches a given cid and iid pair.
...the key to this interface is that the return 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() returns 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 return.
... if it lies outside the valid range an empty string is returned.
...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() returns the number of columns occupied by this cell accessible.
...[propget] hresult columnextent( [out] long ncolumnsspanned ); parameters ncolumnsspanned returns the 1 based column extent of the specified cell.
... return value s_ok.
...And 20 more matches
this - JavaScript
function f1() { return 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 return this; } f2() === undefined; // true in the second example, this should be undefined, bec...
...as a result, they incorrectly returned the window object.
... derived classes must not return before calling super(), unless they return an object or have no constructor at all.
...And 20 more matches
async function - JavaScript
return value a promise which will be resolved with the value returned 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 return value of the await expression.
... async functions always return a promise.
...And 20 more matches
window/utils - Archive of obsolete content
the exception is the windows() function which returns an array of currently opened windows.
... returns nsidomwindow: the topmost browser window.
... getinnerid(window) returns 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 returned by nss.
...the data will be processed and either returned directly or sent to a callback function registered in the context.
... * returns 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; } } return h...
...And 19 more matches
HTMLElement - Web APIs
htmlelement.accesskeylabel read only returns a domstring containing the element's assigned access key.
... htmlelement.iscontenteditable read only returns a boolean that indicates whether or not the content of the element can be edited.
... htmlorforeignelement.dataset read only returns 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() returns 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() returns an svgpoint representing the x and y coordinates in user space utilizing the browser's distance-along-a-path algorithm.
... svgpathelement.getpathsegatlength() returns 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 returns a promise, you can attach .then() to the end and include callbacks inside it for success cases, or you can insert .catch() on the end if you want to include a failure callback.
... sync try { const value = myfunction(); console.log(value); } catch(err) { console.log(err); } async myfunction().then((value) => { console.log(value); }).catch((err) => { console.log(err); }); in the first example, we have to wait for myfunction() to run and return value before any more of the code can execute.
...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); }); return 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); }; return 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) return; 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) return; 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 returns a number value of the element size.
... bigint64array.name returns the string value of the constructor name.
... instance properties bigint64array.prototype.buffer returns the arraybuffer referenced by the bigint64array.
...And 19 more matches
BigUint64Array - JavaScript
static properties biguint64array.bytes_per_element returns a number value of the element size.
... biguint64array.name returns the string value of the constructor name.
... instance properties biguint64array.prototype.buffer returns the arraybuffer referenced by the biguint64array.
...And 19 more matches
Float32Array - JavaScript
static properties float32array.bytes_per_element returns a number value of the element size.
... float32array.name returns the string value of the constructor name.
... instance properties float32array.prototype.buffer returns 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 returns a number value of the element size.
... float64array.name returns the string value of the constructor name.
... instance properties float64array.prototype.buffer returns 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 returns a number value of the element size.
... int16array.name returns the string value of the constructor name.
... instance properties int16array.prototype.buffer returns 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 returns a number value of the element size.
... int32array.name returns the string value of the constructor name.
... instance properties int32array.prototype.buffer returns 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 returns a number value of the element size.
... int8array.name returns the string value of the constructor name.
... instance properties int8array.prototype.buffer returns 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 return an empty object.
... otherwise, it will return an object of a type that corresponds to the given value.
... if the value is an object already, it will return the value.
...And 19 more matches
TypedArray - JavaScript
static properties typedarray.bytes_per_element returns a number value of the element size for the different typedarray objects.
... typedarray.name returns the string value of the constructor name (e.g, "int8array").
... instance properties typedarray.prototype.buffer returns the arraybuffer referenced by the typed array.
...And 19 more matches
Uint16Array - JavaScript
static properties uint16array.bytes_per_element returns a number value of the element size.
... uint16array.name returns the string value of the constructor name.
... instance properties uint16array.prototype.buffer returns 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 returns a number value of the element size.
... uint32array.name returns the string value of the constructor name.
... instance properties uint32array.prototype.buffer returns 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 returns a number value of the element size.
... uint8array.name returns the string value of the constructor name.
... instance properties uint8array.prototype.buffer returns 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 returns a number value of the element size.
... uint8clampedarray.name returns the string value of the constructor name.
... instance properties uint8clampedarray.prototype.buffer returns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus read only.
...And 19 more matches
tabs/utils - Archive of obsolete content
returns tabbrowser : gettabcontainer(window) get the tabbrowser's tabcontainer property.
... returns tabcontainer : gettabs(window) returns the tabs for the specified window.
... if you omit window, this function will return 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(); // returns 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 returns 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) { return ("the java exception is " + e); } return 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() returns an array of nsiuri objects representing the current xml binding for the specified element.
... return value an array of nsiuri objects representing the current xbl binding (if any) for the element and its hierarchy of base bindings.
... getchildrenfornode() returns 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 returns an array of interfaces.
... return value an nsidomdomrequest object.
... invalidnetwork the network must be in the return of getavailablenetworks.
...And 18 more matches
nsIDOMWindowInternal
self nsidomwindowinternal readonly: returns an object reference to the window object.
... navigator nsidomnavigator readonly: returns a reference to the navigator object.
... screen nsidomscreen readonly: returns 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 returns the number of child keys.
... valuecount unsigned long this attribute returns the number of values under this key.
...it is still possible to enumerate values that have other types (that is, getvaluetype() may return a type not defined below).
...And 18 more matches
eval() - JavaScript
return value the completion value of evaluating the given code.
... if the completion value is empty, undefined is returned.
... if the argument of eval() is not a string, eval() returns 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 returns (return values).
... signatures and parameters the signature is a sequence of parameter type declarations followed by a list of return type declarations.
... it is worth noting here that: the absence of a (result) means the function doesn’t return anything.
...And 18 more matches
Client-side form validation - Learn web development
validationmessage: returns 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 return an empty string.
... validity: returns 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 returns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future.
... add this next: request.responsetype = 'text'; fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown.
... xhr allows you to handle this using its onload event handler — this is run when the load event fires (when the response has returned).
...And 17 more matches
NSS PKCS11 Functions
returns the function returns one of these values: if successful, a pointer to a secmodmodule.
...returns the function returns one of these values: if successful, secsuccess.
...returns the function returns one of these values: if successful, secsuccess).
...And 17 more matches
Using Objective-C from js-ctypes
while ([synth isspeaking]) {} [synth release]; return 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 returns it.
...sel_registername receives the name of the selector, and returns 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 returned it is rendered by the web browser.
... at the end of the message we see the body content — which contains the actual html returned by the request.
... static sites a static site is one that returns the same hard coded content from the server whenever a particular resource is requested.
...And 16 more matches
Sqlite.jsm
openconnection(options) returns a promise that resolves to an opened connection instance or is rejected if an error occurred while opening the database.
... this function returns a promise that will be resolved when the database has closed.
... await conn.close(); throw e; } clone(readonly) this function returns a clone of the current connection-promise.
...And 16 more matches
JS::CompileOptions
methods some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain.
... const char *filename() const returns filename of the source code.
... const char *introducerfilename() const returns filename of the file which introduces the file.
...And 16 more matches
nsIAccessibleText
defaulttextattributes nsipersistentproperties return the text attributes that apply to the entire accessible.
...this accessible get return 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 return value getcharacteratoffset() it would be better to return an unsigned long here, to allow unicode chars > 16 bits.
...And 16 more matches
nsILoginManagerStorage
countlogins() implement this method to return the number of logins matching the specified criteria.
...passing null should not match any logins, and should return 0.
... return 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 returns.
... return 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 returns.
...And 16 more matches
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.flipx() returns a new dommatrix created by flipping the source matrix around its x-axis.
... dommatrixreadonly.flipy() returns a new dommatrix created by flipping the source matrix around its y-axis.
... dommatrixreadonly.inverse() returns a new dommatrix created by inverting the source matrix.
...And 16 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
it returns 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 return value is expected.
... return value the returned 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; returned on overflow number.positive_infinity special positive infinite value; returned 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 returns a floating point number.
... number.parseint() parses a string argument and returns 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 returned 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 return values.
... it is the accumulated value previously returned 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 return 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 returns an // array of all of our updated saves.
... only explicitly saved // items are returned 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/return 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() returns 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 returns its resolution value as soon as the promise is resolved.
... if you specify a generator function or the iterator returned by a generator function, then task.spawn() is implicitly called, and the yield operator works on the returned promise.
...And 15 more matches
XPCOMUtils.jsm
if not // provided, the default factory is used, which returns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
... // will be automatically returned 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 returns 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) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 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) return 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) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); ...
...} js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return 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() returns the value of this object as a number.
... the exact return type is implementation dependent.
...[propget] hresult currentvalue( [out] variant currentvalue ); parameters currentvalue returns the current value represented by this object.
...And 15 more matches
nsILocalFile
getrelativedescriptor() returns a relative file path in an opaque, cross platform format.
... return value an opaque string value with undefined character encoding.
... the result returned 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 returns 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 return 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 returns an idbopendbrequest object with a result (success) or error value that you handle as an event.
... most other asynchronous functions in indexeddb do the same thing - return an idbrequest object with the result or error.
...the method returns 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 returned 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 return).
... vk_return (0x0d) kvk_return (0x24) kvk_ansi_keypadenter (0x4c) kvk_powerbook_keypadenter (0x34) gdk_key_return (0xff0d) gdk_key_kp_enter (0xff8d) gdk_key_iso_enter (0xfe34) gdk_key_3270_enter (0xfd1e) qt::key_return (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 returns 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 returns 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 return "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 returned 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 returns 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 returned 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 returns 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 returns 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; } return tempxr; } const xr = getxr("no"); // get the native xrsystem object const xr = getxr("yes"); // always returns an xrsystem from the polyfill const xr = getxr("if-needed"); // use the polyfill only if navigator.xr missing the returned 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 returned 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 return interim results, or just final results.
... speechrecognition.maxalternatives: sets the number of alternative potential matches that should be returned per result.
...And 15 more matches
Date.prototype.getYear() - JavaScript
the getyear() method returns the year in the specified date according to local time.
... because getyear() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getfullyear() method.
... syntax dateobj.getyear() return 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) returns true if the given array contains the element or false otherwise.
... returns boolean : a boolean indicating whether or not the element was found in the array.
... hasany(array, elements) returns 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 return type of the c++ function will be wrapped by xpconnect so that javascript can use it safely.
...the return value of getdocument() is a nsidomdocument.
... static nsiclassinfo* getclassinfoinstance(nsdomclassinfoid aid): this helper method returns 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 returned, and an exception will be thrown.
...in the case of any error, zero is returned, and an exception will be thrown.
... flag_sync_decode: forces synchronous/non-progressive decode of all available data before the call returns.
...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-returned content type is not a known jar type).
... isexecutingonloadhandler boolean returns true if the docshell is currently executing the onload handler.
...when setting this attribute, a ns_error_not_implemented error may be returned by implementations not supporting zoom.
...And 14 more matches
nsIEditorSpellCheck
return value returns true if spell checking can be enabled.
... if there are no available dictionaries, the return value is false.
...in spite of the name, this function checks the word you give it, returning true if the word is misspelled.
...And 14 more matches
nsIMsgDBView
return values count upon return, the count variable may contain the number of messages in the folder.
... note: this return value does not appear to be implemented in the base implementation.
... return values acount upon return, 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 return value is to be cached.
... interlineposition boolean type short returns the type of the selection (see nsiselectioncontroller for available constants).
... native code only!getcachedframeoffset returns cached value for nstextframe::getpointfromoffset.
...And 14 more matches
UInt64
syntax creates and returns a new 64-bit unsigned integer.
... return value a new object representing the specified value.
... return value the returned value is -1 if a < b, 0 if a == b, and 1 if a > b.
...And 14 more matches
Range - Web APIs
WebAPIRange
range.collapsed read only returns a boolean indicating whether the range's start and end points are at the same position.
... range.commonancestorcontainer read only returns the deepest node that contains the startcontainer and endcontainer nodes.
... range.endcontainer read only returns the node within which the range ends.
...And 14 more matches
TreeWalker - Web APIs
treewalker.root read only returns a node representing the root node as specified when the treewalker was created.
... treewalker.whattoshow read only returns an unsigned long being a bitmask made of constants describing the types of node that must be presented.
... treewalker.filter read only returns a nodefilter used to select the relevant nodes.
...And 14 more matches
Inputs and input sources - Web APIs
the returned 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; return 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 */ return 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; } } }; return 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 returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
... workernavigator.permissions read only returns a permissions object that can be used to query and update permission status of apis covered by the permissions api.
... navigator.storageread only returns 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() {return '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() {return '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 return a descendant of unknown, although it may return 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 returns 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 returns true.
... this code is pretty human-readable — it is saying "if the condition returns 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 returns 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) returns true if there are at least required arguments passed in.
... methods inherited from js::callargsbase method description unsigned length() const returns the number of arguments..
... js::mutablehandlevalue operator[](unsigned i) const returns 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, returns a comma-separated list of just the 'mailbox' portions.
... return 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, returns 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); return 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 returns if there is a reference portion (the part after the "#") of the uri.
...about:blank) prepath autf8string the prepath returns 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 returned by queryinterface, when querying an xpcom object for its nsifoo interface.
...the pointer returned 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, // returns 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 returns 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, // returns 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
return 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(); return 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) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-kw", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* wrap the given key.
...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 returns 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 returned 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 returned.
...And 13 more matches
menulist - Archive of obsolete content
editable type: boolean returns true if the element is editable.
... autocomplete fields are editable so this property always returns true for those.
... selectedindex type: integer returns 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 return results for, as specified in an expression passed in via the fq url parameter.
... in this case, we want to return 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) { return 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() { return ( ); } this is ok so far, but our component has to return 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() { return ( <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 return something.
... if at any point in the future you try to render a component that does not return 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 returned before trying to use the values they return.
... for example, this ajax example checks to make sure the request is complete and the response has been returned before trying to use the response for anything.
... in the search packages text field, type "jslint" and press enter/return 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 return null.
...we provide support for this technique via isimpledomnode::get_nodeinfo(), which returns a uniqueid for any iaccessible that can be cached in the internal model.
...the results are always returned 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 returns 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: [], /** * @return {string} the original search string */ get searchstring() { return this._searchstring; }, /** * @return {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() { return this._searchresult...
...And 12 more matches
JNI.jsm
return value blah blah loadclass() blah blah cdata loadclass( ajenv, afullyqualifiedname, [optional] object adeclares ); parameters ajenv the return value of getforthread().
... return value blah blah newstring() blah blah cdata newstring( ajenv, astr ); parameters ajenv the return value of getforthread().
... return value blah blah readstring() blah blah string readstring( ajenv, ajavastring ); parameters ajenv the return value of getforthread().
...And 12 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
// return 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 ...
... // return it to the caller return array; } access to elements since nsiarray is a regular xpcom object, its interfaces follows the standard conventions of ownership.
...the method enumerate() returns a nsisimpleenumerator which accesses all the elements in the array.
...And 12 more matches
Using XPCOM Utilities to Make Things Easier
// returns 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 returns 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 returns 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() returns 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 return the substring of the containing string where the substring is overridden with link behavior, and for an image link this method could return an iunknown variant for iaccessibleimage.
... return 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 returns true if networking is in "offline" mode.
... return value true if the port is allowed, false otherwise.
... return value a string corresponding to the scheme.
...And 12 more matches
nsIMsgDBHdr
inherits from: nsisupports this interface is usually given to you in return to a query from the message database.
... there are utility functions that also return it though.
... for instance, msghdrforcurrentmessage() will return 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 cleartemporaryreturnreceiptsfilter(); void closecachedconnections(); void configuretemporaryfilters(in nsimsgfilterlist filterlist); void configuretemporaryreturnreceiptsfilter(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, return false.
... otherwise, return 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)) { return; } if begininputtransaction() or begininputtransactionfortests() returns 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()) { return; // 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 returns false.
...And 12 more matches
nsIZipReader
findentries() returns a string enumerator containing the matching entry names.
... pat~pat2 returns matches to the pattern 'pat' which do not also match the pattern 'pat2'.
... return value the nsiutf8stringenumerator containing the matching entry names.
...And 12 more matches
Streams - Plugins
once the plug-in returns from this method, the browser deletes the npstream object.
... the value returned 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 return a large number.
...And 12 more matches
Attr - Web APIs
WebAPIAttr
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 return attr types.
... as that doesn't hold true in cases like attr objects being returned by document.evaluate, the dom living standard reintroduced the property.
... specified read only this property always returns true.
...And 12 more matches
Cache - Web APIs
WebAPICache
methods cache.match(request, options) returns a promise that resolves to the response associated with the first matching request in the cache object.
... cache.matchall(request, options) returns a promise that resolves to an array of all matching requests in the cache object.
... cache.delete(request, options) finds the cache entry whose key is the request, returning a promise that resolves to true if a matching cache entry is found and deleted.
...And 12 more matches
DOMMatrix - Web APIs
WebAPIDOMMatrix
constructor dommatrix() creates and returns a new dommatrix object.
...if the matrix can't be inverted, its components are all set to nan, and is2d returns false.
...returns 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 returns or line feeds).
... * * @param nod a node implementing the |characterdata| interface (i.e., * a |text|, |comment|, or |cdatasection| node * @return 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 return !(/[^\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 return 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 return null.
...And 12 more matches
Window.open() - Web APIs
WebAPIWindowopen
return 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 returned value is instead null.
... the returned reference can be used to access properties and methods of the new window as long as it complies with same-origin policy security requirements.
...And 12 more matches
Arrow function expressions - JavaScript
syntax basic syntax (param1, param2, …, paramn) => { statements } (param1, param2, …, paramn) => expression // equivalent to: => { return 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 return 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 returns the array: [8, 6, 7, 9] elements.map(function(element) { return element.length; }); // the regular function above can be written as the arrow function below elements.map((element) => { return element.length; }); // [8, 6, 7, 9] // when there is only one parameter, we can remove the surrounding parentheses elements.map(element => { return element.length; }); // [8, 6, 7, 9] // when the only statement in an arrow function is `return`, we can remove `return` 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 returns 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.) return 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 returned.
...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.returnok || rv == nsifilepicker.returnreplace) { var file = fp.file; // get the path as string.
... var path = fp.file.path; // work with returned nsilocalfile...
... } return 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 return a stream.
...the readstring method returns the string read from the stream.
...this doesn't trigger an error, and the string will just be returned 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 returned 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="return 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 returned 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" returned 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 return a number version of the same value.
... 10 / 5 % remainder (sometimes called modulo) returns 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 return value of a call into an asynchronous api.
...for example, the os.file.exists function returns 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 return 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 returns 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 return promises.
...let worker = new promiseworker.abstractworker() worker.dispatch = function(method, args = []) { // dispatch a call to method `method` with args `args` return 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 returning an error indication.
...likewise, the external references to errors are made in the prototypes files, with the functions which can return 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) ) return (rv *)null; if( !nssbar_verifypointer(arg2) ) return (rv *)null; #endif /* debug */ return 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"); return; } 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) { return -1; } if (c <= '9' && c >= '0') { return c - '0'; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } return -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) { return -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; return -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
returns the function returns one of these values: if successful, a pointer to a certificate structure.
...this function will return the newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate.
... when you are finished with the certificate structure returned by pk11_findcertfromnickname, you must free it by calling cert_destroycertificate.
...And 11 more matches
sslcrt.html
returns the function returns one of these values: if successful, secsuccess.
... returns the function returns 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.
... returns the function returns 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) return true; } return false; } note that `end` points to the character after the end of the string buffer.
...(don't access the return value if the nsresult indicates failure.
... unfortunately mozilla::result is not versatile enough to be used here.) bulkwrite() returns 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returned.
... 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() returns 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 returned in addition to the public suffix.
...And 11 more matches
nsIFaviconService
this method retrieves the given favicon data, returning 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, returns null.
... return value a data url containing the data for the favicon.
...And 11 more matches
nsIMessenger
boolean canundo(); return value boolean representing whether undo is available.
... boolean canredo(); return value boolean representing whether redo is available.
... unsigned long getundotransactiontype(); return value a long representing the type of the transaction.
...And 11 more matches
nsIScriptableIO
return value returns an nsifile object referencing the specified file location.
... getfilewithpath() returns a file reference using an absolute file path to locate the file.
... return value returns 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 return a boolean to pr_true before making the call.
... implementations may skip writing to *_retval unless they want to return pr_false.
...no implementor of this interface should ever return flags with this bit set.
...And 11 more matches
nsIMsgCloudFileProvider
if this value is not known, returns -1.
...if this value is not known, returns -1.
...if this value is not known, returns -1.
...And 11 more matches
Int64
syntax creates and returns a new 64-bit signed integer.
... return value a new object representing the specified value.
... return value the returned value is: -1 if a < b, 0 if a == b, and 1 if a > b.
...And 11 more matches
Element.classList - Web APIs
WebAPIElementclassList
the element.classlist is a read-only property that returns a live domtokenlist collection of the class attributes of the element.
... syntax const elementclasses = elementnodereference.classlist; returns a domtokenlist representing the contents of the element's class attribute.
... if the class attribute is not set or empty, it returns an empty domtokenlist, i.e.
...And 11 more matches
IDBObjectStore - Web APIs
methods idbobjectstore.add() returns 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 returns an idbrequest object, and clears this object store in a separate thread.
... idbobjectstore.count() returns an idbrequest object, and, in a separate thread, returns the total number of records that match the provided key or idbkeyrange.
...And 11 more matches
USBDevice - Web APIs
WebAPIUSBDevice
methods usbdevice.claiminterface() returns a promise that resolves when the requested interface is claimed for exclusive access.
... usbdevice.clearhalt() returns a promise that resolves when a halt condition is cleared.
... usbdevice.controltransferin() returns 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() returns the indexed value for the given target.
... renderbuffers webgl2renderingcontext.getinternalformatparameter() returns information about implementation-dependent support for internal formats.
... programs and shaders webgl2renderingcontext.getfragdatalocation() returns the binding of color numbers to user-defined varying out variables.
...And 11 more matches
HTTP Index - HTTP
WebHTTPIndex
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 returned data.
...when this policy is enabled, the promise returned 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); } return 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 returned from the outer function before being executed.
... here's a slightly more interesting example—a makeadder function: function makeadder(x) { return function(y) { return 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 returns a new function.
...And 11 more matches
Details of the object model - JavaScript
the internal [[prototype]] property determines the prototype chain used to return property values.
... once these properties are set, javascript returns the new object and the assignment statement sets the variable mark to that object.
...if it does, that value is returned.
...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 return value upon its termination.
... specifically, an iterator is any object which implements the iterator protocol by having a next() method that returns an object with two properties: value the next value in the iteration sequence.
...if value is present alongside done, it is the iterator's return value.
...And 11 more matches
Functions - JavaScript
values can be passed to a function, and the function will return a value.
... to return a value other than the default, a function must have a return statement that specifies the value to return.
... a function without a return statement will return a default value.
...And 11 more matches
Array.prototype.findIndex() - JavaScript
the findindex() method returns the index of the first element in the array that satisfies the provided testing function.
... otherwise, it returns -1, indicating that no element passed the test.
... see also the find() method, which returns 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]]) { // return element for new_array }[, thisarg]) parameters callback function that is called for every element of arr.
... each time callback executes, the returned value is added to new_array.
... return 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 returns the sorted array.
... return value the sorted array.
... if comparefunction is supplied, all non-undefined array elements are sorted according to the return 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 returns 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 returned by the specified function.
... return 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 returns 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 returned from symbol() is unique.
... finding symbol properties on objects the method object.getownpropertysymbols() returns 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 returned as a string.
... returns string : the converted native file path as a string.
... returns string : the converted url as a string.
...And 10 more matches
Using microformats - Archive of obsolete content
return value an integer value indicating the number of microformats that match the specified criteria.
... debug() returns a string that describes a microformat object.
... return value a string that describes the contents of the specified microformat object.
...And 10 more matches
Parsing microformats in JavaScript - Archive of obsolete content
return value a string containing the normalized date.
... return value a string containing the property's value.
... return value a string containing the email address.
...And 10 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
51 crlf cr, crlf, glossary, infrastructure, lf, carriage return, 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 return 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, returning 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 returned 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 returning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset.
...when you fetch an image from a server, you can't return the result immediately.
...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); return nullptr; } refptr<promise> echopromise = promise::create(mwindow->asglobal(), arv); if (ns_warn_if(arv.failed())) { return nullptr; } // message passing magic will happen here!
... return 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 return 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 return type here declaring a class/object is done in a special way.
...the arguments are within the parenthesis, and the return 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 return, 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"); return; } 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) { return -1; } if (c <= '9' && c >= '0') { return c - '0'; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } return -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) { return -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; return -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 returns.
... error codes are never returned from methods/functions.
...most people will probablby just print the string representation of the returned certverifylog object.
...And 10 more matches
Introduction to the JavaScript shell
build() returns the date and time at which the javascript shell was built.
... if string is empty and object is not specified, evalcx() returns a new object with eager standard classes.
... if string is "lazy" and object is not specified, evalcx() returns 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) - returns an item's title int64 getitemindex(aitemid) - returns an item's position in it's parent folder prtime getitemtype(aitemid) - returns the type of an item (bookmark, folder, separator) prtime getitemdateadded(aitemid) - returns the time in microseconds that an item was added prtime getitemlastmodified(aitemid) - returns the time in microseconds that an item was last modified int64 getfol...
...deridforitem(aitemid) - returns the id of the folder containing the given item.
... string getitemguid(aitemid) obsolete since gecko 14.0 - returns 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 returned 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 returned 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 return it.
...And 10 more matches
Introduction to XPCOM for the DOM
the memory is never returned 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 "return" a pointer to the required interface.
... please note that all getter functions have to addref the returned 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() returns the specified link.
... the returned 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 return.
...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 returned.
... mozistoragestatement clone(); return value a mozistoragestatement that is a copy of the current statement.
... return 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 returns "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 returns the first child element of the html element that is a head element, or null if there is no html or head element.
... return value true if the command was recognized, false otherwise.
...And 10 more matches
nsIHttpChannel
setter is case insensitive; getter returns an uppercase string.
... requestsucceeded boolean returns true if the http response code indicates success.
... note: this returns 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 returns 0 bytes available.
... return 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 return 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 returns the display name of the application bundle (usually the human readable name of the application) read only.
... bundleidentifier autf8string returns the identifier of the bundle.
... filesizewithresfork print64 returns the combined size of both the data fork and the resource fork (if present) rather than just the size of the data fork as returned by getfilesize() read only.
...And 10 more matches
Component; nsIPrefBranch
return value the value of the requested boolean preference.
... return value returns string - the value of the requested string preference.
... return value returns 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.
... return 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 returned 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() { return { 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 returned a simple object stating alpha transparency is allowed.
... the code to do this looks like so: registerpaint('headerhighlight', class { static get contextoptions() { return { 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
WebAPISelection
properties selection.anchornoderead only returns the node in which the selection begins.
... can return null if selection never existed in the document (e.g., an iframe that was never clicked on).
... selection.anchoroffsetread only returns 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 returns information about the renderbuffer.
...possible values: gl.renderbuffer_width: returns a glint indicating the width of the image of the currently bound renderbuffer.
... gl.renderbuffer_height: returns 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; }); return 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); } return 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) return; 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; return; } 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) { return name in target?
...here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42.
... handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof getprototypeof method must return 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; // returns '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); // returns the number 4 eval(secondstring); // returns 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 returns "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 returned promises before explaining how to create them.
... essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.
... 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 return a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to return 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
returns the old value at that index.
...returns the old value at that index.
...returns 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 returned.
... reviver optional if a function, this prescribes how the value originally produced by parsing is transformed, before being returned.
... return 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 returns an array of [key, value] for each iteration.
...thus, when iterating over it, a map object returns keys in order of insertion.
... instance properties map.prototype.size returns 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 returns a single promise that resolves to an array of the results of the input promises.
... this returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises.
... return 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, returns 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 returned promise is rejected with an aggregateerror, a new subclass of error that groups together individual errors.
... return 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) { return "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") { return "world"; } return 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 returned as the default value when the property name is not in the object.
...And 10 more matches
delete operator - JavaScript
return value true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode.
...on successful deletion, it will return true, else false will be returned.
... 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 return true.
...And 10 more matches
core/heritage - Archive of obsolete content
if (!(this instanceof dog)) return 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() { return 'ruff!
... ruff!' }; // subclassing a `dog` function pet(name, breed) { // once again we do our little dance if (!(this instanceof pet)) return 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) return 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) return; 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)) return addon; return { __proto__: addon, getdatadirectory: function getdatadirectory() { return new promise((accept, reject) => { return 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 ) return type: no return value add a progress listener to the browser which will monitor loaded documents.
... goback() return type: no return value go back one page in the history.
... goforward() return type: no return value go forward one page in the history.
...And 9 more matches
prefwindow - Archive of obsolete content
returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527).
...if the handler returns true, the dialog will indeed go away, but if it returns false it will not.
...if the routine returns true, the dialog will indeed go away, but if it returns false it will not.
...And 9 more matches
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
selectedindex type: integer returns the index of the currently selected item.
...returns -1 if no items are selected selecteditem type: element holds the currently selected item.
... tabbox type: tabbox element returns 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 returns 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 return 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 returned.
...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() { return ( <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() { return ( <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 return information about objects we want to expose.
...if there is no msaa node for a dom node, paccessible->queryinterface(iid_iaccessible) will return 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 return 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) { return 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...
... return promise.resolve(true); // loop end.
...And 9 more matches
JSAutoByteString
char *encodelatin1(jscontext *cx, jsstring *str) call js_encodestring and take ownership of the returned string, and return the string.
... char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take ownership of the returned string, and return the string.
... char *ptr() const return 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)) return rv; nscomptr<nsicategorymanager> catman; servman->getservicebycontractid(ns_categorymanager_contractid, ns_get_iid(nsicategorymanager), getter_addrefs(catman)); if (ns_failed(rv)) return 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); return 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 returning 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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 returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string.
...@return 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...
...@return 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() returns a localized version of the relation type.
... [propget] hresult localizedrelationtype( [out] bstr localizedrelationtype ); parameters localizedrelationtype return value s_ok.
... ntargets() returns the number of targets() for this relation.
...And 9 more matches
mozIStorageConnection
transactioninprogress boolean returns true if there is a transaction in progress on the database.
... otherwise returns false.
... mozistorageconnection clone( in boolean areadonly optional ); parameters areadonly if true, the returned database connection is in read only mode.
...And 9 more matches
nsIAccessible
groupposition this method returns grouping information.
... getchildatpoint this method returns an accessible child which contains the coordinate at (x, y) in screen pixels.
... getchildat this method returns nth accessible child using zero-based index or last child if index than less than zero.
...And 9 more matches
nsIAccessibleHyperLink
the returned 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 returning from the destination page.
...the returned 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() returns whether we can copy an image's contents.
...return value true if an image is selected, false otherwise.
... cancopyimagelocation() returns 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 return value missing description countlogins() returns the number of logins matching the specified criteria.
... return value the number of logins matching the parameters passed.
... return value true if the form was successfully filled out; otherwise false.
...And 9 more matches
nsIMicrosummaryService
return value returns an nsimicrosummary for the given page and generator uris.
...return value returns an nsisimpleenumerator enumeration of bookmark ids.
... getgenerator() return a microsummary generator for the given uri.
...And 9 more matches
nsINavHistoryService
return value returns the original title of the page.
... return value returns true if this uri would be added to the history, otherwise returns false.
... return value returns the id of the created visit.
...And 9 more matches
nsITransactionList
methods getchildlistforitem() returns the list of children associated with the item at aindex.
... implementations may return null if there are no children, or an empty list.
... the list returned 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 returned after beginning a batch.
...adoresult the nsresult returned after executing the transaction.
...aresult the nsresult returned 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() returns the list of nsitransaction on the redo stack.
...And 9 more matches
nsIXULTemplateQueryProcessor
this method should return -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.
... return value -1 if aleft < aright 0 if aleft == aright 1 if aleft > aright compilequery() compile a query from a node.
...if null is returned, the query will be ignored.
...And 9 more matches
nsIAbCard/Thunderbird3
methods getproperty() returns a property for the given name.
... defaultvalue the value to return if the property does not exist.
... return value the value of the attribute asked for.
...And 9 more matches
XPIDL
methods define a return type and a series of in and out parameters.
...however, scriptable methods must contain parameters and a return 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 return type is prevented, so it is called mostly as it looks.
...And 9 more matches
Address Book examples
this function will return the first match that it finds in the collection or null.
...again, this function returns 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 returns 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 returned 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 returning, throwing an exception or being terminated, pop the "debugger" frame, and return an appropriate completion value from the invocation function to the debugger.
...each property is a read-only accessor property whose getter returns the current value of the corresponding parameter.
...And 9 more matches
Debugger.Script - Firefox Developer Tools
getalloffsets() if the instance refers to a jsscript, return 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, return an array describing the relationship between bytecode instruction offsets and source code positions in this script.
... unlike getalloffsets(), which returns all offsets that are entry points for each line, getallcolumnoffsets() returns 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 return that input instead of the form's action html attribute).
... checkvalidity() returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints.
... reportvalidity() returns true if the element's child controls satisfy their validation constraints.
...And 9 more matches
KeyboardEvent.getModifierState() - Web APIs
the keyboardevent.getmodifierstate() method returns 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); returns a boolean parameters keyarg a modifier key value.
... modifier keys on gecko when getmodifierstate() returns true on gecko?
...And 9 more matches
MediaDevices.getUserMedia() - Web APIs
it returns a promise that resolves to a mediastream object.
... note: it's possible for the returned promise to neither resolve nor reject, as the user is not required to make a choice at all and may simply ignore the request.
...if the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with notfounderror.
...And 9 more matches
MediaStreamTrack - Web APIs
mediastreamtrack.id read only returns a domstring containing a unique identifier (guid) for the track; it is generated by the browser.
... mediastreamtrack.isolated read only returns 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 returns 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 return high-resolution timestamps.
...the first property in the processing model is starttime which returns the timestamp immediately before the resource loading process begins.
... when cors is in effect, many of these values are returned as zero unless the server's access policy permits these values to be shared.
...And 9 more matches
SVGTextContentElement - Web APIs
svgtextcontentelement.getnumberofchars() returns 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() returns a float representing the computed length for the text within the element.
... svgtextcontentelement.getsubstringlength() returns 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, returning a cryptokey object that can be used in the web crypto api.
... unwrapkey: the key may be used to unwrap a key return 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); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey method.
...And 9 more matches
SubtleCrypto - Web APIs
subtlecrypto.encrypt() returns a promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters.
... subtlecrypto.decrypt() returns a promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters.
... subtlecrypto.sign() returns 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 returns a dictionary object indicating the progress of the encoding.
... return 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) { return encoder.encodeinto(string, position ?
...And 9 more matches
TextRange - Web APIs
WebAPITextRange
properties textrange.boundingheightread only returns the height of the rectangle bound to the textrange object.
... textrange.boundingleftread only returns 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 returns 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
WebAPITouch
basic properties touch.identifier read only returns a unique identifier for this touch object.
... touch.screenx read only returns the x coordinate of the touch point relative to the left edge of the screen.
... touch.screeny read only returns 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 returns information about a vertex attribute at a given position.
...possible values: gl.vertex_attrib_array_buffer_binding: returns the currently bound webglbuffer.
... gl.vertex_attrib_array_enabled: returns 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"; } return 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"; } return 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"; } return 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 returns a boolean value.
... return value true if the callback function returns 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 returns a falsy value.
...And 9 more matches
Array.prototype.find() - JavaScript
the find() method returns the value of the first element in the provided array that satisfies the provided testing function.
... return value the value of the first element in the array that satisfies the provided testing function.
... otherwise, undefined is returned.
...And 9 more matches
Array.prototype.indexOf() - JavaScript
the indexof() method returns 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 returned, which means the array will not be searched.
... return value the first index of the element in the array; -1 if not found.
...And 9 more matches
JSON.stringify() - JavaScript
return value a json string representing the given value.
...json.stringify() can return undefined when passing in "pure" values like json.stringify(function(){}) or json.stringify(undefined).
... the instances of date implement the tojson() function by returning 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 returns the object.
... return value the object that was passed to the function.
...the return value will be used as the value of the property.
...And 9 more matches
Set - JavaScript
instance properties set.prototype.size returns the number of values in the set object.
...returns the set object.
... set.prototype.delete(value) removes the element associated to the value and returns the value that set.prototype.has(value) would have previously returned.
...And 9 more matches
String.prototype.charCodeAt() - JavaScript
the charcodeat() method returns 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 returned will be the first part of a surrogate pair for the code point.
... return 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 return from the generator function via the iterator protocol.
... if omitted, undefined is returned instead.
... description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned 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 returns a true value.
...if you register a listener function for this event and it returns 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) {' + ' return !!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 returns the index of the currently selected item.
...returns -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 ) return 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 returned by the min property, whichever is higher.
...otherwise it returns the value of the associated label element, if applicable.
... otherwise it returns the placeholder or emptytext property.
...And 8 more matches
JavaScript basics - Learn web development
it returns a true/false (boolean) result.
... === let myvariable = 3; myvariable === 4; not, does-not-equal this returns 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 return the number 7, because "mozilla" is 7 characters long.
... retrieving a specific string character on a related note, you can return 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 return, 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 returns 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 returns 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 returned (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 returned to it much later on, the configuration would still work.
...just press return to accept the default parcel-experiment.
... version: the starting version number for the app: again, just press return 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 returns 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 return 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 return before continuing with the request.
...this tells the browser to wait for your event listener to return before continuing with the request.
... next, return 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 returns control to you).
...your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or return false when something asynchronous is going on.
...returning 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); return 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); return 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); return 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); return 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: return 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 return 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 returned 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) return -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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 returns the length, beginning, and end of a string in one operation.
...@return the new length of the string, or 0 if resizing failed.
... @return 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 return value a domstring containing the attribute value.
...nsidomattr getattributenode( in domstring name ); parameters name attribute name return value a nsidomattr corresponding to the attribute.
...nsidomattr getattributenodens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname attribute name return value a nsidomattr corresponding to the attribute.
...And 8 more matches
nsIOutputStream
this exception may only be thrown if isnonblocking() returns true.
...this exception may only be thrown if isnonblocking() returns true.
... return value true if stream is non-blocking.
...And 8 more matches
nsIPlacesView
methods getdragableselection() returns an array of selected nsinavhistoryresultnode objects that can be dragged from the view.
... return value an array of nsinavhistoryresultnode objects.
... getremovableselectionranges() returns 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 return null.
... hashvalue unsigned long returns 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 return 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() returns a list of flavors (mime types as nsisupportscstring) that the transferable can export, either through intrinsic knowledge or output data converters.
... return 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.
... return value missing description getanytransferdata() returns 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 returned.
...if there isn't one, an empty string is returned.
...if there isn't one, an empty string is returned.
...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 return 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 returned.
... 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 returned.
...And 8 more matches
CacheStorage - Web APIs
equivalent functionality to match a cache entry can be implemented by returning 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 returns a promise that resolves to that match.
... cachestorage.has() returns 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 returns the element within the shadow tree that has focus.
... documentorshadowroot.fullscreenelementread only returns the element that's currently in full screen mode for this document.
... documentorshadowroot.pointerlockelement read only returns the element set as the target for mouse events while the pointer is locked.
...And 8 more matches
File - Web APIs
WebAPIFile
file objects are generally retrieved from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement.
...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() returns a newly constructed file.
... instance properties file.prototype.lastmodified read only returns 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
WebAPISVGMatrix
this matrix is post-multiplied by another matrix, returning the resulting new matrix as svgmatrix.
... svgmatrix.inverse() returns the inverse matrix as svgmatrix.
... svgmatrix.translate() post-multiplies a translation transformation on the current matrix and returns the resulting matrix as svgmatrix.
...And 8 more matches
ServiceWorkerRegistration - Web APIs
serviceworkerregistration.scope read only returns a unique identifier for a service worker registration.
... serviceworkerregistration.installing read only returns a service worker whose state is installing.
... serviceworkerregistration.waiting read only returns a service worker whose state is installed.
...And 8 more matches
Using readable streams - Web APIs
return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue...
...(value); return pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.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 returns a promise containing a results object — this has the results of our read in it, in the form { done, value }: return 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
WebAPIVTTCue
constructor vttcue(starttime, endtime, text) returns a newly created vttcue object that covers the given time range and has the given text.
... vttcue.vertical returns an enum representing the cue writing direction.
... vttcue.snaptolines returns 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 returns parameter information of a webglsampler object.
... pname a glenum specifying which information to return.
... possible values: gl.texture_compare_func: returns a glenum indicating the texture comparison function.
...And 8 more matches
WebGLRenderingContext.getProgramParameter() - Web APIs
the webglrenderingcontext.getprogramparameter() method of the webgl api returns information about the given program.
...possible values: gl.delete_status: returns a glboolean indicating whether or not the program is flagged for deletion.
... gl.link_status: returns a glboolean indicating whether or not the last link operation was successful.
...And 8 more matches
Window.getComputedStyle() - Web APIs
the window.getcomputedstyle() method returns 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 returned 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 returned object is the same cssstyledeclaration type as the object returned from the element's style property.
...And 8 more matches
WorkerGlobalScope - Web APIs
the self property returns the specialized scope for each context.
... standard properties workerglobalscope.navigator read only returns the workernavigator associated with the worker.
... workerglobalscope.self read only returns a reference to the workerglobalscope itself.
...And 8 more matches
WritableStream.WritableStream() - Web APIs
if this process is to be done asynchronously, it can return a promise to signal success or failure.
...it can return a promise to signal success or failure of the write operation.
...if this process is asynchronous, it can return a promise to signal success or failure.
...And 8 more matches
XMLHttpRequest - Web APIs
xmlhttprequest.readystate read only returns an unsigned short, the state of the request.
... xmlhttprequest.response read only returns 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 returns 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 return 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 returns basic, core information about the locale in the form of a substring of the complete data string.
... intl.locale.prototype.calendar returns the part of the locale that indicates the locale's calendar era.
... intl.locale.prototype.casefirst returns 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 returns 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 returned.
... return value a string representing the character (exactly one utf-16 code unit) at the specified index.
...And 8 more matches
String.prototype.match() - JavaScript
return 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 returned, but capturing groups will not.
... if the g flag is not used, only the first complete match and its related capturing groups are returned.
...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 returns the array.
... if separator is omitted or does not occur in str, the returned array contains one element consisting of the entire string.
...zero length) string, which appears at the first (or last) position of the returned array.
...And 8 more matches
parseInt() - JavaScript
the parseint() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
... return value an integer parsed from the given string.
... description the parseint function converts its first argument to a string, parses that string, then returns an integer or nan.
...And 8 more matches
Strict mode - JavaScript
function strict() { // function-level strict mode syntax 'use strict'; function nested() { return 'and so am i!'; } return "hi!
... " + nested(); } function notstrict() { return "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() { return 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 returns 0.
...if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0.
...if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0.
...And 8 more matches
XPCOM Objects - Archive of obsolete content
in some methods the out keyword is used for parameters that are return values in reality.
... this is done for certain value types that are not valid as return 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 returns 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 return true if the controller supports a command.
... if you return false, the command is not handled and command dispatcher will look for another controller.
... iscommandenabled (command) this method should return true if the command is enabled, or false if it is disabled.
...And 7 more matches
menu - Archive of obsolete content
ArchiveMozillaXULmenu
control type: menu element returns 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 returns 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 ) return 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: returns the current display npnvxtappcontext: unix only: returns the application's xtappcontext npnvnetscapewindow: ms windows and unix/x11 only: ms windows: gets the native window on which plug-in drawing occurs; returns hwnd unix/x11: gets the browser toplevel window in which the plug-in is displayed; returns 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: returns 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 returns 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="return this.ownerdocument.getanonymouselementbyattribute(this, 'anonid', 'ref1');"/> <property name="ref2" readonly="true" onget="return 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 return the current value of the control as seen by a user.
...currently interface is: interface nsixformsaccessors : nsisupports { /** * return value of instance node.
...And 7 more matches
Arrays - Learn web development
we'll return to this example later on in the article.
... enter the following into your console: shopping[0]; // returns "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 return [ "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, return once more to our todo-data.js file.
... it already contains a getter that returns all todos, and a getter that returns incomplete todos.
... the getter we are missing is one to return 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 return 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) { // return {...task, name: newname} } return 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 return 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 return 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 return results.
... once the install completes, test that node is installed by typing the following into the terminal, which returns 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 returns 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 returns 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 returns 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 returned 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 returned in the ck_info structure with an internationalize string (utf8).
... cryptotokendescription override the default label value for the internal crypto token returned in the ck_token_info structure with an internationalize string (utf8).
...And 7 more matches
JIT Optimization Strategies
in particular, arguments cannot be returned from the function, or passed as an argument into calls (except for the apply case above).
...in particular, arguments cannot be returned 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) return true; } return 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 returns the length of the array.
... t popcopy() pops an element from the array and returns it.
... js::mutablehandle<t> operator[](size_t i) returns to the i-th element as js::mutablehandle&lt;t&gt;.
...And 7 more matches
JSFastNative
vp jsval * the arguments, including the this argument, the return-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) returns the function object that was called, as a jsval.
...(the return value and the callee are stored in the same stack slot.) js_this(cx, vp) returns 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() returns the background color of this object.
... [propget] hresult background( [out] ia2color background ); parameters background the returned color is the background color of this object or, if that is not supported, the default background color.
... return value s_ok.
...And 7 more matches
mozIStorageValueArray
methods gettypeofindex() returns the type of the value at the given column index.
... return 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.
... return 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, return false.
... otherwise, find the uri of the channel, determine whether it is foreign with respect to auri, and return.
...if so, return.
...And 7 more matches
nsIBinaryInputStream
return value an 8-bit integer read from the stream.
... return value a 16-bit integer read from the stream.
... return value a 32-bit integer read from the stream.
...And 7 more matches
nsIComponentRegistrar
cidtocontractid() this method returns the contractid corresponding to a given classid.
... return value the contractid corresponding to aclassid if one exists and is registered.
... contractidtocid() returns the classid for a given contractid, if one exists and is registered.
...And 7 more matches
nsIContentViewer
can return null.
...return 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 returns 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() returns the controller instance at the given position.
... return value the controller at the given position.
... getcontrollerbyid() returns 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() returns an nsiutf8stringenumerator providing the keys available within the specified section of the ini file.
... return value an nsiutf8stringenumerator object that can be used to access the section's keys.
... getsections() returns 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, returning the javascript object it represents.
... return value the original javascript object, reconstructed from the json string.
... return value the original javascript object, reconstructed from the json string.
...And 7 more matches
nsIMsgMessageService
amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the message.
... aurllistener an nsiurllistener amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the message.
... return 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 returns the node in which the selection begins.
... focusnode nsidomnode returns the node in which the selection ends.
... rangecount long returns 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 return type, and the third is an array of arguments the callback expects.
... the return type of the javascript callback must match the return type declared, otherwise js-ctypes will throw an error saying "unexpected return type".
... examples example 1 this callback that returns bool and has two arguments.
...And 7 more matches
CData
methods available on all cdata objects address() returns a cdata object of the pointer type ctypes.pointertype(dataobject.constructor) whose value points to the c object referred to by the object.
... return 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() returns 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+return on macos).
... when you find the expression you want, press enter (return) 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() { return "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 returned by calling bluetoothremotegattcharacteristic.properties.
... properties authenticatedsignedwritesread only returns a boolean that is true if signed writing to the characteristic value is permitted.
... broadcastread only returns 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 returns an empty string.
...if the descriptor was not specified in the associated rule, the attribute returns an empty string.
...if the descriptor was not specified in the associated rule, the attribute returns an empty string.
...And 7 more matches
FetchEvent.respondWith() - Web APIs
for security reasons, there are a few global rules: you can only return response objects of type "opaque" if the fetchevent.request object's mode is "no-cors".
... you can only return response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual".
... you cannot return 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 returned 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 returns 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 }); return 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; } return 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 returns, the context for localgreeting() is removed from the execution stack and destroyed.
... the greetuser() function returns 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 returns exceptions this method can raise a idbdatabaseexception with the following codes: value the value to store into the index.
... createindex() creates and returns a new index with the given name in the connected database.
... returns 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 returned after a user selects a payment method and approves a payment request.
... properties paymentresponse.details read only secure context returns 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 returns 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 returns a timestamp that is the duration of the performance entry.
... the value returned by this property depends on the performance entry's type: "frame" - returns a timestamp indicating the difference between the starttimes of two successive frames.
... "mark" - returns "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"); return; } // 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"); return; } console.log("= calculate load times"); for (var i=0; i < resources.length; i++) { console.log("== resource[" + i...
...the transfersize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body.
... the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings.
...And 7 more matches
SVGSVGElement - Web APIs
svgsvgelement.unsuspendredraw() cancels a specified suspendredraw() by providing a unique suspend handle id that was returned by a previous suspendredraw() call.
... svgsvgelement.animationspaused() returns true if this svg document fragment is in a paused state.
... svgsvgelement.getcurrenttime() returns 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 returns 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); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below.
... starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); return null; }); } either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share.
...And 7 more matches
SubtleCrypto.importKey() - Web APIs
return value result is a promise that fulfills with the imported key as a cryptokey object.
...takes an arraybuffer string containing the bytes, and returns a promise that will resolve to a cryptokey representing the secret key.
... */ function importsecretkey(rawkey) { return 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() returns the location of a specific uniform variable which is part of a given webglprogram.
... the uniform variable is returned 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() returns 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); return [resultx, resulty, resultz, resultw]; } now using the function above we can multiply a point by the matrix.
... using the identity matrix it should return 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]); returning 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 return [ 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."); return; } 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 returned 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 return 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 returns; 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 returns a promise that will resolve to a publickeycredential containing an authenticatorattestationresponse.
...And 7 more matches
Index - HTTP
WebHTTPHeadersIndex
26 content-location http, reference, header the content-location header indicates an alternate location for the returned data.
...when this policy is enabled and there were no user gestures, the promise returned by htmlmediaelement.play() will reject with a domexception.
...when this policy is enabled, the promise returned 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 returns true if the number of characters in a text object is three.
... otherwise, it displays an alert and returns false.
... function checkdata() { if (document.form1.threechar.value.length == 3) { return true; } else { alert( 'enter exactly three characters.
...And 7 more matches
Array.prototype.filter() - JavaScript
return true to keep the element, false otherwise.
... return value a new array with the elements that pass the test.
... if no elements pass the test, an empty array will be returned.
...And 7 more matches
Array.prototype.some() - JavaScript
it returns a boolean value.
... return value true if the callback function returns 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 returns a truthy value (a value that becomes true when converted to a boolean).
...And 7 more matches
Math.clz32() - JavaScript
the math.clz32() function returns the number of leading zero bits in the 32-bit binary representation of a number.
... return 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 return 32, because all bits are 0.
...And 7 more matches
Number - JavaScript
if the value can't be converted, it returns nan.
... literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true function syntax number('123') // returns the number 123 number('123') === 123 // true number("unicorn") // nan number(undefined) // nan constructor number() creates a new number value.
...returned on overflow.
...And 7 more matches
Reflect - JavaScript
returns a boolean that is true if the property was successfully defined.
... reflect.get(target, propertykey[, receiver]) returns the value of the property.
...returns 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 returns the index within the calling string object of the first occurrence of the specified value, starting the search at fromindex.
... returns -1 if the value is not found.
... so, for example: 'undefined'.indexof() will return 0, as undefined is found at position 0 in the string undefined.
...And 7 more matches
String.prototype.substring() - JavaScript
the substring() method returns 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 returned substring.
... indexend optional the index of the first character to exclude from the returned substring.
...And 7 more matches
in operator - JavaScript
the in operator returns 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 // returns true 3 in trees // returns true 6 in trees // returns false 'bay' in trees // returns false (you must specify the index number, not the value at that index) 'length' in trees // returns true (length is an array property) symbol.iterator in trees // returns true (arrays are iterable, works only in es2015+) // predefined objects 'pi' in math // returns true // custom ob...
...jects let mycar = {make: 'honda', model: 'accord', year: 1998} 'make' in mycar // returns true 'model' in mycar // returns 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 returns a generator object.
... calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
... when the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned 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 return 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++; } } return amount; }; getting the color of a pixel in a canvas this following snippet returns 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); return { 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); return { 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)); }); return frag; } // single element?
...tag.apply(null, childelem) : doc.createtextnode(childelem)); } }); return elem; } return 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="return parseint(document.getanonymousnodes(this)[0].childnodes[0].getattribute('selectedindex'));" onset="return this.setpage(val);"/> the page property gets its value by looking at the first element of the anonymous array.
... this returns the vertical box, so to get the deck, we need to get the first child node of the box.
...the first parentnode returns 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 returns the wizardpage element that is currently displayed.
... pageindex type: integer this property returns the index of the currently selected page.
... pagestep type: integer this property returns 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 returns a pointer to a newly allocated npobject.
...this function is expected to allocate and return enough storage to hold the npobject that is being created.
...returns true if the method exists, otherwise returns 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 returning 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 returns two things: the state, and a function that can be used to update the state later.
... usestate() returns 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 return 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 return a11y hints and typescript compile errors.
...the partial utility returns 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() return { 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 return promise; }, function info() { let status = ...
... // collect any information that may be useful for debugging shutdown issues with this blocker return 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 returned 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 returns a reference to nsiioservice.
... return value returns the nsiasyncstreamcopier object that is handling the copy.
... if (!components.issuccesscode(aresult)) { // handle error return; } // consume the input stream.
...And 6 more matches
NSS_3.12_release_notes.html
bug 354403: nsslist_createiterator returns 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() returns 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 returns 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; return waserror; } void otherfunction(jscontext *cx) { js::value value; bool success = maybegetvalue(cx, &value); // ...
... if (!waserror) valueout.set(resultvalue); return waserror; } void otherfunction(jscontext *cx) { js::rootedvalue value(cx); bool success = maybegetvalue(cx, &value); // ...
... } return values it's ok to return raw pointers!
...And 6 more matches
Hacking Tips
js> function f () { return 1; } js> dis(f); flags: loc op ----- -- main: 00000: one 00001: return 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) { return 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_)) │ return 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 returns its pages to the fragmento for reuse.
...all transitions out of recording mode eventually involve returning 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 returns to monitoring mode.
...And 6 more matches
Querying Places
the defaults for these objects will result in a query that returns 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 return 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 returned in the results.
... results_as_uri: this is the default, and returns one result node of type result_type_uri for each uri that matches the query.
...And 6 more matches
nsIApplicationCacheService
return value the nsiapplicationcache best able to serve the resource indicated by the key parameter.
... return value the newly-created nsiapplicationcache.
... getactivecache() returns the currently active cache object for a cache group.
...And 6 more matches
nsIBrowserSearchService
returns the first visible engine if the default engine is hidden.
...this differs from the "defaultengine" attribute in that it always returns a given build's default engine, regardless of whether it is hidden.
... getdefaultengines() returns an array of all default search engines.
...And 6 more matches
nsICommandLine
methods findflag() finds a command-line flag, returning its position on the command line.
... return 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.
... return 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 returns system event group.
... obsolete since gecko 7.0 methods geteventtargetchainfor() returns 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 returns.
...And 6 more matches
nsILocaleService
this method returns something similar to getsystemlocale.
...return value the user's os setting for preferred locale.
...this method returns 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 returned by nsinavbookmarkservice's getfolderuri method.
...the query is exeucted, the results are sorted, and then the top maxresults results are taken and returned.
... results_as_date_query 3 returns 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 return immediately.
...use resolveasync instead previous doc this method returns a nsiproxyinfo instance that identifies a proxy to be used for loading the given uri.
... otherwise, this method returns null indicating that a direct connection should be used.
...And 6 more matches
nsISHEntry
(prior to gecko 6.0 returned a json encoded string.) sticky boolean whether the content viewer is marked "sticky" windowstate nsisupports saved state of the global window object.
... return value clearchildshells() clear the child shell list.
...return value native code only!create additional ways to create an entry.
...And 6 more matches
nsISecurityCheckedComponent
the two special return 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() returns a capability string indicating what permissions are required to call the specified method on the given interface.
... return 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 returns the type of the selection (see nsiselectioncontroller for available constants).
... methods getrangesforinterval() return array of ranges intersecting with the given dom interval.
... allowadjacent specifies whether the returned 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 returning it on demand.
... return value an nsiwebbrowserchrome object for the corresponding chrome window getnewauthprompter() return a newly created nsiauthprompt implementation.
... return 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 returned from this server.
... null if the last call didn't return an xml-rpc fault.
... result readonly nsisupports the most recent xml-rpc call result returned 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(); return 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(); return 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(); return 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 returned 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) { return 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, /* return 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 returns 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 returns the bluetoothgattservice this characteristic belongs to.
... bluetoothremotegattcharacteristic.uuidread only returns a domstring containing the uuid of the characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
... bluetoothremotegattcharacteristic.propertiesread only returns the properties of this characteristic.
...And 6 more matches
DOMTokenList - Web APIs
such a set is returned by element.classlist, htmllinkelement.rellist, htmlanchorelement.rellist, htmlareaelement.rellist, htmliframeelement.sandbox, or htmloutputelement.htmlfor.
... domtokenlist.value a stringifier property that returns the value of the list as a domstring.
... methods domtokenlist.item(index) returns 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 returns the string value of the attribute with the specified namespace and name.
... if the named attribute does not exist, the value returned will either be null or "" (the empty string); see notes for details.
... return value the string value of the specified attribute.
...And 6 more matches
Element.getBoundingClientRect() - Web APIs
the element.getboundingclientrect() method returns the size of an element and its position relative to the viewport.
... syntax domrect = element.getboundingclientrect(); value the returned value is a domrect object which is the union of the rectangles returned 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 returned 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.
...returns a promise which is resolved once full-screen mode has been completely shut off.
...returns a promise which is resolved once full-screen mode has been activated.
...And 6 more matches
HTMLVideoElement - Web APIs
htmlvideoelement.videoheight read only returns 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 returns 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 returns an unsigned long with the count of video frames that have been parsed from the media resource.
...And 6 more matches
IDBIndex - Web APIs
WebAPIIDBIndex
properties idbindex.isautolocale read only returns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) idbindex.locale read only returns 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() returns an idbrequest object, and in a separate thread, returns the number of records within a key range.
... idbindex.get() returns 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 returns a new mediastream object.
... mediastream.active read only a boolean value that returns true if the mediastream is active, or false otherwise.
... mediastream.clone() returns a clone of the mediastream object.
...And 6 more matches
MutationRecord - Web APIs
properties property type description mutationrecord.type string returns "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 returns the node the mutation affected, depending on the mutationrecord.type.
... mutationrecord.addednodes nodelist return the nodes added.
...And 6 more matches
NavigatorID - Web APIs
navigatorid.appcodename read only always returns "mozilla", in any browser.
... navigatorid.appname read only always returns "netscape", in any browser.
... navigatorid.appversion read only returns either "4.0" or a string representing version information about the browser.
...And 6 more matches
PerformanceEntry.startTime - Web APIs
the starttime property returns the first recorded timestamp of the performance entry.
... the value returned by this property depends on the performance entry's type: "frame" - returns the timestamp when the frame was started.
... "mark" - returns the timestamp when the mark was created by a call to performance.mark().
...And 6 more matches
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
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 returns 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() returns an array of rtcicecandidate objects, each describing one of the ice candidates that have been gathered so far for the local device.
... getlocalparameters() returns a rtciceparameters object describing the ice parameters established by a call to the rtcpeerconnection.setlocaldescription() method.
...And 6 more matches
Request - Web APIs
WebAPIRequest
you can create a new request object using the request() constructor, but you are more likely to encounter a request object being returned as the result of another api operation, such as a service worker fetchevent.request.
... request.destination read only returns 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() returns a promise that resolves with an arraybuffer representation of the request body.
...And 6 more matches
Response - Web APIs
WebAPIResponse
you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being returned as the result of another api operation—for example, a service worker fetchevent.respondwith, or a simple windoworworkerglobalscope.fetch().
... response.error() returns a new response object associated with a network error.
...it returns a promise that resolves with an arraybuffer.
...And 6 more matches
Screen - Web APIs
WebAPIScreen
screen.availleft returns the first available pixel available from the left side of the screen.
... screen.availwidth returns the amount of horizontal space in pixels available to the window.
... screen.colordepth returns the color depth of the screen.
...And 6 more matches
ShadowRoot - Web APIs
properties shadowroot.delegatesfocus read only returns a boolean that indicates whether delegatesfocus was set when the shadow was attached (see element.attachshadow()).
... shadowroot.host read only returns a reference to the dom element the shadowroot is attached to.
... shadowroot.innerhtml sets or returns a reference to the dom tree inside the shadowroot.
...And 6 more matches
UIEvent - Web APIs
WebAPIUIEvent
uievent.detailread only returns a long with details about the event, depending on the event type.
... uievent.ischar read only returns a boolean indicating whether the event produced a key character or not.
... uievent.layerx read only returns 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 returns indexed information about a given target.
... syntax any gl.getindexedparameter(target, index); parameters target a glenum specifying the target for which to return information.
... possible values: gl.transform_feedback_buffer_binding: returns a webglbuffer.
...And 6 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
return value the returned 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 return; } var __nativest__ = window.settimeout; window.settimeout = function(vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc.
... */ ) { var aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ?
...And 6 more matches
WritableStreamDefaultWriter - Web APIs
the writablestreamdefaultwriter interface of the the streams api is the object returned by writablestream.getwriter() and once created locks the writer to the writablestream ensuring that no other streams can write to the underlying sink.
...returns 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 returns the desired size required to fill the stream's internal queue.
...And 6 more matches
XRView - Web APIs
WebAPIXRView
examples preparing to render every view for a pose to draw eerything the user sees each frame requires iterating over the list of views returned 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 returns 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) { return 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 returned by htmlmediaelement.play() will reject with a domexception.
...when this policy is disabled, the promise returned by navigator.getbattery() will reject with a notallowederror domexception.
...when this policy is disabled, the promise returned by getusermedia() will reject with a notallowederror domexception.
...And 6 more matches
Loops and iteration - JavaScript
control returns 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++; } } return 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 returns 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) { return 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 returning all matches.
...it returns an array of information or null on a mismatch.
...it returns 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`; } } return result; } so, the function call showprops(mycar, "mycar") would return 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 returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o.
... object.getownpropertynames(o) this method returns 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 return nan.
... function multiply(a, b) { return a * b } multiply(5, 2) // 10 multiply(5) // nan !
... b : 1 return 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
return value a new array instance.
...symbol.iterator : 'symbol(symbol.iterator)'; } catch { symboliterator = 'symbol(symbol.iterator)'; } var tostr = object.prototype.tostring; var iscallable = function (fn) { return ( typeof fn === 'function' || tostr.call(fn) === '[object function]' ); }; var tointeger = function (value) { var number = number(value); if (isnan(number)) return 0; if (number === 0 || !isfinite(number)) return number; return (number > 0 ?
... 1 : -1) * math.floor(math.abs(number)); }; var maxsafeinteger = math.pow(2, 53) - 1; var tolength = function (value) { var len = tointeger(value); return math.min(math.max(len, 0), maxsafeinteger); }; var setgetitemhandler = function setgetitemhandler(isiterator, items) { var iterator = isiterator && items[symboliterator](); return function getitem(k) { return isiterator ?
...And 6 more matches
Function.prototype.bind() - JavaScript
return 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'); } return function(){ var funcargs = args.concat(slice.call(arguments)) return 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); return ftobind.apply( fnop.prototype.isprototypeof(this) ?
...And 6 more matches
Math.sign() - JavaScript
the math.sign() function returns 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 return a +/- 0.
... note that if the number is positive, an explicit (+) will not be returned.
...And 6 more matches
String.fromCharCode() - JavaScript
the static string.fromcharcode() method returns a string created from the specified sequence of utf-16 code units.
... return value a string of length n consisting of the n specified utf-16 code units.
... description this method returns a string and not a string object.
...And 6 more matches
TypedArray.prototype.find() - JavaScript
the find() method returns a value in the typed array, if an element satisfies the provided testing function.
... otherwise undefined is returned.
... see also the findindex() method, which returns 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 returns an index in the typed array, if an element in the typed array satisfies the provided testing function.
... otherwise -1 is returned.
... see also the find() method, which returns the value of a found element in the typed array instead of its index.
...And 6 more matches
typeof - JavaScript
the typeof operator returns 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 returned.
... description the following table summarizes the possible return 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 returns a reference to the customelementregistry object.
... the element.shadowroot property returns 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() { return 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 returns 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); return 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 return 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); return 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); return 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 () { return this._x; }; point.prototype.setx = function (x) { this._x = x; }; point.prototype.gety = function () { return 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 () { return _x; }; this.setx = function (x) { _x = x; }; this.gety = function () { return _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; } return 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 returns nsidomwindow for that content.
... if target does not represents valid content null is returned.
... for example target can be a content window itself in which case it's will be returned 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) return (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 returned 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)) return null; return (hwnd)hwnd; } that's it; use with caution!
...And 5 more matches
Miscellaneous - Archive of obsolete content
system info operating system detection // returns "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; // returns "firefox" for firefox services.appinfo.version; // returns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous callback function that might not be called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see aroun...
...it also collapses consecutive whitespaces into a single whitespace, and returns 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., return 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 return 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) { return alert("response: " + (response ?
...And 5 more matches
Adding windows and dialogs - Archive of obsolete content
let somevalue = 2; let returnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, returnvalue); // you can send as many extra parameters as you need.
... // if (returnvalue.accepted) { do stuff } the optional parameters are available in the dialog code through the window.arguments property: let somevalue = window.arguments[0]; let returnvalue = window.arguments[1]; // returnvalue.accepted = true; // returnvalue.result = "something"; the parameter named returnvalue 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 return 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)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return 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)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return 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)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return 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 returned 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 returned 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 returned 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 returned 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 returned to the c++ caller.
... the ns_nointerface error is never reported when returned 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 returned 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"); } return 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); return false; } document.forms[0].onsubmit = loadcertificate; </script> signing text domstring signtext(domstring stringtosign, domstring caoption /* ...
...And 5 more matches
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
item(target) returns an item in the menu.
... return value a menuitem object, or null if no such target exists.
...it must return a non-function menuitem.
...And 5 more matches
Methods - Archive of obsolete content
dirgetparent returns an object representing the parent directory.
... diskspaceavailable returns the amount of disk space available in bytes.
... exists returns a boolean value indicating whether the specified file exists or not.
...And 5 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
this will return a table of result records which are then used to generate output.
...for example, if you spell a value wrong, no data may be returned, 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 return 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 returned are in pixels.
...width, height the width and height properties are also measured in pixels and return the width and height of the element, including css padding and borders.
... note that retrieving these values will return 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 returns the number of rows in a page.
... in the scrolling example above, getpagelength() would return four.
...the name was changed to getpagelength() since it was confusing before since it doesn't return 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 ) return type: element create a new notification and display it.
... if the return value from this function is not true, then the notification is closed.
... getnotificationwithvalue( value ) return 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 returns a supported mime type list for your plugin.
... npn_getintidentifier returns an opaque identifier for the integer that is passed in.
... npn_getstringidentifier returns 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 returned by another function and can be assigned as a value to a variable.
... example | pass a function as an argument javascript function sayhello() { return "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 | return a function javascript function sayhello() { return function() { console.log("hello!"); } } in this example; we need to return a function from another function - we can return 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() returns 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() returns 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 returned 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 returned.
...you should see the value you've assigned to the variable returned in the console to confirm it, in each case.
... again, you can return 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 return 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 return the <p> element we want.
... there's definitely a problem in the game logic somewhere — the game is not returning 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 returned by a method, please use the full name of the interface in the description of the method.
... @returns description if the method returns 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 returns a resolved promise.
... if the download is in progress, the method returns 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 returns 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 return value of a call into an asynchronous api.
...the method returns 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.
... return 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 return 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 returned.
... in the above example, $num equals 1, so the string returned (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 returns from its root function or the process abnormally terminates.
...pr_cleanup waits for the last user thread to exit before returning, 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 returned secfailure, and the bad certificate callback function either was not configured or did not choose to override the error code returned 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 returned 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 returned by pkcs#11 routines that did not provide meaningful error codes of their own.
...And 5 more matches
NSS tools : ssltap
MozillaProjectsNSStoolsssltap
-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 return to the debugger upon entry into the function.
... otherwise control will return 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 return to the debugger at the next line in the current function or top-level script.
...And 5 more matches
JS::IdentifyStandardInstance
if so, return the associated jsprotokey.
... if not, return jsproto_null.
...if so, return the associated jsprotokey.
...And 5 more matches
JS::Value
the number mutators attempt to use int32_t representation for compatible input values, returning 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*) returns an object value corresponding to the given non-null pointer, or a null value if the pointer is null.
... val.isobjectornull() returns true if the value is either an object or undefined.
...And 5 more matches
JS_GetFunctionId
description js_getfunctionid returns the name of a function, fun, as a jsstring, or null if fun is unnamed.
... the returned 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 returns 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() returns the application name.
... return value s_false if there is nothing to return, [out] value is null.
...appversion() returns 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) returns the first accessible parent of a dom node.
... guaranteed not to return 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 return the number of columns occupied by this cell.
... columnheadercells nsiarray return an array of column header cells for this cell.
... columnindex long return column index of this cell.
...And 5 more matches
nsICookieManager2
cookieexists() returns whether or not a matching cookie already exists.
... return value returns true if a cookie was found which matches the host, path, and name fields of acookie.
... countcookiesfromhost() returns the number of cookies that would be returned to a given host.
...And 5 more matches
nsIEnvironment
return value returns the value of the env variable.
... an empty string will be returned 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() returns 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 returned element will be the application-wide focused element (the value of focusedelement).
... the return value will be null if no element is focused.
... adeep if true, then child frames are traversed and the return value may be the element within a child descendant window that is focused.
...And 5 more matches
nsILivemarkService
return value the id of the folder for the livemark.
... return value returns the id of the folder for the livemark.
... return value a nsiuri representing the uri of the feed; if the livemark container doesn't have a valid feed uri, null will be returned or the nsiuri object returned will be the empty string.
...And 5 more matches
nsIMsgFolder
will return nsmsgkey_none if there was no last message loaded.
... dbtransferinfo nsidbfolderinfo subfolders nsisimpleenumerator readonly: returns an enumerator containing a list of nsimsgfolder items that are subfolders of the instance this is called on.
... hassubfolders boolean readonly: returns true if this folder has sub folders.
...And 5 more matches
nsINavHistoryResultTreeViewer
obsolete since gecko 1.9 constants constant value description index_invisible 0xffffffff returned by treeindexfornode() when the requested node isn't visible (such as when its parent is collapsed).
... also returned if there is no tree attached.
... methods nodefortreeindex() returns the node for a given row index.
...And 5 more matches
nsITreeColumns
nsitreecolumn getcolumnat( in long index ); parameters index index of the column return value a nsitreecolumn for this index.
...nsitreecolumn getcolumnfor( in nsidomelement element ); parameters element a dom element return value a nsitreecolumn for this element.
...return 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 returned 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 return value if istypesupported to detect whether a type is supported at all.
... image 1 returned 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)){ return self; } //line 6.
... nscomptr<nsiaccessible> accnode; rv = refp->getaccessiblefor(node, getter_addrefs(accnode)); if(ns_failed(rv)){ return self; } void *wh = null; nscomptr<nsiaccessibledocument> accdocnode; accdocnode = do_queryinterface(accnode, &rv); if(ns_failed(rv)){ return self; } rv = accdocnode->getwindowhandle(&wh); if(ns_succeeded(rv)){ self = static_cast<hwnd>(wh); } return 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)){ return 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 return value of window.open.
...the return 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 returns 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 returns a new ctype representing an array data type.
... return value a ctype represents the newly declared array type.
... ptr ctype returns a ctype representing the data type "pointer to this type".
...And 5 more matches
CType
ptr ctype returns a ctype representing the data type "pointer to this type".
... methods available on all ctype objects array() returns a new ctype representing an array of elements of the type on which it was called.
... return value a ctype representing the data type "array of this type".
...And 5 more matches
FunctionType
syntax returns a new ctype object describing a c function.
... ctype functiontype( abi, returntype[, argtype1, ...] ); parameters abi the abi type for the function; this is one of the abi constants.
... returntype a ctype indicating the type of the value returned by the function.
...And 5 more matches
ctypes
method overview ctype arraytype(type[, length]); cdata cast(data, type); ctype functiontype(abi, returntype[, 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 returns a new cdata object of array type.
...this can only be used as a return 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 returns an error code.
... unix and ms windows the queried information is returned in the variable parameter.
...the value parameter returns 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 returns 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 returns an array of cssstylevalue objects, each containing one of the supplied values.
... cssunparsedvalue.entries() method returning 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 returns an unsigned long representing the size of the string contained in characterdata.data.
... nondocumenttypechildnode.nextelementsibling read only returns 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 returns 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
WebAPIDOMParser
note: xmlhttprequest can parse xml and html directly from a url-addressable resource, returning a document in its response property.
... syntax let domparser = new domparser()​​ methods domparser.parsefromstring() syntax let doc = domparser.parsefromstring(string, mimetype) return either document or xmldocument depending on the mimetype argument.
...this string determines a class of the the method's return value.
...And 5 more matches
DirectoryEntrySync - Web APIs
example the getfile() method returns a fileentrysync, which represents a file in the file system.
... var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system.
... directoryreadersync createreader ( ) raises (fileexception); returns 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 returns a new documentfragment object.
... parentnode.children read only returns a live htmlcollection containing all objects of type element that are children of the documentfragment object.
... parentnode.firstelementchild read only returns 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 returns a collection of domrect objects that indicate the bounding rectangles for each css border box in a client.
... syntax let rectcollection = object.getclientrects(); return value the returned value is a collection of domrect objects, one for each css border box associated with the element.
... originally, microsoft intended this method to return a textrectangle object for each line of text.
...And 5 more matches
HTMLMediaElement.play() - Web APIs
it returns a promise which is resolved when playback has been successfully started.
... return 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 return a value from play().
...And 5 more matches
HTMLObjectElement - Web APIs
htmlobjectelement.contentdocument read only returns a document representing the active document of the object element's nested browsing context, if any; otherwise null.
... htmlobjectelement.contentwindow read only returns a windowproxy representing the window proxy of the object element's nested browsing context, if any; otherwise null.
... htmlobjectelement.data returns 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 returns null.
...when multiple is true, it returns "select-multiple"; otherwise, it returns "select-one".
...returns the value property of the first selected option element if there is one, otherwise the empty string.
...And 5 more matches
IDBCursor - Web APIs
WebAPIIDBCursor
idbcursor.source read only returns the idbobjectstore or idbindex that the cursor is iterating.
... this function never returns 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 returns 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 returns exceptions this method can raise a idbdatabaseexception with the following code: value the value to store into the index.
... returns any the retrieved value from the index.
... getobject() retrieves and returns 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 return an idbrequest instance.
...when the state is set to done, every request returns a result and an error, and an event is fired on the request.
... in plain words, all asynchronous methods return 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 returned 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) { return new promise(resolve => settimeout(resolve, delayinms)); } the wait() function returns 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() ); return 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 returned 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 returns 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 returned 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 returns true if the alt key was down when the mouse event was fired.
... mouseevent.ctrlkey read only returns true if the control key was down when the mouse event was fired.
...And 5 more matches
NodeIterator - Web APIs
the nodes will be returned in document order.
... nodeiterator.root read only returns a node representing the root node as specified when the nodeiterator was created.
... nodeiterator.whattoshow read only returns 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 returned 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.
... return value a promise that eventually resolves with a paymentresponse.
... exceptions aborterror the returned 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 returns 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 returns 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 returns 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 return the required object parameters: function buildsupportedpaymentmethoddata() { // example supported payment methods: return [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard'], supportedtypes: ['debit', 'credit'] } }]; } function buildshoppingcartdetails() { // hardcoded for demo purposes: return { id: 'order-123', display...
...this returns 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 returns 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 returned 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 returned is 0.
...if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0.
...And 5 more matches
Request.cache - Web APIs
WebAPIRequestcache
if there is a match and it is fresh, it will be returned from the cache.
...if the server indicates that the resource has not changed, it will be returned from the cache.
...if the server indicates that the resource has not changed, it will be returned from the cache.
...And 5 more matches
SpeechRecognition - Web APIs
speechrecognition.grammars returns and sets a collection of speechgrammar objects that represent the grammars that will be understood by the current speechrecognition.
... speechrecognition.lang returns and sets the language of the current speechrecognition.
... speechrecognition.continuous controls whether continuous results are returned for each recognition, or only a single result.
...And 5 more matches
SpeechRecognitionEvent - Web APIs
speechrecognitionevent.emma read only returns an extensible multimodal annotation markup language (emma) — xml — representation of the result.
... speechrecognitionevent.interpretation read only returns the semantic meaning of what the user said.
... speechrecognitionevent.resultindex read only returns 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() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding.
... textencoder.prototype.encodingread only always returns "utf-8".
... textencoder.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text.
...And 5 more matches
URL - Web APIs
WebAPIURL
constructor new url() creates and returns 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 returns a usvstring containing the whole url.
... origin read only returns 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() returns a urlsearchparams object instance.
... urlsearchparams.entries() returns an iterator allowing iteration through all key/value pairs contained in this object.
... urlsearchparams.get() returns the first value associated with the given search parameter.
...And 5 more matches
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
possible values: gl.uniform_block_binding: returns a gluint indicating the uniform buffer binding point.
... gl.uniform_block_data_size: returns a gluint indicating the minimum total buffer object size.
... gl.uniform_block_active_uniforms: returns 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: returns an array of glenum indicating the types of the uniforms.
... gl.uniform_size: returns an array of gluint indicating the sizes of the uniforms.
... gl.uniform_block_index: returns 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 returns a value for the passed parameter name.
... syntax any gl.getparameter(pname); parameters pname a glenum specifying which parameter value to return.
... return value depends on the parameter.
...And 5 more matches
A basic 2D WebGL animation example - Web APIs
its role is to return the color of each pixel in the shape being rendered.
... the shader set is passed into the function buildshaderprogram(), which returns 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 returns 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 return the transformed vertex by saving it in a special variable provided by glsl, called gl_position.
...the color is then returned to the webgl layer by storing it in the special variable gl_fragcolor.
... in this case, we're simply returning 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 return 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]; return [x, y, z, 1]; } function homogeneoustocartesian(point) { let x = point[0]; let y = point[1]; let z = point[2]; let w = point[3]; return [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) { return; } /* 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" */ return 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); } return function (oformelement) { if (!oformelement.action) { return; } 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); return 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() returns 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 return the native framebuffer scaling factor.
... return 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
WebHTMLElementinput
this attribute has no effect on input types that do not return 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 returns or line feeds.
... mozactionhint a string indicating the type of action that will be taken when the user presses the enter or return 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 return a value of undefined.
... so even if you declare and initialize after you use or refer to this variable, it still returns undefined.
... /** * example 1 */ console.log(x === undefined); // true var x = 3; /** * example 2 */ // will return 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() { return '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() { return '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() returns in a subclass.
...And 5 more matches
arguments.callee - JavaScript
for example, this syntax worked: function factorial (n) { return !(n > 1) ?
... 1 : factorial(n - 1) * n; } [1, 2, 3, 4, 5].map(factorial); but: [1, 2, 3, 4, 5].map(function(n) { return !(n > 1) ?
...to get around this arguments.callee was added so you could do [1, 2, 3, 4, 5].map(function(n) { return !(n > 1) ?
...And 5 more matches
getter - JavaScript
description sometimes it is desirable to allow access to a property that returns 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 return the last array item in log.
... const obj = { log: ['example','test'], get latest() { if (this.log.length === 0) return undefined; return 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 returns 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 returned.
... return value a new array containing the extracted elements.
...And 5 more matches
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
return value an array of objects containing the formatted date in parts.
...it returns 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 returns, 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 returns a non-negative integer that is the unicode code point value.
... syntax str.codepointat(pos) parameters pos position of an element in str to return the code point value from.
... return 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 returns a boolean value.
... however, the && operator actually returns the value of one of the specified operands, so if this operator is used with non-boolean values, it will return a non-boolean value.
... syntax expr1 && expr2 description if expr1 can be converted to true, returns expr2; else, returns expr1.
...And 5 more matches
Logical OR (||) - JavaScript
when it is, it returns a boolean value.
... however, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-boolean values, it will return a non-boolean value.
... syntax expr1 || expr2 description if expr1 can be converted to true, returns expr1; else, returns expr2.
...And 5 more matches
Nullish coalescing operator (??) - JavaScript
the nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
... contrary to the logical or (||) operator, the left operand is returned 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 returned.
...And 5 more matches
void operator - JavaScript
the void operator evaluates the given expression and then returns 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', returns false void (2 == '2'); // void (2 == '2'), returns 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 returned value, unless the returned 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, return information on what custom elements are registered, etc.
... // create a shadow root this.attachshadow({mode: 'open'}); // sets and returns '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 returns 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 returns a promise resolving to the new database.
... function opendatabase() { return 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 return 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) return 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 returns 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 returned by the api.
... because the search function is expected to return 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="return onaccept();" ondialogcancel="return oncancel();"> <script src="chrome://..."/> <!-- content --> </dialog> you need to implement onaccept and oncancel functions in your script.
... if they return anything but false, the dialog will be closed.
... passing parameter to a dialog and getting return 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,returnresult) { var request = new xmlhttprequest(); request.open("get", url, true); // async=true request.responsetype = type; request.onerror = function(event) { logerrormessage("error attempting to load: " + url); returnresult(null); }; request.onload = function(event) { if (request.response) returnresult(request.response); else ...
...here are some functions to handle this: function getgenericpref(branch,prefname) { switch (branch.getpreftype(prefname)) { default: case 0: return undefined; // pref_invalid case 32: return getucharpref(prefname,branch); // pref_string case 64: return branch.getintpref(prefname); // pref_int case 128: return branch.getboolpref(prefname); // pref_bool } } function setgenericpref(branch,prefname,prefvalue) { switch (typeof prefvalue) { case "string": setucharpref...
...(prefname,prefvalue,branch); return; case "number": branch.setintpref(prefname,prefvalue); return; case "boolean": branch.setboolpref(prefname,prefvalue); return; } } 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 returns 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 returns 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 returns 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: // return; // 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"); return recentwindow ?
...in those cases, the following code returns 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 returns a weak reference to the object.
...it has a get method which returns 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 return it.
... itemexists(guid) should simply return true if an item with the given guid exists in the store, false otherwise.
... getallids() must return 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 returns true.
...for example: <wizard id="example-window" title="select a dog wizard" onwizardfinish="return 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 returns true, the wizard closes.
...And 4 more matches
Document Object Model - Archive of obsolete content
function gettext(){ return "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 returns 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 returns 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 returns a status code that indicates what the user selected.
... note that the function does not return until the user has selected a file.
... the function returns one of three constants: returnok - the user selected a file and pressed ok.
...And 4 more matches
menupopup - Archive of obsolete content
returning 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() return type: no return value closes the popup immediately.
... moveto( x, y ) return type: no return 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
returning 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() return type: no return value closes the popup immediately.
... moveto( x, y ) return type: no return 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 returned from shouldload() or shouldprocess() if the load or process request is rejected based on details of the request.
... reject_type -2 returned from shouldload() or shouldprocess() if the load/process is rejected based solely on its type (of the above flags).
... reject_server -3 returned 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 returns 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();} return 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') { return s.replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } if (typeof s === 'xml') { return s.tostring().replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } return string(s).replace(/"/g, '&quot;'...
... createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.call(arguments, 1); return strs.formatstringfromname(msg,args,args.length); } return 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 return h(cond); } else if (_else) { return _else(cond); } return ''; // 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 return 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 returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object.
... keyonly if keyonly is truthy value, iterator.prototype.next returns property_name only.
... description returns iterator instance that iterates over object.
...And 4 more matches
JavaArray - Archive of obsolete content
created by any java method which returns 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 returned by java.lang.class.forname.
...for example: var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); bytearray[0] // returns 72 bytearray[1] // returns 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 return a scriptable iid and a pointer to a scriptable instance object.
... ns_imethod getflags(pruint32 *aflags) {*aflags = nsiclassinfo::plugin_object | nsiclassinfo::dom_object; return ns_ok;} ns_imethod getimplementationlanguage(pruint32 *aimplementationlanguage) {*aimplementationlanguage = nsiprogramminglanguage::cplusplus; return ns_ok;} // the rest of the methods can safely return 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; } } return 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 returns 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; return 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 returned 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 returned 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: webkitreturn 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) { return localdb.put(...); }).then(function (resultofput) { return localdb.get(...); }).then(function (resultofget) { return localdb.put(...); }).catch(function (err) { console.log(err); }); or even: remotedb.alldocs(...) .then(resultofalldocs => { return localdb.put(...); }) .then(resultofput => { return localdb.get(...); }) .then(resultofget => { return 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 returns 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 returns 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 returns 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) { return 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})) return {...t, completed: completed} }) } in this case we are using the map() method, which returns a new array with the results of executing the provided function for each item.
... the function returns a copy of each todo using spread syntax and overwrites the property of the completed value accordingly.
... this solution has the added benefit of returning 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 returned 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 { return 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)) return 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 return 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 returns, 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 returns ns_ok.
...And 4 more matches
Implementing QueryInterface
if ( !ainstanceptr ) return 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; return status; } what's so good about it?
...it has more than one return, but the primary return is at the end of the function as expected; and the additional return 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 returns a list of recommended add-ons, and searchaddons(), which performs a search of the repository.
... methods getrecommendedurl() returns the url that can be visited to see recommended add-ons.
... return 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) { return 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 return an array which is the final fallback chain of locales, or if the negotiation is asynchronous, it must return a falsy value and call the callback argument upon completion.
... ctx.linkresource(function(locale) { return '../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 returns from the root function.
... pr_joinable_thread joinable thread references remain valid after they have returned 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 returns from its root function.
...And 4 more matches
PR_FindSymbolAndLibrary
finds a symbol in one of the currently loaded libraries, and returns both the symbol and the library in which it was found.
... returns if successful, returns 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, returns 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) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { return 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"); return 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"); return 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); return 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 returns 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 returning false.
...otherwise the callback must return true, and the property operation proceeds.
...And 4 more matches
JS_DecompileScript
return the source code of the script or the function.
... description js_decompilescript returns the source code of script.
...otherwise, it returns the original source code of the script.
...And 4 more matches
Split object
inner objects implement the jsextendedclass.outerobject hook, which returns a pointer to the corresponding outer object.
...the script in a might have opened tb by calling window.open, which returns a direct reference to tb's window.
...the outer window object is the object returned by window.open.
...And 4 more matches
Redis Tips
in standard node fashion, first return value is error or null; second return 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 return value from setnx is 1 if the value was set, 0 otherwise.
... they return the post-increment value of your key.
...And 4 more matches
Using the Places history service
when isvisited returns true, the link gets the "visited" style.
...because actually counting all the pages in history is expensive,navhistory will always return the value 0 or 1.
... 0 is returned when there is no history, 1 is returned 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 return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.
... syntax var succeeded = components.issuccesscode(returncode); parameters returncode the return code (of type nsresult) to be checked.
... description components.issuccesscode() may be used to determine whether an xpcom return code (an nsresult) indicates success or failure.
...And 4 more matches
IAccessibleEditableText
return value e_invalidarg if bad [in] passed.
... return value e_invalidarg if bad [in] passed.
... return 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() returns the localized description of the image.
... return value s_false if there is nothing to return, [out] value is null.
...imageposition() returns the coordinates of the image.
...And 4 more matches
mozIStorageAggregateFunction
an aggregate function is a function that returns 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 returned by the query.
... the implementation should store or perform some work to prepare to return a value.
...And 4 more matches
mozIStorageService
the actual backup file is returned, and the resulting filename can be obtained from that.
... return value an nsifile object representing the newly-created backup file.
...note: the connection object returned by this function is not threadsafe.
...And 4 more matches
mozITXTToHTMLConv
return value the html version of the specified string.
... return value a normalized version of the original html string.
... citeleveltxt() returns 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() returns an nsiarray of the selected nsiaccessible children.
...return value an nsiarray.
... return 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 return immediately after calling and return the entered data in a callback.
...calling nsicancelable.cancel() on the returned 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 returning.
...And 4 more matches
nsICategoryManager
return value the previous value for the given category entry (if any).
... exceptions thrown ns_error_invalid_arg this error is returned if areplace is false and the category entry already has a value, or if apersist is true.
... return value a simple enumerator, each result qis to nsisupportscstring.
...And 4 more matches
nsIClassInfo
no implementor of this interface should ever return flags with this bit set.
...it has no meaning when returned from the flags attribute of a nsiclassinfo implementation.
... for example, if asked for the helper for nsiprogramminglanguage::javascript this might return 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() returns the number of items in the collection.
...return value number of items in the list.
... enumerate() returns an nsienumerator that lets you iterate over the items in the collection.
...And 4 more matches
nsIComponentManager
unlike getservice, this returns a new instance each time it is called.
... aiid the interface type to be returned.
... aiid the interface type to be returned.
...And 4 more matches
nsIContentPrefService
getpref() returns the value of a preference saved for a particular site.
... return value the preference's value is returned; this value may be a string, integer, boolean, or any other value.
... return 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 returned object will be undefined (nsidatatype.vtype_void()).
... if the preference is neither cached nor known not to exist, then null is returned, and get() must be called to determine whether the preference exists.
... return 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 returned value is a base-64 encoded string.
... if false, then the returned value is binary data.
... return value this method returns a hash of the data that was read by this object.
...And 4 more matches
nsIDispatchSupport
gethostingflags() return the activex security and hosting flags.
...unsigned long gethostingflags( in string acontext ); parameters acontext return value isclassmarkedsafeforscripting() test if the specified class is marked safe for scripting.
...classexists returns containing pr_false if the class is not registered.
...And 4 more matches
nsIDownloadManager
defaultdownloadsdirectory nsilocalfile returns the platform default downloads directory.
...obsolete since gecko 1.8 userdownloadsdirectory nsilocalfile returns 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 returned nsidownload object, and then call the nsiwebbrowserpersist.saveuri() method.
...And 4 more matches
nsIDroppedLinkHandler
return value true if the link being dragged can be dropped.
...if a uri is returned the caller can, for instance, load it.
... if null is returned, there is no valid link to be dropped.
...And 4 more matches
nsIExternalProtocolService
return value true if we have a handler and false otherwise.
... return 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 returns 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); return { get objectname () { return "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); return true; }, registerfile: function(path, filepath) { var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(filepath); return server.registerfile(path, file); }, registerdirectory : function(path, directorypath) { var...
... file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(directorypath); return 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, returning a utf-8 format string.
... return value the utf-8 encoded equivalent of the hostname.
...isascii on return, this is set to true if the result is ascii or ace encoded; otherwise it's false.
...And 4 more matches
nsIInstallLocation
return value the id for an item that might live at the location specified.
... return value a file object at the requested location.
... return value the location of the item.
...And 4 more matches
nsIMemory
ns_getmemorymanager returns the global nsimemory instance.
... return value if the memory cannot be allocated (because of an out-of-memory condition), null is returned.
... otherwise, it returns a pointer to the newly allocated memory segment.
...And 4 more matches
nsINavHistoryContainerResultNode
methods findnodebydetails() returns a node matching specified details.
... return value an nsinavhistoryresultnode of a node matching the specified details or null if no match is found.
... getchild() returns the child node at the specified index.
...And 4 more matches
nsIPluginHost
nsifile createtempfiletopost( in string apostdataurl ); parameters apostdataurl return 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.) returns 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 return 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 returning.
... if not set, posts a request which is processed at some point after the method returns.
... return 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 returns a reference to a particular xpcom service given the classid of the service.
... unlike createinstance, this will always return the same object each time it is called with the same arguments.
... aiid the interface type to be returned.
...And 4 more matches
nsISocketTransport
securityinfo nsisupports security info object returned from the secure socket provider.
... methods native code only!getpeeraddr returns the ip address of the socket connection peer.
...return 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() returns 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.
... return value returns the formatted string.
... formatstringfromname() returns 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.
... return value the converted, exposable uri, as an nsiuri.
...returns 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 return a boolean depending on whether they clicked "ok" or "cancel".
... a web page could redefine it to return true: window.confirm = function() { return 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() {return 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 returns a ctype object describing a new structure data type.
... return value a ctype object describing the newly created struct data type.
... ptr ctype returns a ctype representing the data type "pointer to this type".
...And 4 more matches
Version, UI, and Status Information - Plugins
this function returns 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 returns 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 return 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 return 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 return 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 + return 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 return enter find the previous match in the markup, when searching is active shift + enter shift + return 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 return 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 return 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 , returning the first node descended from element that matches.
... $$(selector, element) looks up a css selector string selector, returning an array of dom nodes descended from element that match.
...this is like for document.queryselectorall(), but returns an array instead of a nodelist.
...And 4 more matches
AnimationEffect.getComputedTiming() - Web APIs
the getcomputedtiming() method of the animationeffect interface returns the calculated timing properties for this animation effect.
... although many of the attributes of the returned object are common to the effecttiming contained in the object returned by the animationeffect.gettiming() method, the values returned by this object differ in the following ways: duration returns the calculated value of the iteration duration.
... if effecttiming.duration is the string auto, this attribute will return 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 returns 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 returns a double representing an ever-increasing hardware time in seconds used for scheduling.
... baseaudiocontext.destination read only returns an audiodestinationnode representing the final destination of all audio in the context.
...And 4 more matches
Blob.stream() - Web APIs
WebAPIBlobstream
the blob interface's stream() method returns a readablestream which upon reading returns the data contained within the blob.
... returns a readablestream which, upon reading, returns the contents of the blob.
... usage notes with stream() and the returned readablestream, you gain several interesting capabilities: call getreader() on the returned 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
WebAPIBlob
constructor blob() returns 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() returns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data.
... blob.prototype.slice() returns 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
WebAPIBluetooth
the bluetooth interface of the web bluetooth api returns a promise to a bluetoothdevice object with the specified options.
... bluetooth.referringdevice read only returns a reference to the device, if any, from which the user opened the current page.
... methods bluetooth.getavailability() returns 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 returns information about a bluetooth device through an instance of bluetoothdevice.
... bluetoothremotegattservice.isprimaryread only returns a boolean indicating whether this is a primary or secondary service.
... bluetoothremotegattservice.uuidread only returns 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 return 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)] } return 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()); return n + " : " + o } function coll(t, e) { return 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 returns 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; return [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; return [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
WebAPIClientsmatchAll
the matchall() method of the clients interface returns a promise for a list of service worker client objects.
... include the options parameter to return all service worker clients whose origin is the same as the associated service worker's origin.
... if options are not included, the method returns 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 returns a validitystate object, whose properties represent validation errors for the value of that element.
... validationmessage a read-only property that returns 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 returns a localized validation message.
...And 4 more matches
DOMImplementation - Web APIs
such an object is returned by the document.implementation property.
... domimplementation.createdocument() creates and returns an xmldocument.
... domimplementation.createdocumenttype() creates and returns a documenttype.
...And 4 more matches
DOMLocator - Web APIs
returned by domerror.location.
... properties domlocator.linenumber read only returns a positive integer or -1.
... domlocator.columnnumber read only returns a positive integer or -1.
...And 4 more matches
Document.querySelector() - Web APIs
the document method queryselector() returns the first element within the document that matches the specified selector, or group of selectors.
... if no matches are found, null is returned.
... return value an htmlelement object representing the first element in the document that matches the specified set of css selectors, or null is returned if there are no matches.
...And 4 more matches
EventTarget.addEventListener() - Web APIs
return 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 return 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 returns nothing.
... passivesupported = true; return 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 returns metadata exceptions this method can raise a fileexception with the following codes: exception description not_found_err the entry does not exist.
... returns filesystementrysync an object that represents an entry in the file system.
... returns filesystementrysync an object that represents an entry in the file system.
...And 4 more matches
GeolocationCoordinates - Web APIs
geolocationcoordinates.latitude read only secure context returns a double representing the position's latitude in decimal degrees.
... geolocationcoordinates.longitude read only secure context returns a double representing the position's longitude in decimal degrees.
... geolocationcoordinates.altitude read only secure context returns 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 returns the number of items in the collection.
... methods htmlcollection.item() returns the specific node at the given zero-based index into the list.
... returns 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 returns a new htmlimageelement object representing an html <img> element which is not attached to any dom tree.
... htmlimageelement.complete read only returns a boolean that is true if the browser has finished fetching the image, whether successful or not.
... htmlimageelement.currentsrc read only returns 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 returns a list of mime-type like domstrings, such as text/plain or image/jpeg.
...you can do this either by returning false from attribute-defined event listeners, or by calling the event's preventdefault() method.
... <div ondragover="return 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
WebAPIHeaders
headers.entries() returns an iterator allowing to go through all key/value pairs contained in this object.
... headers.get() returns a bytestring sequence of all the values of a header within a headers object with a given name.
... headers.has() returns a boolean stating whether a headers object contains a certain header.
...And 4 more matches
IDBDatabaseSync - Web APIs
methods createobjectstore() creates and returns a new object store with the given name in the connected database.
... returns idbobjectstoresync an object to access the newly created object store.
... returns 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 returned by setinterval().
...And 4 more matches
KeyboardEvent.code - Web APIs
in other words, this property returns 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 returned 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 returned 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
WebAPIKeyboardEventkey
the keyboardevent interface's key read-only property returns 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 returned 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 returned 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 returned mediastream.
... since getdisplaymedia() requires a video track, the returned stream will have one even if no video track is expressly requested by the constraints object.
... return 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 returns the number of key/value pars in the status map.
... methods mediakeystatusmap.entries() read only returns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order.
... mediakeystatusmap.get() read only returns the value associated with the given key, or undefined if there is none.
...And 4 more matches
NodeList - Web APIs
WebAPINodeList
nodelist objects are collections of nodes, usually returned by properties such as node.childnodes and methods such as document.queryselectorall().
...the ubiquitous document.queryselectorall() method returns a static nodelist.
... methods nodelist.item() returns 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
WebAPIPerformancenow
the performance.now() method returns a domhighrestimestamp, measured in milliseconds.
... the returned 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 returned 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 returns "resource".
... performanceentry.nameread only returns the resources url.
... performanceentry.starttimeread only returns 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 returns 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 () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() constructor is deprecated.
... return value a promise which is fulfilled once the value of the connection's remotedescription is successfully changed or rejected if the change cannot be applied (for example, if the 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 returns 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 returned by the stun or turn server.
...And 4 more matches
RTCRtpReceiver - Web APIs
properties rtcrtpreceiver.track read only returns the mediastreamtrack associated with the current rtcrtpreceiver instance.
... rtcrtpreceiver.transport read only returns the rtcdtlstransport instance over which the media for the receiver's track is received.
... methods rtcrtpreceiver.getcontributingsources() returns 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 returns a readable stream object from the given handlers.
...if this process is to be done asynchronously, it can return a promise to signal success or failure.
...if pull() returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored.
...And 4 more matches
SpeechRecognitionAlternative.confidence - Web APIs
the confidence read-only property of the speechrecognitionresult interface returns 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 return 1.
... syntax var myconfidence = speechrecognitionalternativeinstance.confidence; returns a number betwen 0 and 1.
...And 4 more matches
StylePropertyMapReadOnly - Web APIs
properties stylepropertymapreadonly.size returns an unsinged long integer containing the size of the stylepropertymapreadonly object.
... methods stylepropertymapreadonly.entries() returns 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() returns the value of the specified property.
...And 4 more matches
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
it returns a promise which will be fulfilled with the signature.
... return 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 returns 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 returns 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 returns 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 returns parameter information of a webglsync object.
... pname a glenum specifying which information to return.
... possible values: gl.object_type: returns 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 return these two descriptions, aren't as simple as they look.
... the current description (which is returned by the rtcpeerconnection.currentlocaldescription and rtcpeerconnection.currentremotedescription properties) represents the description currently in actual use by the connection.
... the pending description (returned 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) { return; } 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) { return; } 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 return 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 returns 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); return 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 returned to the caller.
...And 4 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
all you really need to know is that it returns 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); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing.
...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; return notefreq; } the result is an array, notefreq, with an object for each octave.
... if (!object.entries) { object.entries = function entries(o) { return 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 returns a selection object representing the range of text selected by the user or the current position of the caret.
... syntax selection = window.getselection(); return value a selection object.
... when cast to string, either by appending an empty string ("") or using selection.tostring(), this object returns the text selected.
...And 4 more matches
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the call to opendialog() returns 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 returns the cachestorage object associated with the current context.
... windoworworkerglobalscope.crossoriginisolated read only returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call.
... windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object.
...And 4 more matches
WritableStream - Web APIs
writablestream.getwriter() returns a new instance of writablestreamdefaultwriter and locks the stream to that instance.
...inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
...finally, write() and close() return 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() returns all the response headers, separated by crlf, as a string, or returns null if no response has been received.
... if a network error happened, an empty string is returned.
... note: for multipart requests, this returns 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 returns 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 returned by getoffsetreferencespace() is an xrreferencespace if called on an xrreferencespace, or an xrboundedreferencespace if called on an object of that type.
... return 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 returns 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 returned.
... the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace.
...And 4 more matches
@supports - CSS: Cascading Style Sheets
WebCSS@supports
the following example returns 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 returns 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 returns 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
WebHTMLElementinputfile
getting information on selected files the selected files' are returned by the element's htmlinputelement.files property, which is a filelist object containing a list of file objects.
...the custom returnfilesize() function returns 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 ${returnfilesize(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
returns an object containing the canvas's 2d context and the wrapper's id.
...returns the list's id.
...returns 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, return undefined.
... var o = { a: 2, m: function() { return 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/return key.
...And 4 more matches
Private class fields - JavaScript
syntax class classwithprivatefield { #privatefield } class classwithprivatemethod { #privatemethod() { return '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 return 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 return 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() { return this.calcarea(); } // method calcarea() { return 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; return 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() { return this; } static eat() { return 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 returns the longest one: function longeststring() { var longest = ''; for (var i=0; i < arguments.length; i++) { if (arguments[i].length > longest.length) { longest = arguments[i]; } } return longest; } you can use arguments.length to count how many arguments the function was called with.
... using typeof with arguments the typeof operator returns '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]); // returns the type of the first argument properties arguments.callee reference to the currently executing function that the arguments belong to.
... arguments[@@iterator] returns 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 returned in the last invocation of the callback, or initialvalue, if supplied.
... return 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 returned without calling callback.
...And 4 more matches
Date.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns 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 returned are entirely implementation-dependent.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.
...And 4 more matches
Math.ceil() - JavaScript
note: math.ceil(null) returns integer 0 and does not give a nan error.
... return value the smallest integer greater than or equal to the given number.
... * @returns {number} the adjusted value.
...And 4 more matches
Math.floor() - JavaScript
the math.floor() function returns the largest integer less than or equal to a given number.
... return value a number representing the largest integer less than or equal to the specified number.
... note: math.floor(null) returns 0, not a nan.
...And 4 more matches
Math.fround() - JavaScript
the math.fround() function returns the nearest 32-bit single precision float representation of a number.
... return 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 returned.
...And 4 more matches
Math.log() - JavaScript
the math.log() function returns 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.
... return value the natural logarithm (base e) of the given number.
... if the number is negative, nan is returned.
...And 4 more matches
Math.random() - JavaScript
the math.random() function returns 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() return 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() { return math.random(); } getting a random number between two values this example returns a random number between the specified values.
...And 4 more matches
Math.random() - JavaScript
the math.random() function returns 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() return 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() { return math.random(); } getting a random number between two values this example returns a random number between the specified values.
...And 4 more matches
Number.prototype.toFixed() - JavaScript
return value a string representing the given number using fixed-point notation.
... description tofixed() returns 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 returns a string in exponential notation.
...And 4 more matches
Object.prototype.__lookupGetter__() - JavaScript
the __lookupgetter__ method returns 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 returned.
... return value the function bound as a getter to the specified property.
...And 4 more matches
Object.entries() - JavaScript
the object.entries() method returns 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 returned 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 returned.
...And 4 more matches
Object.freeze() - JavaScript
freeze() returns the same object that was passed in.
... return value the object that was passed to the function.
... freeze() returns the same object that was passed into the function.
...And 4 more matches
Object.keys() - JavaScript
the object.keys() method returns 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 returned.
... return 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 returns a boolean indicating whether the specified property is enumerable and is the object's own property.
... return 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 returns false.
...And 4 more matches
Object.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object.
... syntax object.tosource(); obj.tosource(); return value a string representing the source code of the object.
... description the tosource() method returns the following values: for the built-in object object, tosource() returns the following string indicating that the source code is not available: function object() { [native code] } for instances of object, tosource() returns a string representing the source code.
...And 4 more matches
Object.prototype.toString() - JavaScript
the tostring() method returns a string representing the object.
... syntax obj.tostring() return value a string representing the object.
...if this method is not overridden in a custom object, tostring() returns "[object type]", where type is the object type.
...And 4 more matches
Promise.prototype.catch() - JavaScript
the catch() method returns a promise and deals with rejected cases only.
... the promise returned by catch() is rejected if onrejected throws an error or returns a promise which is itself rejected; otherwise, it is resolved.
... return 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
returns true or false.
... returns true if there is a match between the regular expression and the string str.
...test() returns a boolean, unlike the string.prototype.search() method (which returns the index of a match, or -1 if not found).
...And 4 more matches
String.prototype.localeCompare() - JavaScript
the localecompare() method returns 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 returned are entirely implementation-dependent.
... return 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
return 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" returned 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); return 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 returns a floating point number.
... return 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 returns 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 returned from a function it's always been possible to return an array from a function.
... destructuring can make working with an array return value more concise.
... in this example, f() returns 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, returning a boolean result.
...this can be roughly summarised as follows: if the operands are both objects, return true only if both operands reference the same object.
... if one operand is null and the other is undefined, return true.
...And 4 more matches
Logical NOT (!) - JavaScript
when used with non-boolean values, it returns false if its single operand can be converted to true; otherwise, returns true.
... syntax !expr description returns false if its single operand can be converted to true; otherwise, returns true.
...operator can be used with operands that are not boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive.
...And 4 more matches
instanceof - JavaScript
the return value is a boolean value.
...for instance, [] instanceof window.frames[0].array will return false, because array.prototype !== window.frames[0].array and arrays inherit from the former.
...components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and returns true if queryinterface succeeded.
...And 4 more matches
Expressions and operators - JavaScript
void the void operator discards an expression's return value.
... arithmetic operators arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.
... relational operators a comparison operator compares its operands and returns 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 return this templated literal.
... the tag function can then perform whatever operations on these arguments you wish, and return the manipulated string.
... (alternatively, it can return 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, return 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'); return cache.addall(contenttocache); }) ); }); there are two things that need an explanation here: what extendableevent.waituntil does, and what the caches object is.
...it returns 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
returns 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 returned from settimeout(), prevents the callback with the id from being called (if it hasn't yet been called).
... parameters id : integer an id returned 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 return our `loadermodule`.
... the function returns 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) return 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 returns 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 returned.
... options : object optional options: name type count number the number of bookmark items to return.
...And 3 more matches
preferences/service - Archive of obsolete content
returns string,number,boolean : preference value, returns defaultvalue if no preference is set, returns undefined if defaultvalue is not provided.
... returns boolean : returns whether or not the application preference name exists.
... returns array : returns 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 return 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; return true; }, promptpassword: function(dialogtitle, text, passwordrealm, savepassword, pwd) { pwd.value = hardcodedpassword; return true; }, promptusernameandpassword: function(dialogtitle, text, passwordrealm, savepassword, user, pwd) { user.value = hardcodedusername; pwd.value = hardcodedpassword; return true; } }; persist.saveuri(urltosave, null, null, null, "", nsfil...
... instead of using qi like above, you can also implement nsiinterfacerequestor and return 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 return 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)); return 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 returns that value.
... if there's a value of the expected type in the default tree, it is returned (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("",{}) returns an array of preference names that start with that branch's root, for example var branch = prefs.getbranch("accessibility."); var children = branch.getchildlist("", {}); will return 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 returning 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 return 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 return 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 returns 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 returned 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>.returns{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)returns data to jetpack from the clipboard.
... if flavor is provided, the data is returned 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"); return 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)); return 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"); return 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"); return(false); } return(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() returned: " + err); // create the plugins folder next to mozilla var pluginsfolder = getfolder("plugins"); if (!fileexists(pluginsfolder)) { var ignoreerr = dircreate(pluginsfolder); logcomment("dircreate() returned: " + 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 returns 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() { return this._id; }, // return 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); return this._data[name]; }, // return an object instead of a string for convenient comparison purposes // or null to say just use string value getbindingobjectfor: function(avar) { return 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() { return this._index < this._array.length; }, getnext: function() { return 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 return value of the getindexofresource method.
...in a content builder, it will return 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 returns true for the candrop method.
...And 3 more matches
Styling a Tree - Archive of obsolete content
these return 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 return a string of space-separated property names from these functions.
... getrowproperties : function(row){ return ''} getcolumnproperties : function(column,columnelement){ return ''} getcellproperties : function(row,column){ return ''} let's look at an example of changing a specific cell.
...And 3 more matches
panel - Archive of obsolete content
ArchiveMozillaXULpanel
returning 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() return type: no return value closes the popup immediately.
... moveto( x, y ) return type: no return 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 returns a calidatetime corresponding to the first date shown by the view enddate returns a calidatetime corresponding to the last date shown by the view.
...if an implementation returns true for this attribute, it must allow for any arbitrary set of dates to be displayed.
... hasdisjointdates returns 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 returns 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 returns 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 returns 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/return 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) { return 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, returns a whole number between 0 and x-1.
...cats.length returns 5, as there are 5 items in the array, but we don't want to get up to i = 5, as that would return 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 returning the value.
...the following will return 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 return information in http responses.
...every "view" function (a request handler) receives an httprequest object containing request information, and is required to return an httpresponse object with the formatted output (in this case a string).
... # return httpresponse return httpresponse('output string to return') 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 returns their sum.
... in javascript, that function could be written like this: function add(a, b) { return 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) { return 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 returns a clean-up function, which takes care of releasing the subscription.
... the subscribe() method must return 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 return () => subs = subs.filter(sub => sub !== handler) // return unsubscribe function } const set = (new_value) => { if (value === new_value) return // 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 return {...
...And 3 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
we've turned our static markup into a dynamic template ready to display the tasks from our component's state.
...to turn our component into a general purpose to-do editor we should allow the parent of this component to pass in the list of todos to edit.
...so let's turn the array into a prop.
...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 return 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 returns 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 return a pass or fail message depending on what its value is.
...And 3 more matches
Performance best practices for Firefox front-end engineers
return window.getcomputedstyle(node).display; }); return 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.
... return 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 return 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 return 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 returns an instance of the component manager service.
... webbrowser = do_createinstance(ns_webbrowser_contractid, &rv); if (ns_failed(rv)) return 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(), returning 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 returning.
...that returned 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() return true.
...And 3 more matches
AddonManager
the callbacks will be called just once but that may be before or after the method returns.
... note: the extensions.enabledscopes preference lets you configure which of these scopes are enabled; however, you can't turn off the profile scope.
... getstartupchanges() returns an array of add-on ids that changed for a given startup change type.
...And 3 more matches
DeferredTask.jsm
bool ispending(); return value returns 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 returned promise will be resolved.
... if the task is running and the timer is not armed, the returned 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 dosomethingwithfooandreturnittoo: 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 returns it.
... dosomethingwithfooandreturnittoo() is a method that munges the foo before returning it to main(), the main program.
... dosomethingwithfooandreturnittoo() leaks two refcounts.
...And 3 more matches
NSPR Poll Method
the arguments and return 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 return.
... return value if the poll method stores a nonzero value in *out_flags, the return value will be the value of in_flags.
...And 3 more matches
Nonblocking IO In NSPR
in nspr, a new socket returned 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 returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> inherits the blocking/nonblocking io mode of the listening socket and this cannot be changed.
... the socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> on a blocking, listening socket may be a recycled socket previously used in a <tt>pr_transmitfile()</tt> call.
...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 returned by pr_getlibraryname.
... returns if successful, returns a reference to an opaque prlibrary object.
... if the operation fails, returns null.
...And 3 more matches
PR_OpenSharedMemory
returns 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 returns 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 returned.
...And 3 more matches
PR_Poll
if this time expires without any i/o becoming ready, pr_poll returns zero.
... returns the function returns one of these values: if successful, the function returns a positive number indicating the number of prpolldesc structures in pds that have events.
... description this function returns 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
* returns 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; } } return 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"); return; } 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) { return 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) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { return 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"); return 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"); return 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); return 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
* returns 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; } } return 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"); return; } 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) { return 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
* returns 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; } } return 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"); return; } 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) { return 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 - return 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 returns general information about the pkcs #11 library.
... on return, 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 returns 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 returning false.
...otherwise the callback must return 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 returns, and at the end of the script.
... if the callback returns js_true, the js engine continues to execute the script.
... if the callback raises an exception using js_setpendingexception() and returns 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 returns a pointer to the beginning of the region.
...then it frees the region at p and returns a pointer to the new region.
...when p is not null, js_realloc(cx, p, 0) behaves like js_free(cx, p) and returns 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 return/throw ns_error_not_available if the annotation requested does not exist.
... the getter functions return only the value of the annotation (with the exception of the c++ getpageannotationbinary and getitemannotationbinary methods which return 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 returned 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 return 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 return value a preference object, or null if the preference does not exist getvalue() gets the value of a preference.
... returns a default value if the preference does not exist.
... return value the value of the preference or the given default value if preference does not exists.
...And 3 more matches
Components.lastResult
components.lastresult returns 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 return interesting 'success' codes.
...most interfaces only return 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 return value of exportfunction() to an object in the target scope.
... returns 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 return 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() returns 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 returned.
... return 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 returns the type of the relation.
... targetscount unsigned long returns the number of targets for this relation.
... methods gettarget() returns accessible relation target at the given index.
...And 3 more matches
nsIAppShellService
attributes attribute type description applicationprovidedhiddenwindow boolean return true if the application hidden window was provided by the application.
... hiddendomwindow nsidomwindow return the (singleton) application hidden window, automatically created and maintained by this appshellservice.
... hiddenwindow nsixulwindow return the (singleton) application hidden window, automatically created and maintained by this appshellservice.
...And 3 more matches
nsIAppStartup
return value true if a window was opened.
... getstartupinfo() returns a javascript object with events from startup and the timestamps indicating when they occurred.
... return value a javascript object with the following fields.
...And 3 more matches
nsIApplicationCache
gatherentries() returns a list of entries in the cache whose type matches one or more of the specified types.
...count on return, indicates how many matching entries were found.
... getmatchingnamespace() returns the most specific namespace matching a given key.
...And 3 more matches
nsICacheSession
if false, expired entries will be returned (useful for offline mode and clients, such as http, that can update the valid lifetime of cached content).
...return value returns whether any of the cache devices implied by the session storage policy are currently enabled for instantiation or not, depending on their existence.
...it returns a unique descriptor each time it is called, even if the same key is specified.
...And 3 more matches
nsIClipboard
return value returns true, if data is present and it matches the specified flavor.
... otherwise it returns false.
... return value returns true if kselectionclipboard is available.
...And 3 more matches
nsIDOMHTMLTimeRanges
methods end() returns 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 returned.
... return 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() returns from session storage the data corresponding to the specified key.
... domstring getitem( in domstring key ); parameters key the key for which data should be returned.
... return 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() returns from local storage the data corresponding to the specified key.
... domstring getitem( in domstring key ); parameters key the key for which data should be returned.
... return 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 returned 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 return the most appropriate type.
...return value a dom node.
...And 3 more matches
nsIDOMXULElement
returns an nsicontrollers object that additional controllers may be appended to so as to provide focus-specific actions for commands.
...returns the template builder's database, if it is an rdf template.
...returns the nsirdfresource corresponding to the element's ref or id attribute, if any.
...And 3 more matches
nsIDictionary
return value true if present, false if absent.
... void getkeys( out pruint32 count, [retval, array, size_is(count)] out string keys ); return value array of all keys, unsorted.
... return value the value associated with the specified key.
...And 3 more matches
nsIFileProtocolHandler
return value a reference to a new nsifile object.
... return value corresponding url string.
... return value corresponding url string.
...And 3 more matches
nsIJSID
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the following methods return 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.
...returns true if the jsid has been initialised.
... return 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 returned by a call to initlistbuild().
... return value true if the operation completed successfully.
...return 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) {return false;}, cyclecell: function(arow, acol) { }, getcelltext: function(arow, acol) { }, getsortstringforrow: function(ahdr) { return ""; }, isstring: function() {return true;}, getcellproperties: function(arow, acol, aprops) { }, getrowproperties: function(arow, aprops) { }, getimagesrc: function(arow, acol) {return null;}, getsortlongforrow: functio...
...n(ahdr) {return 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 return the string that the column should be sorted by.
... return value the string value that sorting will be done with.
...And 3 more matches
nsINavHistoryQuery
this allows place queries to be returned (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 return anything whose host name ends in domain.
... onlybookmarked boolean when set, returns only bookmarked items, when unset, returns 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 return value.) flags conversion option flags defined in nsidocumentencoder.
... return value the plain text conversion of the html specified in src.
... return 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 returning false from the corresponding callback method.
... return value true to allow the go back operation to proceed or false to cancel it.
... return 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() return the number of bytes currently available in the stream.
...return value the number of bytes.
... warning: if the data contains a null byte, then this method will return a truncated string.
...And 3 more matches
nsIScriptableUnicodeConverter
returns the converted string.
... after converting, finish should be called and its return value appended to this return value.
... acstring convertfromunicode( in astring asrc ); finish() returns 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 return value clone() nsisupportsarray clone(); parameters none.
... return 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 return value enumeratebackwards() [notxpcom, noscript] boolean enumeratebackwards( in nsisupportsarrayenumfunc afunc, in voidptr adata ); parameters afunc adata return value enumerateforwards() [notxpcom, noscript] boolean enumerateforwards( in nsisupportsarrayenumfunc afunc, in voidptr adata ); parameters afunc adata return 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 return the real non-proxied object.
...calls on object created with this flag will return immediately and you will lose all return information.
... ns_ok will be returned 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 returns true if the operating system supports windows 7 or later taskbar features; you can use this instead of in-place operating system version checking.
...return value an nsijumplistbuilder.
... return 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() returns the result for a given id.
... only one such result is returned and is always the result with that id associated with the active match.
... this method will return 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() returns a (possibly shared) cached nsizipreader for a zip inside another zip.
... return value the nsizipreader for the given zip file.
... getzip() returns 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 return.
... // return 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 return 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 returned 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 returned 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: return 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 "return false;".
... example: <form id="provider-form" onsubmit="return 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 returns true.
...And 3 more matches
Mail and RDF
if you ask it for #child nodes out of msgaccounts:/, it returns 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 returns.
...if asked about a folder along the #child arc, it will return resources for all subfolders in that folder.
...And 3 more matches
Standard OS Libraries
for finding out the values and types of arguments and returns 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 // return - 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, // return - 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 // return - 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 returns a new ctype object describing a new pointer data type.
... return value a ctype object describing the newly created data type.
... ptr ctype returns 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 return type of a native function (see library.declare()).
... type constructors these are functions that define new types, and thus return a ctype object.
... ctypes.functiontype(abi, returntype, argtype1 [, argtype2 ...]), which creates a new type describing a c function.
...And 3 more matches
Initialization and Destruction - Plugins
when the user returns 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 returns.
...*/ char* result = npn_useragent(); if (result == null) return 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 returns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror.
... names() return an array of strings giving the names of the identifiers bound by this environment.
... getvariable(name) return 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 return placeholder values.
...the text generation is disabled if the debugger has the allowwasmbinarysource property set, the "[wasm]" value will be returned 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 return 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 returns a new audiobuffer object instance.
... properties audiobuffer.samplerate read only returns a float representing the sample rate, in samples per second, of the pcm data stored in the buffer.
... audiobuffer.length read only returns an integer representing the length, in sample-frames, of the pcm data stored in the buffer.
...And 3 more matches
BlobBuilder - Web APIs
getblob() returns 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 returned in the blob.
... return 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 returns a cssstyledeclaration object on the first css rule in the document's first stylesheet.
... methods cssstyledeclaration.getpropertypriority() returns the optional priority, "important".
... cssstyledeclaration.getpropertyvalue() returns the property value given a property name.
...And 3 more matches
CacheStorage.match() - Web APIs
this method returns 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 returned by caches.keys()) until a response is returned.
... return value a promise that resolves to the matching response.
...And 3 more matches
CredentialsContainer.get() - Web APIs
the get() method of the credentialscontainer interface returns a promise to a single credential instance that matches the provided parameters.
...it can contain the following properties: password: a boolean indicating that returned credential instances should include user (as opposed to federated) credentials.
... federated: a federatedcredentialrequestoptions object containing requirements for returned federated credentials.
...And 3 more matches
DOMQuad - Web APIs
WebAPIDOMQuad
returning domquads lets getboxquads() return accurate information even when arbitrary 2d or 3d transforms are present.
... it has a handy bounds attribute returning a domrectreadonly for those cases where you just want an axis-aligned bounding rectangle.
... methods domquad.fromrect() returns 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() returns a filesystemfileentry or filesystemdirectoryentry representing it.
... if the item isn't a file, null is returned.
... return 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 return 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 returns an object of type document (e.g., the ownerdocument property of an element returns 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 returned 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() returns the first matching element node within the node's subtree.
... if no matching node is found, null is returned.
... queryselectorall() returns 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
WebAPIElementclosest
will return itself or the matching ancestor.
... if no such element exists, it returns null.
... ex: p:hover, .toto + q return 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 returns the value of a specified attribute on the element.
... if the given attribute does not exist, the value returned 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) return 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 returns 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 returned.
... return value the first descendant element of baseelement which matches the specified group of selectors.
...And 3 more matches
Event - Web APIs
WebAPIEvent
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, returning it to the caller.
...setting its value to true before returning from an event handler prevents propagation of the event.
...(mozilla-specific.) event.returnvalue 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 returning of a response, such as streaming and caching.
...for get requests it tries to return a match in the cache, and falls back to the network.
... if (event.request.method != 'get') return; // prevent the default, and handle the request ourselves.
...And 3 more matches
FileSystemDirectoryEntry.createReader() - Web APIs
the filesystemdirectoryentry interface's method createreader() returns a filesystemdirectoryreader object which can be used to read the entries in the directory.
... return value a filesystemdirectoryreader object which can be used to read the directory's entries.
... example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array.
...And 3 more matches
FormData - Web APIs
WebAPIFormData
formdata.entries() returns an iterator allowing to go through all key/value pairs contained in this object.
... formdata.get() returns the first value associated with a given key from within a formdata object.
... formdata.getall() returns 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 returned 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 returns a gamepad object.
... the navigator.getgamepads() method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be returned 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() returns a canvascapturemediastream that is a real-time video capture of the surface of the canvas.
... htmlcanvaselement.getcontext() returns a drawing context on the canvas, or null if the context id is not supported.
...calling getcontext with "2d" returns a canvasrenderingcontext2d object, whereas calling it with "webgl" (or "experimental-webgl") returns a webglrenderingcontext object.
...And 3 more matches
HTMLSlotElement.assignedElements() - Web APIs
the assignedelements() property of the htmlslotelement interface returns a sequence of the elements assigned to this slot (and no other nodes).
... if the flatten option is set to true, it also returns the assigned elements of any other slots that are descendants of this slot.
... if no assigned nodes are found, it returns the slot's fallback content.
...And 3 more matches
HTMLTableElement - Web APIs
htmltableelement.rowsread only returns 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 returns a live htmlcollection containing all the <tbody> of the element.
... htmltableelement.createthead() returns an htmlelement representing the first <thead> that is a child of the element.
...And 3 more matches
HTMLTableRowElement - Web APIs
htmltablerowelement.cells read only returns a live htmlcollection containing the cells in the row.
... htmltablerowelement.rowindex read only returns a long value which gives the logical position of the row within the entire table.
... if the row is not part of a table, returns -1.
...And 3 more matches
IdleDeadline.timeRemaining() - Web APIs
the timeremaining() method on the idledeadline interface returns 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 return.
...if there isn't, the callback can just return immediately, or look for other work to do with the remaining time.
...And 3 more matches
KeyboardLayoutMap - Web APIs
properties keyboardlayoutmap.entries read only returns 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 returns a new array iterator object that contains the keys for each index in the array.
... keyboardlayoutmap.size read only returns the number of elements in the keyboardlayoutmap object.
...And 3 more matches
LockedFile - Web APIs
returns a filerequest.
...returns a filerequest object.
...returns a filerequest object.
...And 3 more matches
MediaKeySession - Web APIs
properties mediakeysession.closed read only returns a promise signaling when a mediakeysession closes.
... methods mediakeysession.close() returns 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() returns 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 returns a promise that resolves.
... navigationpreloadmanager.disable() disables navigation preloading and returns a promise that resolves.
... navigationpreloadmanager.setheadervalue() sets the value of the service-worker-navigation-preload header and returns an empty promise.
...And 3 more matches
Navigator.onLine - Web APIs
returns the online status of the browser.
... the property returns a boolean value, with true meaning online and false meaning offline.
...for example, the property should return false when users click links soon after they lose internet connection.
...And 3 more matches
NetworkInformation - Web APIs
networkinformation.downlink read only returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.
... networkinformation.downlinkmax read only returns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology.
... networkinformation.effectivetype read only returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'.
...And 3 more matches
Node.getRootNode() - Web APIs
WebAPINodegetRootNode
the getrootnode() method of the node interface returns 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 returned (false, the default), or a root node beyond shadow root (true).
... returns an object inheriting from node.
...And 3 more matches
Node.textContent - Web APIs
WebAPINodetextContent
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 returns null.
... if the node is a cdata section, comment, processing instruction, or text node, textcontent returns the text inside the node, i.e., the node.nodevalue.
... for other node types, textcontent returns 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 returns 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 return values are: constant description nodefilter.filter_accept value returned by the nodefilter.acceptnode() method when a node should be accepted.
... nodefilter.filter_reject value to be returned by the nodefilter.acceptnode() method when a node should be rejected.
...And 3 more matches
ParentNode - Web APIs
properties parentnode.childelementcount read only returns the number of children of this parentnode which are elements.
... parentnode.children read only returns 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 returns 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 returns the high resolution timestamp of the start time of the performance measurement.
... performance.getentries() returns a list of performanceentry objects based on the given filter.
... performance.getentriesbyname() returns 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 returns "navigation".
... performanceentry.name read only returns the document's address.
... performanceentry.starttime read only returns a domhighrestimestamp with a value of "0".
...And 3 more matches
RTCPeerConnection.createOffer() - Web APIs
the return 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 returned offer to have different credentials than those already in place.
... if you then apply the returned offer, ice will restart.
...And 3 more matches
RTCPeerConnection.getStats() - Web APIs
the rtcpeerconnection method getstats() returns a promise which resolves with data providing statistics about either the overall connection or about the specified mediastreamtrack.
... return value a promise which resolves with an rtcstatsreport object providing connection statistics.
... exceptions this method does not throw exceptions; instead, it rejects the returned 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 returns a javascript promise that resolves to an rtcidentityassertion which contains a domstring identifying the remote peer.
... note: the promise returned 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 returned by setremotedescription() will be rejected.
...And 3 more matches
RTCRtpReceiver.getCapabilities() static function - Web APIs
the static function rtcrtpreceiver.getcapabilities() returns an rtcrtpcapabilities object describing the codecs and capabilities supported by rtcrtpreceivers on the current device.
... return 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 returned value is null.
...And 3 more matches
RTCRtpSender.getCapabilities() static function - Web APIs
the static function rtcrtpsender.getcapabilities() returns an rtcrtpcapabilities object describing the codecs and capabilities supported by the rtcrtpsender.
... return 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 returned 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 returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
...the method will return 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 return 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 returns a readablestreamdefaultreader object instance.
... return 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 return 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 returns a promise providing access to the next chunk in the stream's internal queue.
... return 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 return 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 returns an svganimatedlength corresponding to the x attribute of the given <rect> element.
... svgrectelement.y read only returns an svganimatedlength corresponding to the y attribute of the given <rect> element.
... svgrectelement.width read only returns 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 returns a serviceworker object if its state is activated (the same object returned by serviceworkerregistration.active).
... this property returns null during a force-refresh request (shift + refresh) or if there is no active worker.
...it returns 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 returns the applicationcache object for the worker (see using the application cache).
... properties inherited from workerglobalscope workerglobalscope.self returns an object reference to the dedicatedworkerglobalscope object itself.
... workerglobalscope.console read only returns the console associated with the worker.
...And 3 more matches
SpeechRecognitionAlternative.transcript - Web APIs
the transcript read-only property of the speechrecognitionresult interface returns a string containing the transcript of the recognised word(s).
... syntax var mytranscript = speechrecognitionalternativeinstance.transcript; returns a domstring.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
SpeechRecognitionAlternative - Web APIs
properties speechrecognitionalternative.transcript read only returns a string containing the transcript of the recognised word.
... speechrecognitionalternative.confidence read only returns a numeric estimate of how confident the speech recognition system is that the recognition is correct.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns 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 returns a speechrecognitionresultlist object representing all the speech recognition results for the current session.
... specifically this object will contain all final results that have been returned, followed by the current best hypothesis for all interim results.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns 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 returned; if not, then this result is an interim result, and may be updated later on.
... syntax var myisfinal = speechrecognitionresultinstance.isfinal; returns a boolean.
... examples recognition.onresult = function(event) { // the speechrecognitionevent results property returns 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 returns 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; returns a number.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns 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 returned; if not, then this result is an interim result, and may be updated later on.
... speechrecognitionresult.length read only returns 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 returns 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 returns the length of the "array" — the number of speechrecognitionresult objects in the list.
... syntax var mylength = speechrecognitionresultlistinstance.length; returns a number.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
...And 3 more matches
StaticRange - Web APIs
staticrange.collapsed read only returns 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 returns the dom node which contains the ending point of the range.
... staticrange.endoffset read only returns 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 returns a domstring representing the location of the stylesheet.
... stylesheet.media read only returns a medialist representing the intended destination medium for style information.
... stylesheet.ownernode read only returns a node associating this style sheet with the current document.
...And 3 more matches
SubtleCrypto.decrypt() - Web APIs
it returns a promise which will be fulfilled with the decrypted data (also known as "plaintext").
... return value result is a promise that fulfills with an arraybuffer containing the plaintext.
... function decryptmessage(privatekey, ciphertext) { return 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 returns a promise which will be fulfilled with the encrypted data (also known as "ciphertext").
... return 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(); return enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode.
...And 3 more matches
SubtleCrypto.verify() - Web APIs
it returns a promise which will be fulfilled with a boolean value indicating whether the signature is valid.
... return 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(); return 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 returns a new trackdefault object.
... properties trackdefault.type read only returns the type of track that this sourcebuffer's media segment data relates to (i.e.
... audio, video, or text track.) trackdefault.bytestreamtrackid read only returns the id of the specific track that the sourcebuffer should apply to.
...And 3 more matches
UIEvent.layerX - Web APIs
WebAPIUIEventlayerX
the uievent.layerx read-only property returns the horizontal coordinate of the event relative to the current layer.
... this property takes scrolling of the page into account and returns a value relative to the whole of the document unless the event occurs inside a positioned element, where the returned 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 return 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 return layerx/layery values that are relative to the top-left corner of this positioned element.
...And 3 more matches
UIEvent.layerY - Web APIs
WebAPIUIEventlayerY
the uievent.layery read-only property returns the vertical coordinate of the event relative to the current layer.
... this property takes scrolling of the page into account, and returns a value relative to the whole of the document, unless the event occurs inside a positioned element, where the returned 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 return 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 return 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 returns the alternate setting number of this interface.
... usbalternateinterface.interfaceclassread only returns the class of this interface.
... usbalternateinterface.interfacesubclassread only returns 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); return; } 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); return; } 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); return; } 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() returns all performance entries in the performance timeline.
... performance.getentriesbyname(name, entrytype) returns 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) returns 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 returns a webglactiveinfo object containing size, type, and name of a uniform attribute.
...this value is an index 0 to n - 1 as returned by gl.getprogramparameter(program, gl.active_uniforms).
... return 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 returned by geterror).
... instead of: function compileonce(gl, shader) { if (shader.compiled) return; 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) return; 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
WebAPIWindowprompt
return 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 returned.
... if the user clicks ok without entering any text, an empty string is returned.
...And 3 more matches
WritableStream.getWriter() - Web APIs
the getwriter() method of the writablestream interface returns a new instance of writablestreamdefaultwriter and locks the stream to that instance.
... return value a writablestreamdefaultwriter object instance.
...inside this function it calls the stream's getwriter() method, which returns 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 returns a promise that resolves to indicate the success or failure of the write operation.
... return 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 returns an instance of writablestreamdefaultwriter.
...And 3 more matches
XMLHttpRequest.getResponseHeader() - Web APIs
the xmlhttprequest method getresponseheader() returns 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 returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space.
... the getresponseheader() method returns the value as a utf byte sequence.
...And 3 more matches
XRSession - Web APIs
WebAPIXRSession
environmentblendmode read only returns 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 returns 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 returned by a previous call to requestanimationframe().
...And 3 more matches
XRWebGLLayer - Web APIs
constructor new xrwebgllayer() creates and returns a new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context.
... framebuffer read only returns a webglframebuffer suitable for passing into the bindframebuffer() method.
... framebufferwidth read only returns the width of the xrwebgllayer's framebuffer.
...And 3 more matches
ARIA: textbox role - Accessibility
the default is a single line input, in which return 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 return 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 return 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 returns, focus should return 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 returns, 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="return 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 returns false.
... and the and operator is used for combining multiple media features together into a single media query, requiring each chained feature to return true in order for the query to be true.
... not the not operator is used to negate a media query, returning true if the query would otherwise return false.
...And 3 more matches
<angle> - CSS: Cascading Style Sheets
WebCSSangle
the <angle> css data type represents an angle value expressed in degrees, gradians, radians, or turns.
...for example, 90deg equals -270deg, and 1turn equals 4turn.
... 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 – returns the server response as a string of text httprequest.responsexml – returns the response as an xmldocument object you can traverse with javascript dom functions note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true).
... <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'); return 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 return 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){ return document.getelementbyid(aid).contentdocument; } else { // ie return 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
return value undefined.
...(see this example, below.) foreach() executes the callback function once for each array element; unlike map() or reduce() it always returns 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 returning a truthy value to determine if further iteration is required.
...And 3 more matches
Array.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns a string representing the elements of the array.
... return value a string representing the elements of the array.
...if len is zero, return 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 return any fractional digits).
... instance methods bigint.prototype.tolocalestring() returns a string with a language-sensitive representation of this number.
... bigint.prototype.tostring() returns a string representing the specified object in the specified radix (base).
...And 3 more matches
Date.prototype.toLocaleDateString() - JavaScript
the tolocaledatestring() method returns 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 returned are entirely implementation dependent.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.
...And 3 more matches
Date.prototype.toLocaleTimeString() - JavaScript
the tolocaletimestring() method returns 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 returned are entirely implementation dependent.
...in implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.
...And 3 more matches
Intl.Collator.supportedLocalesOf() - JavaScript
the intl.collator.supportedlocalesof() method returns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.
... return 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 returns 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 returns 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.
... return 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 returns 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 returns 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.
... return 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 returns 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 returns 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.
... return 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 returns 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 returns 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.
... return 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 returns 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 returns 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.
... return 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 returns 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 returns 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.
... return 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 returns an array with a subset of the language tags provided in locales.
...And 3 more matches
Math.log2() - JavaScript
the math.log2() function returns 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.
... return value the base 2 logarithm of the given number.
... if the number is negative, nan is returned.
...And 3 more matches
Math.max() - JavaScript
the math.max() function returns the largest of the zero or more numbers given as input parameters.
... return value the largest of the given numbers.
... if at least one of the arguments cannot be converted to a number, nan is returned.
...And 3 more matches
Number.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns 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 returned are entirely implementation dependent.
... return value a string with a language-sensitive representation of the given number.
...And 3 more matches
Object.assign() - JavaScript
it returns the target object.
... syntax object.assign(target, ...sources) parameters target the target object — what to apply the sources’ properties to, which is returned after it is modified.
... return 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, returning the object.
...the function's return value will be used as the value of the property.
... return value the object that was passed to the function.
...And 3 more matches
Object.getOwnPropertyNames() - JavaScript
the object.getownpropertynames() method returns 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 returned.
... return 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 returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
... return value a boolean indicating whether or not the object has the specified property as own property.
... note hasownproperty returns true even if the value of the property is null or undefined.
...And 3 more matches
Object.setPrototypeOf() - JavaScript
return value the specified object.
...* returns @object (if it was a primitive value it will transformed into an object).
...* returns the function.
...And 3 more matches
Object.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of the specified object.
... syntax object.valueof() return value the primitive value of the specified object.
...every built-in core object overrides this method to return an appropriate value.
...And 3 more matches
Promise() constructor - JavaScript
the executor has no meaningful return value.
... resolutionfunc(value) // call on fulfilled rejectionfunc(reason) // call on rejected the returned value can be another promise object, in which case the promise gets dynamically inserted into the chain.
... return value promiseobj when called via new, the promise constructor returns a promise object.
...And 3 more matches
Reflect.defineProperty() - JavaScript
the static reflect.defineproperty() method is like object.defineproperty() but returns a boolean.
... return value a boolean indicating whether or not the property was successfully defined.
... one key difference: object.defineproperty returns 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 returns a string created by using the specified sequence of code points.
... return value a string created by using the specified sequence of code points.
... description this method returns a string (and not a string object).
...And 3 more matches
String.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns the index within the calling string object of the last occurrence of the specified value, searching backwards from fromindex.
... returns -1 if the value is not found.
...if searchvalue is an empty string, then fromindex is returned.
...And 3 more matches
WeakMap.prototype.get() - JavaScript
the get() method returns a specified element from a weakmap object.
...the key of the element to return from the weakmap object.
... return 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 returns the value of the last operand.
... one or more expressions, the last of which is returned 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 returned to console (i.e., 4).
...And 3 more matches
Operator precedence - JavaScript
this is because the assignment operator returns the value that is assigned.
...then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.
... code output function echo(name, num) { console.log("evaluating the " + name + " side"); return 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"); return 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 return undefined.
... to return any other value, the function must have a return statement that specifies the value to return.
...typeof foo is ${typeof foo}`); if (false) { function foo(){ return 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 returns 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 return.
... object1 the first object to consider returning.
...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 returns the resulting node-set.
... node-set (optional) an expression pointing to a node-set in the external document that should be returned.
... returns 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 returns a reference to the clone.
...note that the function's closure will be exported, too: // content-script.js var salutation = "hello, "; function greetme(user) { return 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 return 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 return 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) { return 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 return 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) { return att.value; } return 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."); return; } 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; return true; } for (var nidx = 0; nidx < vmimetypes.length; nidx++) { odicts[(vmimetypes[nidx]).tostring()] = fcompiler; } return 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) { return; } /* this function takes as argument a plain text (in this case, a code written in c) and returns 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 () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.example.com/foo.xpi" iconurl="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="return 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 () { return 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.
... return false; this last part is the most important - the install function must return 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); return 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 return value, and making changes both before and after the original method is called.
... * @optional @default document * * @returns {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 returns 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 returns true, we have found the right listener and we are done.
...if any of those steps fails, the function returns 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 returns it if present.
... then, nsrulenode::getstyledata checks for a cached struct or a dependent bit on the rule node, and returns 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)returns data to jetpack from the clipboard.
... if flavor is provided, the data is returned in that format.
... flavorreturns 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)returns data to jetpack from the clipboard.
... if flavor is provided, the data is returned in that format.
... flavorreturns 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)returns data to jetpack from the clipboard.
... if flavor is provided, the data is returned in that format.
... flavorreturns data to jetpack from the clipboard.
...And 2 more matches
LIR - Archive of obsolete content
category op code code name return 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 return an int 7 retq void 64 bit return a quad 8 retd void return 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 returns void 34 calli integer call subroutine that returns an int 35 callq quad 64 bit call subroutine that returns a quad 36 calld double call subroutine that returns 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
return value nodelist - the return value of getanonymousnodes is a nodelist that represents the children of an element after insertion points from its own binding have been applied.
... return value element - the return value of getanonymouselementbyattribute is an anonymous descendant of the given element with matching attribute name and value.
... return value element - the return value of getbindingparent is the element responsible for the given anonymous node.
...And 2 more matches
modDateChanged - Archive of obsolete content
summary returns whether file has been modified since a certain date.
... returns 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 returned 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
returns if the versions are the same, this method returns 0.
... if this version object represents a smaller (earlier) version than that represented by the version parameter, this method returns a negative number.
... otherwise, it returns a positive number.
...And 2 more matches
cancelInstall - Archive of obsolete content
returns an integer error code.
... the optional argument is an error code that can be returned to the triggering page.
... for most purposes, it's recommended that one of the standard return codes be used.
...And 2 more matches
Installer Script - Archive of obsolete content
return(false); 16.
... return(true); 18.
... logcomment("adddirectory() returned: " + err); 33.
...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) { return i; } } return -1; } function find_cell_up(current) { var row = get_index_within_parent(current); var arsiblings = current.parentnode.childnodes; return row == 0 ?
... null : arsiblings[row - 1]; } function find_cell_down(current) { var row = get_index_within_parent(current); var arsiblings = current.parentnode.childnodes; return 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; return column = 0 ?
...And 2 more matches
Working With Directories - Archive of obsolete content
note that nsifile.append() modifies the file object, rather than returning a new one.
...this method returns true if a file object returned by nsiscriptableio.getfile() refers to a directory, and false otherwise.
...it returns an enumeration which can be iterated over.
...And 2 more matches
Getting File Information - Archive of obsolete content
it is convenient to pass the returned time to the date constructor.
...the following four methods return true or false: nsifile.isreadable() - returns true if the file can be read from.
... nsifile.iswritable() - returns 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() return type: no return value closes the notification or findbar and removes it from its enclosing notificationbox or findbar.
... open( mode ) return type: no return value opens the findbar using the specified mode, which should be one of find_normal, find_typeahead, or find_links.
... onfindagaincommand( findprevious ) return type: no return 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 return the value that should be treated as the value of that property.
...<property name="size" onget="return 77;" onset="alert('changed to:'+val);"/> this property will always return 77 when retrieved.
...the script calculates the value and returns it.
...And 2 more matches
Manipulating Lists - Archive of obsolete content
the former returns the index of the selected item while the latter returns the selected element.
...if no item is selected, selectedindex will return -1, while selecteditem will return null.
...it also has a selectedindex function which will return 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() return type: no return value accepts the dialog and closes it, similar to pressing the ok button.
... canceldialog() return type: no return value cancels the dialog and closes it, similar to pressing the cancel button.
... centerwindowonscreen() return type: no return 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="return myfunction(event);"/> </window> readonly type: boolean if set to true, then the user cannot change the value of the element.
... properties defaultvalue (readonly) returns the default value of the preference.
... if the preference has no default value, this property returns 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 returns 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 return type: element adds a custom toolbar to the toolbox with the given name.
...the method returns the dom element for the created toolbar.
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
return 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 returns 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 returned by the method.
... returns true if the method was successfully invoked, otherwise false.
... if the method was invoked successfully, any return 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 returned by the default method.
... returns true if the default method was successfully invoked, otherwise false.
... if the default method was invoked successfully, any return 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 returns this value (see description below).
... returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
...And 2 more matches
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
if you haven't you can return 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) return nperr_incompatible_version_error; err = callnpn_getvalueproc(gnetscapefuncs.getvalue, null, npnvtoolkit, (void *)&toolkit); if (err != nperr_no_error || toolkit != npnvgtk2) return nperr_incompatible_version_error; [ the rest of initialization ] return 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 return an error.
...And 2 more matches
Accessing XML children - Archive of obsolete content
in this case, accessing foo.bar will return an xml list object, of all child elements of the type "bar".
...e4x behaves no differently when returning these properties.
...var element = <foo> <bar baz="1">red</bar> <bar baz="2">blue</bar> </foo>; var list = element.bar; list.length(); // returns 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 returns a qname object (qualified name).
...the localname property returns the name of the element, without any namespace prefix.
... the uri property returns the uri of the namespace that the element is in.
...And 2 more matches
GetObject - Archive of obsolete content
the getobject function returns a reference to an automation object from a file.
...assign the object returned by getobject to the object variable.
...if pathname is a zero-length string (""), getobject returns a new object instance of the specified type.
...And 2 more matches
VBArray - Archive of obsolete content
methods vbarray.dimensions returns the number of dimensions in a vbarray.
... vbarray.getitem returns the item at the specified location.
... vbarray.lbound returns 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 returned the last element added to an array.
... under javascript 1.3, push returns the new length of the array.
... array.prototype.slice(): in javascript 1.2, the splice method returned 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() returns a property descriptor for a named property on an object.
... bug 505587 object.keys() returns an array of all enumerable properties on an object.
... bug 307791 object.getownpropertynames() returns an array of all enumerable and non-enumerable properties on an object.
...And 2 more matches
Object.prototype.watch() - Archive of obsolete content
return 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 return value in that property.
... a watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning 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 returns an error.
... getwrappedexceptiontype instance method getwrappedexceptiontype returns the int mapping of the type of the wrappedexception object.
... declaration public object getwrappedexception() description getwrappedexception() returns 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) { return (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) { return (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)); return 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 return a string containing the type, extension list, and type description separated by colons.
... caution: gecko caches the values returned 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 returned 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 return or enter.
... you can then press enter/return 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/return 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 return or enter.
... you can then press enter/return 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/return 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) { return 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 returns a random number.
...returning 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 return values articles.
... functions 3 in this task, you return 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 returns the result.
...And 2 more matches
Manipulating documents - Learn web development
using methods available on this object you can do things like return 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 return 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 returns 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 returns one of the items stored inside the array at random.
... placing the event handler and incomplete function: now return to the raw text file.
...And 2 more matches
Solve common problems in your JavaScript code - Learn web development
not inside any functions), or return the value from the function.
... running code after a return statement remember also that when you return from a function, the javascript interpreter exits the function — no code after the return 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 return 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 return 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 returning 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 returns 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() returns the value of the object it is called on.
...you can check this by entering the following in the console: person2.__proto__ this will return the person1 object.
... for example, try these commands in the console: person1.constructor person2.constructor these should both return 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() { return { key: value } } you'll note that the data property is a function.
...this will return 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 returns a label field.
... your component object should now look something like this: export default { methods: { onsubmit() { console.log("form submitted"); } }, data() { return { 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() { return { 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() { return !!document.createelement('canvas').getcontext; } if(supports_canvas()) { ...
... } method on element return 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 returns.
...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 return 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
MozillaGeckoChromeAPIBrowser APIUsing
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 return a boolean defining whether backward/forward navigation is possible at this point in the history.
... if true is returned, the relevant button is disabled, and if false is returned, the relevant button is enabled.
...And 2 more matches
Infallible memory allocation
these are memory allocation routines that never return null; that is, they always successfully return the requested block of memory.
... this is in contrast to a traditional, fallible memory allocator that can return 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, return to your code.
...And 2 more matches
FileUtils.jsm
return value returns a nsifile object for the file specified.
... return value returns a nsifile object for the location specified.
... modeflags optional file open flags (see constants above) return value returns 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 returns the set of parameters that initialized the firefox accounts oauth flow.
... constructor fxaccountsoauthclient() creates and returns 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 returned from client registration.
...And 2 more matches
Memory reporting
size_t mystring::sizeofexcludingthis(mozilla::mallocsizeof amallocsizeof) const { return amallocsizeof(mbuffer); } size_t mystring::sizeofincludingthis(mozilla::mallocsizeof amallocsizeof) const { return 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.
... return 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 { return ...
...And 2 more matches
PR_AcceptRead
on return, *acceptedsock points to the prfiledesc object for the newly connected socket.
... this parameter is valid only if the function return does not indicate failure.
...on return, 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 returned by pr_poll().
... returns if the nonblocking connect has successfully completed, pr_connectcontinue returns pr_success.
... if pr_connectcontinue() returns 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 returned value.
... the enumeration is complete when a value of null is returned.
... addrinfo a pointer to a praddrinfo structure returned 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 returned value.
... the enumeration is complete when a value of zero is returned.
... returns the function returns one of the following values: if successful, the function returns the value you should specify in the enumindex parameter for the next call of the enumerator.
...And 2 more matches
PR_PopIOLayer
returns the function returns 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 returns null with the error code pr_invalid_argument_error.
...if the object to be removed is found, pr_popiolayer returns a pointer to the removed object the object then becomes the responsibility of the caller.
...And 2 more matches
PR_ReadDir
returns a pointer to the next entry in the directory.
... description pr_readdir returns 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 returned prdirentry structure is managed by nspr.
...And 2 more matches
PR_WaitSemaphore
returns 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 returned from a call to pr_opensemaphore.
... returns 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 returned value.
...this gives a return value similar to that of ecvt, except that trailing zeros are suppressed.
...this gives a return value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative.
...And 2 more matches
PR_strtod
returns 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 returned.
... if the answer would underflow, a properly signed 0 is returned.
...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 returns.
... additional documentation in pk11pub.h: the caller of pk11_derencodepublickey should free the returned secitem with a secitem_freeitem(..., pr_true) call.
... pk11_readrawattribute allocates the buffer for returning 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 returns them as der bytes.
... if no such certificates can be found, returns secsuccess and sets *results to null.
... if a failure is encountered while fetching any of the matching certificates, secfailure is returned and *results will be null.
...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 returned should include all the pkcs 2.0 function calls.
... if you don't implement a function, you should still provide a stub that returns ckr_function_not_supported.
...if a token has been removed during a session, c_getsessioninfo should return 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 returns 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 returns 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 returns information about the database configuration for the modules.
...And 2 more matches
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
if any of these databases already exist in a specified directory, modutil returns 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 returns 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 returns 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){return 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 return a scope object that we use in later calls.
...$ java runscript3 "function f(a) { return a; }" x is not defined.
...And 2 more matches
Rhino shell
environment returns 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 return the exit status of the process.
...And 2 more matches
Exact Stack Rooting
bool hello(jscontext *cx, handleobject foo) { return hello(cx, foo); } .....
... warning: never give a function a js::handlet return type: this can easily lead to a js::handlet outliving its js::rootedt's lifetime.
... bool returnfoo(jscontext *cx, mutablehandlestring out) { out.set(js_newstringcopyz(cx, "foo")); return bool(out); } size_t getlengthfoo(jscontext *cx) { rootedstring s(cx); if (returnfoo(cx, &s)) return js_getstringlength(s); return size_t(-1); } all methods in the js-api that return gcpointers have been changed to this out-param style.
...And 2 more matches
JS::AutoIdArray
methods method description bool operator!() const return true if this has no owned array.
... jsid operator[](size_t i) const return a jsid in specified index of the owned array.
... size_t length() const return the length of the owned array.
...And 2 more matches
JS::CurrentGlobalOrNull
this article covers features introduced in spidermonkey 31 return 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 return the global object.
... description js::currentglobalornull() returns the global object for whatever function is currently running on the context.
...And 2 more matches
JS::PersistentRooted
added in spidermonkey 38 t& get() returns ptr.
... const t& get() const operator const t&() const const t& operator->() const t* address() returns a pointer to ptr.
... persistentval.ref() = args.get(0); // or // *persistentval = args.get(0); // [spidermonkey 38] // persistentval = args.get(0); args.rval().setundefined(); return 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 return-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 return value.
... on success, the callback must set js::callargs::rval() or call js_set_rval (at least once) and return true.
...And 2 more matches
JSObjectOps.lookupProperty
description look for id in obj and its prototype chain, returning js_false on error or exception, js_true on success.
... on success, return null in *propp if id was not found.
... if id was found, return the first object searching from obj along its prototype chain in which id names a direct property in *objp, and return a non-null, opaque property pointer in *propp.
...And 2 more matches
JS_CallFunction
on success, *rval receives the return value from the function call.
...if js engine fails to get the function, it returns false.
... rval is a pointer to a variable that will hold the function's return 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)) return js_false; /* allocate.
... */ char *dst = (char *) js_malloc(cx, dstlen); if (dst == null) return js_false; /* convert characters to bytes.
...And 2 more matches
JS_EncodeString
if js_cstringsareutf8 is true, then the returned string of js_encodestring is utf-8, and the conversion is lossless.
... the array returned 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 return a corrupted copy of the contents of the string.
...And 2 more matches
JS_GetGlobalForCompartmentOrNull
this article covers features introduced in spidermonkey 17 return 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 return the global object.
... c jscompartment * the compartment for which to return the global object.
...And 2 more matches
JS_GetGlobalForScopeChain
this article covers features introduced in spidermonkey 1.8.5 returns 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 return the global object.
... description js_getglobalforscopechain() returns 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 returns true.
...for many objects, including objects of standard classes such as object and array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp.
...for many properties, the getter does nothing and returns 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 returned string is utf-8, and the conversion is lossless.
...on success, the return value is a pointer to the char array, which is null-terminated.
... on failure, js_getstringbytes returns a pointer to a null-terminated empty string; js_getstringbytesz returns null.
...And 2 more matches
JS_PropertyStub
it behaves exactly like a property callback that accepts the default property behavior: it does nothing and returns true.
...it behaves exactly like a property callback that accepts the default property behavior: it does nothing and returns true.
...it behaves exactly like a property callback that accepts the default property behavior: it does nothing and returns true.
...And 2 more matches
JS_SetContextCallback
for future compatibility the callback must do nothing and return true if any other value is passed.
...if the callback returns js_false, the instance will be destroyed and js_newcontext returns null.
...the callback may perform its own cleanup and must always return 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 return value.
... if null or an empty list is passed, events for all apps are returned.
... since the timestamp of the earliest event you want returned.
...And 2 more matches
extISessionStorage
return 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 return 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 return 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 return a new object implementing nsiwindowsregkey.
...this method returns an integer indicating the data type of the value.
... function readregistryvalue(wrk, value) { switch (wrk.getvaluetype(value)) { case wrk.type_string: return wrk.readstringvalue(value); case wrk.type_binary: return wrk.readbinaryvalue(value); case wrk.type_int: return wrk.readintvalue(value); case wrk.type_int64: return wrk.readint64value(value); } // unknown type return 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) { return minner->init(auri); } ns_imethod geturi(char* *auri) { return minner->geturi(auri); } // etc., for each method in nsirdfdatasource!
...aresult) return 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())) { return minner->queryinterface(aiid, aresult); } else { *aresult = nsnull; return ns_nointerface; } ns_ad...
...dref(ns_static_cast(nsisupports*, aresult)); return 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 returns 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.
... returns 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 returned 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 return code (that is, an nsresult value) indicates the success or failure of an operation, returning 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.returncodecomponents.stackcomponents.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack.
...it returns 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 returned by an xpcom function; these are typically error or status codes.
... for a list of defined result values, see error codes returned by mozilla apis.
...as a result, it was possible for code to misuse it, such as returning an nsresult value from a function whose signature indicates it returns a boolean.
...And 2 more matches
amIInstallTrigger
return value install() starts a new installation of a set of add-ons.
... return value true if the installations were successfully started.
... return 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 returned request will have aobserver as the observer.
... aobserver will be notified synchronously (before the clone call returns) with all the notifications that have already been dispatched for this image load.
... imgirequest clone( in imgidecoderobserver aobserver ); parameters aobserver return value decrementanimationconsumers() tell the image it can forget about a request that the image animate.
...And 2 more matches
nsIAbCard
return value the value of the attribute asked for.
... return value true if the cards are the same.
... converttobase64encodedxml() string converttobase64encodedxml() return value converttoxmlprintdata() astring converttoxmlprintdata() return value converttoescapedvcard() string converttoescapedvcard() return value generatename() generate a name from the card for display purposes.
...And 2 more matches
nsIAutoCompleteInput
methods getsearchat() returns 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 returned.
... return value the name of the specified object.
...And 2 more matches
nsICacheEntryDescriptor
return value returns the string value containing the meta data for the provided key.
...the returned stream may implement nsiseekablestream.
... return value returns blocking, unbuffered input stream.
...And 2 more matches
nsICacheService
storagepolicy limits the storage policy for all entries accessed via the returned session.
... as a result, devices excluded by the storage policy will not be searched when opening entries from the returned session.
... return value returns 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 return 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 return 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() ...
...return value missing description exceptions thrown missing exception missing description getcharptrproperty() string getcharptrproperty( in string propertyname ); parameters propertyname missing description return 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 return more than one resolved ip address, the record acts like an enumerator, allowing the caller to easily step through the list of ip addresses.
... return value the value of the next ip address.
... getnextaddrasstring() this function returns the value of the next ip address as a string and increments the internal address iterator.
...And 2 more matches
nsIDNSService
speculative requests return errors if prefetching is disabled by configuration.
... resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses will be returned by asyncresolve() and resolve().
... return 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 returned.
... 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 return value native code only!duplicateprivatedata void duplicateprivatedata(); parameters none.
... return value getpreventdefault() note: use the defaultprevented attribute instead.
...And 2 more matches
nsIDOMOfflineResourceList
mozhasitem returns a boolean value indicating whether or not the specified uri represents a resource that's in the application cache's list.
... return value true if the resource is in the list, otherwise false.
... mozitem returns the uri of the item at the specific offset into the list of cached resources.
...And 2 more matches
nsIDOMStorageManager
getlocalstorageforprincipal() returns the instance of the localstorage object for auri's origin.
...nsidomstorage getlocalstorageforprincipal( nsiprincipal aprincipal, domstring adocumenturi ); parameters aprincipal the principal for which to return the local storage object.
... return 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 return objects implementing nsifeedtextconstruct.
... return value an nsidocumentfragment containing the text and markup.
... plaintext() returns the text as plain text with all markup stripped and all entities decoded.
...And 2 more matches
nsIFilePicker
return value constants these values are returned by show() or passed as an argument to open()'s callback, indicating the result of the file picker activity.
... constant value description returnok 0 the file picker dialog was closed by the user hitting 'ok' returncancel 1 the file picker dialog was closed by the user hitting 'cancel' returnreplace 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.
... return value one of the return 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 returns true if and only if the channel has been canceled.
...void getrequestversion( out unsigned long major, out unsigned long minor ); parameters major on return, contains the request's major version number.
... minor on return, 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 returns a meaningful result on all common platforms.
... methods enumeratemultireporters() returns an enumerator for looking at the installed memory multi-reporters.
...return value an enumerator of nsimemorymultireporters that are currently registered.
...And 2 more matches
nsIPrintingPrompt
if an embedder implemented service returns any error code (other than ns_error_abort) printing will terminate.
... returning 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 return 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 returned by the process upon exit.
... gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method returned the process id of the newly executing process.
... it no longer returns 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); return; } // `subscription` implements `nsipushsubscription`.
... example pushservice.getsubscription( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error fetching subscription: " + code); return; } // `subscription == null` if the `(scope, principal)` pair doesn't have a // push subscription.
... example pushservice.unsubscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, ok) => { if (!components.issuccesscode(code)) { cu.reporterror("error unsubscribing: " + code); return; } // `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 returned.
...the enumerator object thus returned by this method can be traversed using nsisimpleenumerator.
... use nsisimpleenumerator.getnext() on the object returned by step #1 to obtain handle to the next object in the list.
...And 2 more matches
nsIScreenManager
methods native code only!screenfornativewidget returns the nsiscreen instance for the native widget pointer.
... return value the nsiscreen instance for the native widget pointer.
... screenforrect() returns 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 return a converted (blocking) stream to you.
...it will then convert that data from type x to your desired output type and return converted data to you via the nsistreamlistener you passed in by calling its nsistreamlistener.ondataavailable() method.
... atotype the mime type of the returned stream.
...And 2 more matches
nsITaggingService
return value returns 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 return the tags.
... length optional on return, contains the number of tags returned in atags.
...And 2 more matches
nsITelemetry
returns 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.
... return value the returned jsval object has the following functions: add(value) - adds an integer value to the appropriate bucket snapshot() - returns a snapshot of the histogram with the same data fields as in histogramsnapshots.
... return value the returned 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 returns, the thread will be shut down and will no longer be available to receive events.
... return 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 returns, the event queue may no longer be empty, even if a false result is reported.
...And 2 more matches
nsITreeBoxObject
selectionregion nsiscriptableregion readonly: return the region for the visible parts of the selection, in device pixels.
...returns -1 for invalid mouse coordinates.
...returns -1 for invalid mouse coordinates.
...And 2 more matches
nsIUTF8ConverterService
if not, convert to utf-8 assuming it's encoded in acharset and return the converted string in utf-8.
... return value the converted string in utf-8.
...if not, convert it to utf-8, assuming it's encoded in acharset, and return the result.
...And 2 more matches
nsIUTF8StringEnumerator
inherits from: nsisupports last changed in gecko 1.7 method overview autf8string getnext(); boolean hasmore(); methods getnext() returns the next string in the enumerator.
...must be preceded by a call to hasmore(), which returns pr_true.
...return value the next string in the enumerator.
...And 2 more matches
nsIXSLTProcessor
returns null otherwise.
... return value an nsivariant containing the value of the parameter.
... return value an document containing the result of the transformation.
...And 2 more matches
nsIZipWriter
getentry() returns a specified entry or null if there is no such entry in the current zip file.
... return value an nsizipentry object describing the specified entry, or null if there is no such entry.
... return value true if there is an entry with the given path in the zip file, otherwise returns 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 return the buffer as-is.
... adata [out] upon return, if the function was successful, then *adata references the string's internal buffer.
... return values this function returns 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() { return 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); return; } 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); return; } }, queryinterface:...
... function (iid) { if (iid.equals(components.interfaces.nsiobserver) || iid.equals(components.interfaces.nsisupports)) return this; components.returncode = components.results.ns_error_no_interface; return 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 return 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 returning a raw pointer or nscomptr (see the nscomptr user manual).
...already_addrefed<nsifoo> getfoo() { nsifoo* foo = mfoo; ns_if_addref(foo); return 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 returns 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 returns 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 returns 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 returns the necessary data for the folder pane's display.
... this data is returned 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)); } return 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: returns the number of messages currently selected.
... gfolderdisplay.selectedmessage: returns the first currently-selected message.
... gfolderdisplay.selectedmessages: returns an array of nsimsgdbhdrs for the selected messages.
...And 2 more matches
Library
method overview close(); cdata declare(name, [abi, ], returntype[, argtype1, ...]); methods close() closes the library.
... cdata declare( name[, abi, returntype 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.
... returntype the ctype type returned by the defined api, if it's a function.
...And 2 more matches
Memory - Plugins
this function returns a pointer to the allocated memory or null if not enough memory is available.
...if npn_memflush returns 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 return a string containing the type, extension list, and type description separated by colons.
... caution: gecko caches the values returned 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 returned by this function.
...And 2 more matches
URLs - Plugins
note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data.
...it returns 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 returns 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 returns a saved call stack indicating wheredobj’s referent was allocated.
... allocationslogoverflowed returns true if there have been more than [maxallocationsloglength][#max-alloc-log] allocations since the last time [drainallocationslog][#drain-alloc-log] was called and some data has been lost.
... returns false otherwise.
...And 2 more matches
Page inspector keyboard shortcuts - Firefox Developer Tools
enter return 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 return 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 + return 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 return enter find the previous match in the markup, when searching is active shift + enter shift + return 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 return 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 return or tab enter or tab increment...
...And 2 more matches
Animation - Web APIs
WebAPIAnimation
animation.finished read only returns the current finished promise for this animation.
... animation.playstate read only returns an enumerated value describing the playback state of an animation.
... animation.ready read only returns 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 returns.
... window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); return settimeout(function() { handler({ didtimeout: false, timeremaining: function() { return 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 returned 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 returns one of the values defined by the org.bluetooth.characteristic.gap.appearance characteristic.
... bluetoothadvertisingdata.txpower read only returns the transmission power at which the device is broadcasting, measured in dbm.
... bluetoothadvertisingdata.rssi read only returns 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 returns the bluetoothremotegattcharacteristic this descriptor belongs to.
... bluetoothremotegattdescriptor.uuidread only returns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor.
... bluetoothremotegattdescriptor.valueread only returns the currently cached descriptor value.
...And 2 more matches
Body - Web APIs
WebAPIBody
it returns a promise that resolves with an arraybuffer.
...it returns a promise that resolves with a blob.
...it returns a promise that resolves with a formdata object.
...And 2 more matches
Cache.keys() - Web APIs
WebAPICachekeys
the keys() method of the cache interface returns a promise that resolves to an array of cache keys.
... the requests are returned in the same order that they were inserted.
... note: requests with duplicate urls but different headers can be returned if their responses have the vary header set on them.
...And 2 more matches
Cache.match() - Web APIs
WebAPICachematch
the match() method of the cache interface returns a promise that resolves to the response associated with the first matching request in the cache object.
... return 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 return the correct response.
...And 2 more matches
Cache.put() - Web APIs
WebAPICacheput
fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request.
... return 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 return a clone of the default network request using return response.clone().
...And 2 more matches
CanvasRenderingContext2D - Web APIs
canvasrenderingcontext2d.measuretext() returns a textmetrics object.
... canvasrenderingcontext2d.getlinedash() returns the current line dash pattern array containing an even number of non-negative numbers.
...this method returns 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(); return; }; 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; return 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(); return 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
WebAPIClipboard
all of the clipboard api methods operate asynchronously; they return a promise which is resolved once the clipboard access has been completed.
... read() requests arbitrary data (such as images) from the clipboard, returning a promise.
... readtext() requests text from the system clipboard; returns a promise which is resolved with a domstring containing the clipboard's text once it's available.
...And 2 more matches
ClipboardItem - Web APIs
types read only returns an array of mime types available within the clipboarditem.
... gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type is not found.
... examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem.
...And 2 more matches
CustomEvent - Web APIs
setting its value to true before returning from an event handler prevents propagation of the event.
...(mozilla-specific.) event.returnvalue 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 returnvalue if you choose to do so.
...And 2 more matches
DedicatedWorkerGlobalScope - Web APIs
properties inherited from workerglobalscope workerglobalscope.self returns an object reference to the dedicatedworkerglobalscope object itself.
... workerglobalscope.console read only returns the console associated with the worker.
... workerglobalscope.location read only returns the workerlocation associated with the worker.
...And 2 more matches
Document.getElementById() - Web APIs
the document method getelementbyid() returns an element object representing the element whose id property matches the specified string.
... return 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 returns null.
...And 2 more matches
Document.getElementsByName() - Web APIs
the getelementsbyname() method of the document object returns a nodelist collection of elements with a given name in the document.
... the returned 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 returns elements that have an id attribute with the specified value.
...And 2 more matches
Document.getElementsByTagNameNS() - Web APIs
returns 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 returns a htmlcollection both in gecko and internet explorer.
... opera returns 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() returns a static (not live) nodelist representing a list of the document's elements that match the specified group of selectors.
... return 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 returned list is always empty.
...And 2 more matches
DocumentOrShadowRoot.elementFromPoint() - Web APIs
the elementfrompoint() method—available on both the document and shadowroot objects—returns 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 returned (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 returned.
...And 2 more matches
DocumentOrShadowRoot.getSelection() - Web APIs
the getselection() property of the documentorshadowroot interface returns a selection object representing the range of text selected by the user, or the current position of the caret.
... returns 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 returned value is passed to the function.
...And 2 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
when called, it returns an array with all of the element's descendants matching the tag name.
...the return value is an object that represents the text node.
...like getelementsbytagname(), it returns a list of nodes.
...And 2 more matches
EXT_disjoint_timer_query.getQueryObjectEXT() - Web APIs
the ext_disjoint_timer_query.getqueryobjectext() method of the webgl api returns the state of a query object.
... syntax any ext.getqueryobjectext(query, pname); parameters query a webglquery object from which to return information.
... pname a glenum specifying which information to return.
...And 2 more matches
Element.getElementsByClassName() - Web APIs
the element method getelementsbyclassname() returns a live htmlcollection which contains every descendant element which has the specified class name or names.
... return 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 returned 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
WebAPIElementlocalName
the element.localname read-only property returns the local part of the qualified name of an element.
... syntax name = element.localname return 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 returns 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() returns 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.
... return 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 returned list is always empty.
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
return value undefined.
... note that to read all files in a directory, readentries needs to be called repeatedly until it returns an empty array.
... in chromium-based browsers, the following example will only return 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 returned, 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 returned to getcurrentposition().
... const watchid = navigator.geolocation.watchposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the watchposition() method returns 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 returns a data uri containing a representation of the image in the format specified by the type parameter (defaults to png).
... the returned 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 returned.
...And 2 more matches
HTMLFormElement.elements - Web APIs
the htmlformelement property elements returns an htmlformcontrolscollection listing all the form controls contained in the <form> element.
... you can access a particular form control in the returned collection by using either an index or the element's name or id.
... prior to html 5, the returned 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 returns 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 returned 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 returns a texttrackslist thru which we can iterate.
...And 2 more matches
HTMLSlotElement.assignedNodes() - Web APIs
the assignednodes() property of the htmlslotelement interface returns 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 returns the slot's fallback content.
... syntax var assignednodes = htmlslotelement.assignednodes(options) parameters options optional an object that sets options for the nodes to be returned.
...And 2 more matches
HTMLSlotElement - Web APIs
methods htmlslotelement.assignednodes() returns 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 returns the slot's fallback content.
... htmlslotelement.assignedelements() returns 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="return checkdrag(event)" ondragover="return checkdrag(event)" ondrop="dodrop(event)"/> <script> function checkdrag(event) { return 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 returns 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 return an nsisupports that needs to be checked and converted into an nsifile.
...And 2 more matches
Headers.get() - Web APIs
WebAPIHeadersget
the get() method of the headers interface returns 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 returns null.
... returns 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
WebAPIIDBIndexget
the get() method of the idbindex interface returns 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 returns the record the key is associated with.
... return value an idbrequest object on which subsequent events related to this operation are fired.
...And 2 more matches
IDBIndex.getKey() - Web APIs
WebAPIIDBIndexgetKey
the getkey() method of the idbindex interface returns 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 return the whole record as idbindex.get does.
... return 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 returns a reference to the mediastreamtrack passed to the constructor.
... imagecapture.takephoto() takes a single exposure using the video capture device sourcing a mediastreamtrack and returns a promise that resolves with a blob containing the data.
... imagecapture.getphotocapabilities() returns 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 returns a domstring with the inserted characters.
... inputevent.datatransferread only returns a datatransfer object containing information about richtext or plaintext data being added to or removed from editable content.
... inputevent.inputtyperead only returns the type of change for editable content such as, for example, inserting, deleting, or formatting text.
...And 2 more matches
compareVersion - Web APIs
returns if the versions are the same or if software installation is not enabled, this method returns 0.
... if the version of registryname is smaller (earlier) than version, this method returns a negative number.
... otherwise, this method returns a positive number.
...And 2 more matches
LockManager.request() - Web APIs
the requested lock is passed to a callback, while the function itself returns a promise that resolves with undefined.
... callback … return 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 returns.
...And 2 more matches
MediaDeviceInfo.groupId - Web APIs
the groupid readonly property of the mediadeviceinfo interface returns 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); } }); }); return 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 returned to the caller.
...And 2 more matches
MediaDeviceInfo - Web APIs
properties mediadeviceinfo.deviceidread only returns a domstring that is an identifier for the represented device that is persisted across sessions.
... mediadeviceinfo.groupidread only returns a domstring that is a group identifier.
... mediadeviceinfo.kindread only returns an enumerated value that is either "videoinput", "audioinput" or "audiooutput".
...And 2 more matches
MediaRecorder - Web APIs
properties mediarecorder.mimetype read only returns the mime type that was selected as the recording container for the mediarecorder object when it was created.
... mediarecorder.state read only returns the current state of the mediarecorder object (inactive, recording, or paused.) mediarecorder.stream read only returns the stream that was passed into the constructor when the mediarecorder was created.
... mediarecorder.videobitspersecond read only returns 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 returns a new mediasource object with no associated source buffers.
... properties mediasource.sourcebuffers read only returns a sourcebufferlist object containing the list of sourcebuffer objects associated with this mediasource.
... mediasource.activesourcebuffers read only returns 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 returns a mediastreamtrack object representing the track with the specified id string.
... if there is no track with the specified id, this method returns null.
... syntax var track = mediastream.gettrackbyid(id); parameters id a domstring which identifies the track to be returned.
...And 2 more matches
MediaStreamTrack.getConstraints() - Web APIs
the getconstraints() method of the mediastreamtrack interface returns 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() return value a mediatrackconstraints object which indicates the constrainable properties the web site or app most recently set using applyconstraints().
... the properties in the returned 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
WebAPIMimeType
navigatorplugins.mimetypes returns an array of this object.
... properties mimetype.type returns the mime type of the associated plugin.
... mimetype.description returns a description of the associated plugin or an empty string if there is none.
...And 2 more matches
NavigatorPlugins.plugins - Web APIs
returns a pluginarray object, listing the plugin objects describing the plugins installed in the application.
... the returned 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 returns the version of the shockwave flash plugin.
...And 2 more matches
Node.isConnected - Web APIs
WebAPINodeisConnected
the isconnected read-only property of the node interface returns 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 return 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); // returns false document.body.appendchild(test); console.log(test.isconnected); // returns 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); // returns 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
WebAPINodenodeValue
the nodevalue property of the node interface returns or sets the value of the current node.
...for the document itself, nodevalue returns null.
... for text, comment, and cdata nodes, nodevalue returns the content of the node.
...And 2 more matches
NodeFilter - Web APIs
nodefilter.acceptnode() returns 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 return values are: constant description filter_accept value returned by the nodefilter.acceptnode() method when a node should be accepted.
... filter_reject value to be returned 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 returning 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.
... return 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 returned list is always empty.
...And 2 more matches
PaymentResponse.retry() - Web APIs
return 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 returned paymentresponse describes the requested payment and the options chosen by the user.
... validate the returned 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 returns a list of performanceentry objects for the given name and type.
... return 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 return.
...And 2 more matches
PerformanceResourceTiming.initiatorType - Web APIs
the value of this string is as follows: if the initiator is a element, the property returns the element's localname.
... if the initiator is a css resource, the property returns "css".
... if the initiator is a xmlhttprequest object, the property returns "xmlhttprequest".
...And 2 more matches
PhotoCapabilities - Web APIs
properties photocapabilities.redeyereduction read only returns one of "never", "always", or "controllable".
... photocapabilities.imageheight read only returns a mediasettingsrange object indicating the image height range supported by the user agent.
... photocapabilities.imagewidth read only returns a mediasettingsrange object indicating the image width range supported by the user agent.
...And 2 more matches
PushManager - Web APIs
properties pushmanager.supportedcontentencodings returns an array of supported content codings that can be used to encrypt the payload of a push message.
...it returns a promise that resolves to a pushsubscription object containing details of an existing subscription.
... pushmanager.permissionstate() returns 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
returns an interface to register or unregister a push registration, get an active registration, or check the permission status of the registration.
... methods pushregistrationmanager.register() returns a promise that resolves to a pushregistration with details of a new registration.
... pushregistrationmanager.unregister() returns 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 returns 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 returns an id number (between 0 and 65,534) which uniquely identifi...
...es the rtcdatachannel.label read only the read-only rtcdatachannel property label returns 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 returns 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 returns 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 returns a value indicative of the available outbound capacity of the network connection represented by the candidate pair.
... the returned 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 returned 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 returned promise, and should then be sent to the source of the offer to continue the negotiation process.
... return 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) { return 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
return 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 return out of the recursive function and print the entire stream to another part of the ui.
... function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...And 2 more matches
ReadableStream.pipeThrough() - Web APIs
the method will return 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 return a promise rejected with the source’s error, or with any error that occurs during aborting the destination.
...in this case the method will return 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, returning a two-element array containing the two resulting branches as new readablestream instances.
... return 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() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...And 2 more matches
ReadableStream - Web APIs
constructor readablestream() creates and returns a readable stream object from the given handlers.
... properties readablestream.locked read only the locked getter returns whether or not the readable stream is locked to a reader.
... readablestream.pipeto() pipes the current readablestream to a given writablestream and returns 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
return 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 return out of the recursive function and print the entire stream to another part of the ui.
... function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...And 2 more matches
ReadableStreamDefaultReader - Web APIs
constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance.
...returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors.
... readablestreamdefaultreader.read() returns 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 returns an svganimatedlengthlist reflecting the x attribute of the given element.
... svgtextpositioningelement.y read only returns an svganimatedlengthlist reflecting the y attribute of the given element.
... svgtextpositioningelement.dx read only returns an svganimatedlengthlist reflecting the dx attribute of the given element.
...And 2 more matches
SVGTransformList - Web APIs
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
...the return value is the item inserted into the list.
... getitem(in unsigned long index) svgtransform returns the specified item from the list.
...And 2 more matches
Screen.availLeft - Web APIs
WebAPIScreenavailLeft
returns 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 returns 0.
... if you work with two screens this property, evaluated on the right screen, returns 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 returns a wakelock object instance, from which all other functionality can be accessed.
...And 2 more matches
ServiceWorkerGlobalScope - Web APIs
this returns a promise that resolves to the response object representing the response to your request.
...when fired, the code returns a promise that resolves to the first matching request in the cache object.
...it will return 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 returns 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 returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
...And 2 more matches
SpeechRecognitionResult.item() - Web APIs
syntax var myalternative = speechrecognitionresultinstance[0]; returns a speechrecognitionalternative object.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
...And 2 more matches
SpeechRecognitionResultList.item() - Web APIs
syntax var myresult = speechrecognitionresultlistinstance[0]; returns a speechrecognitionresult object.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
...And 2 more matches
SpeechRecognitionResultList - Web APIs
properties speechrecognitionresultlist.length read only returns the length of the "array" — the number of speechrecognitionresult objects in the list.
... recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
...And 2 more matches
SpeechSynthesis - Web APIs
speechsynthesis.paused read only a boolean that returns true if the speechsynthesis object is in a paused state.
... speechsynthesis.pending read only a boolean that returns true if the utterance queue contains as-yet-unspoken utterances.
... speechsynthesis.speaking read only a boolean that returns 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 returns a promise which will be fulfilled with a cryptokey object representing the new key.
... return 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) { return 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 returns 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 returns the type of frame container, one of iframe, embed, or object.
... taskattributiontiming.containersrc read only returns the container's src attribute.
...And 2 more matches
Text - Web APIs
WebAPIText
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() returns a text node with the parameter as its textual content.
... text.iselementcontentwhitespace read only returns a boolean flag indicating whether or not the text node contains only whitespace.
... text.wholetext read only returns 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
WebAPIUIEventpageY
the uievent.pagey read-only property returns 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 return 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 return layerx/layery values that are relative to the top-left corner of this positioned element.
... note the pagex\pagey properties still return 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 returned 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 returns 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 returns parameter information of a webglquery object.
... pname a glenum specifying which information to return.
... possible values: gl.query_result: returns a gluint containing the query result.
...And 2 more matches
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
the webglrenderingcontext.checkframebufferstatus() method of the webgl api returns the completeness status of the webglframebuffer object.
... return value a glenum indicating the completeness status of the framebuffer or 0 if an error occurs.
... possible enum return 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 returns information about the given shader.
...possible values: gl.delete_status: returns a glboolean indicating whether or not the shader is flagged for deletion.
... gl.compile_status: returns 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 returned 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 returned 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 returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace.
... the "interface" column in the table below indicates which of the two types is returned 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 returned object.
...And 2 more matches
Web Locks API - Web APIs
the api provides optional functionality that may be used as needed, including: returning values from the asynchronous task shared and exclusive lock modes conditional acquisition diagnostics to query the state of locks in an origin an escape hatch to protect against deadlocks locks are scoped to origins; the locks acquired by a tab from https://example.com have no effect on the locks acquired by a tab from https://example.org:8080 as they are separate origins.
...the lock is automatically released when the callback returns, 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 returns 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 return 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 returned object.
... no support no support no support websocket creates and returns 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 returnvalue property returning a string from the event handler.
... some browsers used to display the returned 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.returnvalue.
...And 2 more matches
Window.scrollX - Web APIs
WebAPIWindowscrollX
the read-only scrollx property of the window interface returns the number of pixels that the document is currently scrolled horizontally.
... syntax var x = window.scrollx; value in practice, the returned 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 returned value is also subpixel-precise and may contain a decimal component.
...And 2 more matches
Window.scrollY - Web APIs
WebAPIWindowscrollY
the read-only scrolly property of the window interface returns the number of pixels that the document is currently scrolled vertically.
... syntax var y = window.scrolly value in practice, the returned 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 returned value is also subpixel-precise and may contain a decimal component.
...And 2 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
return value an instance of the writablestreamdefaultwriter object.
...inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
...finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams.
...And 2 more matches
WritableStreamDefaultWriter.close() - Web APIs
return 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 returns an instance of writablestreamdefaultwriter.
...finally, write() and close() return 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 returns an xpathresult.
... type optional specifies the type of result to be returned by evaluating the expression.
... result optional allows to specify a result object which may be reused and returned 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 returns an xpathresult.
... type optional specifies the type of result to be returned by evaluating the expression.
... result optional allows to specify a result object which may be reused and returned by this method.
...And 2 more matches
XRWebGLLayer.getViewport() - Web APIs
the xrwebgllayer interface's getviewport() method returns 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 returned 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 returned.
...And 2 more matches
attr() - CSS: Cascading Style Sheets
WebCSSattr
it can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
...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() returns 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 return 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 returned or when the autoplay attribute has caused playback to begin.
...And 2 more matches
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
the text must not include carriage returns or line feeds.
... the value returned 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 return 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 returned data.
...location is a header associated with the response, while content-location is associated with the data returned.
... examples requesting data from a server in different formats let's say a site's api can return data in json, xml, or csv formats.
...And 2 more matches
get Array[@@species] - JavaScript
the array[@@species] accessor property returns the array constructor.
... syntax array[symbol.species] return value the array constructor.
... description the species accessor property returns the default constructor for array objects.
...And 2 more matches
Array.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns 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 returned, i.e.
... return 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 returns a string representing the specified bigint object.
... return value a string representing the specified bigint object.
...for bigint objects, the tostring() method returns a string representation of the object in the specified radix.
...And 2 more matches
Boolean.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified boolean object.
... syntax bool.tostring() return value a string representing the specified boolean object.
...for boolean objects, the tostring method returns a string representation of the object.
...And 2 more matches
Function.prototype.apply() - JavaScript
return 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 returns 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); } return 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 returns an object with two properties done and value.
... return 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 return value of the iterator.
...And 2 more matches
Intl.NumberFormat.prototype.formatToParts() - JavaScript
return value an array of objects containing the formatted number in parts.
...it returns 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 returns, 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 returns 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.
... return value the arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, nan.
... description the math.acos() method returns a numeric value between 0 and π radians for x between -1 and 1.
...And 2 more matches
Math.asin() - JavaScript
the math.asin() function returns 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.
... return value the arcsine (in radians) of the given number if it's between -1 and 1; otherwise, nan.
... description the math.asin() method returns 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 returns 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.
... return 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 returned.
...And 2 more matches
Math.log10() - JavaScript
the math.log10() function returns 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.
... return value the base 10 logarithm of the given number.
... if the number is negative, nan is returned.
...And 2 more matches
Math.log1p() - JavaScript
the math.log1p() function returns 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.
... return value the natural logarithm (base e) of 1 plus the given number.
... if the number is less than -1, nan is returned.
...And 2 more matches
Math.tan() - JavaScript
the math.tan() function returns the tangent of a number.
... return value the tangent of the given number.
... description the math.tan() method returns a numeric value that represents the tangent of the angle.
...And 2 more matches
Number.isInteger() - JavaScript
return value a boolean indicating whether or not the given value is an integer.
... description if the target value is an integer, return true, otherwise return false.
... if the value is nan or infinity, return false.
...And 2 more matches
Number.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified number object.
... return value a string representing the specified number object.
...for number objects, the tostring() method returns a string representation of the object in the specified radix.
...And 2 more matches
Object.prototype.constructor - JavaScript
the constructor property returns 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 // return 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() { return 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 returns 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 returned is mutable but mutating it has no effect on the original property's configuration.
... return 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 returns 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 returned.
... return value an array containing the given object's own enumerable property values.
...And 2 more matches
Promise.allSettled() - JavaScript
the promise.allsettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
... in comparison, the promise returned by promise.all() may be more appropriate if the tasks are dependent on each other / if you'd like to immediately reject upon any of them rejecting.
... return value a pending promise that will be asynchronously fulfilled once every promise in the specified collection of promises has completed, either by successfully being fulfilled or by being rejected.
...And 2 more matches
Promise.race() - JavaScript
the promise.race() method returns 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.
... return value a pending promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject.
... description the race function returns a promise that is settled the same way (and takes the same value) as the first promise that settles amongst the promises of the iterable passed as an argument.
...And 2 more matches
Promise.resolve() - JavaScript
the promise.resolve() method returns a promise object that is resolved with a given value.
... if the value is a promise, that promise is returned; if the value is a thenable (i.e.
... has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.
...And 2 more matches
handler.getPrototypeOf() - JavaScript
return value the getprototypeof() method must return 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 return an object or null.
... if target is not extensible, object.getprototypeof(proxy) method must return the same value as object.getprototypeof(target).
...And 2 more matches
handler.set() - JavaScript
return value the set() method should return a boolean value.
... return true to indicate that assignment succeeded.
... if the set() method returns 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 return type.
... it sets the prototype (i.e., the internal [[prototype]] property) of a specified object to another object or to null, and returns true if the operation was successful, or false otherwise.
... return value a boolean indicating whether or not the prototype was successfully set.
...And 2 more matches
RegExp - JavaScript
regexp.prototype.tostring() returns a string representing the specified object.
... regexp.prototype[@@match]() performs match to given string and returns match result.
... regexp.prototype[@@matchall]() returns all matches of the regular expression against a string.
...And 2 more matches
String.prototype.replaceAll() - JavaScript
the replaceall() method returns a new string with all matches of a pattern replaced by a replacement.
...the matches are replaced with newsubstr or the value returned by the specified function.
... return 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 returns 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() returns an empty string.
...(for example, if endindex is -3 it is treated as str.length - 3.) return value a new string containing the extracted section of the string.
...And 2 more matches
TypedArray.prototype.every() - JavaScript
return value true if the callback function returns 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 returns a falsy value (a value that becomes false when converted to a boolean).
... if such an element is found, the every method immediately returns false.
...And 2 more matches
TypedArray.prototype.slice() - JavaScript
the slice() method returns a shallow copy of a portion of a typed array into a new typed array object.
... return value a new typed array containing the extracted elements.
...it returns a shallow copy of elements from the original typed array.
...And 2 more matches
TypedArray.prototype.some() - JavaScript
return value true if the callback function returns 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 returns a true value.
... if such an element is found, some immediately returns true.
...And 2 more matches
WeakMap - JavaScript
weakmap.prototype.has(key) will return false afterwards.
... weakmap.prototype.get(key) returns the value associated to the key, or undefined if there is none.
... weakmap.prototype.has(key) returns 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, returning a boolean result.
... if the operands are of different types, return false.
... if both operands are objects, return true only if they refer to the same object.
...And 2 more matches
yield* - JavaScript
syntax yield* expression; expression the expression which returns an iterable object.
... description the yield* expression iterates over the operand and yields each value returned by it.
... the value of yield* expression itself is the value returned 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; return; } }); } 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 returned rtcrtpsendparameters object, we set codeclist to the codecs property and return to the caller.
... on return, 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 return, 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="return false;"> <p> <label>number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>max.
... function display() { return document.getelementbyid('display'); } // determine dimensions of the display element.
... // return 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') ); return [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() { return [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 returns 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 returned.
... returns 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), returning 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); return 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 returning an array instead).
...And 2 more matches
panel - Archive of obsolete content
the panel just contains a <textarea> element: when the user presses the return 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 return, 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 return, send the "text-entered" // message to main.js.
...only turn this off if necessary, to prevent accessibility issue.
querystring - Archive of obsolete content
returns string : the query string.
... returns object : an object containing the components of the query string as name : value pairs.
... returns string : the escaped query string.
... returns string : the unescaped string.
selection - Archive of obsolete content
getting the selection when there is no current selection returns null.
...getting the selection when iscontiguous is true returns the text of the first selection.
...getting the selection when there is no current selection returns null.
...getting the selection when iscontiguous is true returns the text of the first selection.
self - Archive of obsolete content
methods data.load(name) the data.load() method returns the contents of an embedded data file, as a string.
... returns string : the file contents.
... data.url(name) the data.url() method returns a resource:// url that points at an embedded data file.
... returns 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(); } } return 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 returns a string from the stream.
... returns string : the string read.
... if the stream is at the end, the empty string is returned.
loader/sandbox - Archive of obsolete content
returns sandbox : a sandbox in which you can evaluate and load javascript.
... evaluate(sandbox, code, uri, line, version) evaluate code in sandbox, and return the result.
... returns result : returns whatever the evaluated code returns.
... returns result : returns whatever the evaluated code returns.
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 return 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 return 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); returns state : if you have passed the second state argument to make this function a setter, it returns undefined.
... otherwise, it functions as a getter and returns 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 return 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 return 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); returns state : if you have passed the second state argument to make this function a setter, it returns undefined.
... otherwise, it functions as a getter and returns the button's state for the specified object.
Creating annotations - Archive of obsolete content
$('*').mouseenter(function() { if (!active || $(this).hasclass('annotated')) { return; } 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(); return 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 return 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 return 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 return 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) { return node.isdefaultnamespace(namespaceuri); } switch (node.nodetype) { case 1: // element_node if (!node.prefix) { return (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') { return att.value === namespaceuri; } } ...
... } if (node.parentnode) { // entityreferences may have to be skipped to get to it return isdefaultnamespace(node.parentnode, namespaceuri); } else { return false; // unknown; } case 9: // document_node return isdefaultnamespace(node.documentelement, namespaceuri); case 6: // entity_node case 12: // notation_node case 10: // document_type_node case 11: // document_fragment_node return false; // unknown case 2: // attribute_node: if (node.ownerelement ) { return isdefaultnamespace(node.ownerelement , namespaceuri); } else { return false; // unknown } ...
... default: if (node.parentnode) { // entityreferences may have to be skipped to get to it return isdefaultnamespace(node.parentnode, namespaceuri); } else { return 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 returns false instead of throwing an exception when |c| doesn't support interface |i|.
... another difference is that queryinterface returns an object, where as instanceof returns 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; return channel; }, geturiflags: function(uri) { // do not return ci.nsiaboutmodule.uri_safe_for_untrusted_content unless // you make sure to set a non-system principal in newchannel.
... return 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] returns 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"); return false; // trigger debughook // return true; if you do not wish to trigger debughook } }; // note that debughook does not _always_ trigger when jsd.errorhook[onerror] returns 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); return components.interfaces.jsdiexecutionhook.return_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 }; return 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;} return el.queryselector(selector); } function $$ (selector, el) { if (!el) {el = document;} return el.queryselectorall(selector); // note: the returned object is a nodelist.
... // if you'd like to convert it to a array for convenience, use this instead: // return 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 returning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { return this.queryselector(select...
...or); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; example: <label value="test!"/> <script type="text/javascript"><![cdata[ xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; alert(document.$('label')); // [object xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml return 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 return this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { return 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) { return 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; } } return 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) { return 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; } //return (xmlbase === '') ?
... null : xmlbase; return 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 returns 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(); return content.replace(/\r\n?/g, "\n"); } catch (ex) { } return 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, return the pointer file, and relaunch firefox again.
... getbrowserstate() returns a json-formatted5 text string representing the state of every currently open browser window.
JavaScript Object Management - Archive of obsolete content
* @return the user name.
... */ get name() { return this._name; }, /** * gets the user url.
... * @return the user url.
... */ get url() { return 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 .isreturn boolean flag the variable is being returned.
...note that when constructing the return value of a function (e.g.
... return t();), no container variable is available; in this case, .isreturn 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 return type.
Drag and Drop JavaScript Wrapper - Archive of obsolete content
getsupportedflavours() this function should return a list of flavors that the object being dragged over can accept.
...the getsupportedflavours function should return 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"); return 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"); return 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 returned.
... file.readall() read the entire file in, returning an array of lines.
...xxx file.tostring() returns the canonical path to the file.
... file.tourl() returns 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 return values, errors, counters, variable scopes—as they change over the course of the script execution.
...if the breakpoint script returns 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 returns a false value, venkman will stop execution at that point.
... early return from caller with result will cause the function that the breakpoint is set in to return 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 return 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); returns the return 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 return value of confirm() to be a boolean.
... that is incorrect, confirm() always returned a plain integer (in pre-gecko-1.8 versions either 0 or 1).
getLastError - Archive of obsolete content
getlasterror returns the most recent nonzero error code.
...returns the most recent nonzero error code.
... for a list of possible values, see return codes.
...the getlasterror method does not return errors from methods that return objects, such as getfolder.
patch - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
...if the existing version of the file does not match the checksum stored in the gdiff file, patch returns 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 returned.
Methods - Archive of obsolete content
(mac os only) getcomponentfolder returns an object representing the directory in which a component is installed.
... getfolder returns an object representing a directory, for use with the addfile method.
... getlasterror returns the most recent non-zero error code.
... loadresources returns an object whose properties are localized strings loaded from the specified property file.
XUL Events - Archive of obsolete content
returning false from this event handler prevents the popup from appearing.
...returning false from this event handler prevents the popup from appearing.
...the script may return a value to set the element to a specific value rather than the value of the preference.
...the script may return 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 returns a new nsifile object.
...that is, nsiscriptableio.getfile() will still return a valid file reference even if the file 'sample.txt' does not yet exist.
...the exists method returns true if the file is present and false if it is not.
...for instance, on windows, the value 'strt' returns 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) { return table[row][col.id]; }; this.getcellvalue = function(row, col) { return table[row][col.id]; }; this.settree = function(treebox) { this.treebox = treebox; }; this.iseditable = function(row, col) { return col.editable; }; this.iscontainer = function(row){ return false; }; this.isseparator = function(row){ return false; }; this.issorted = function(){ return false; }; this.getlevel = ...
...function(row){ return 0; }; this.getimagesrc = function(row,col){ return 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])) return 1 * order; if (prepareforcomparison(a[columnname]) < prepareforcomparison(b[columnname])) return -1 * order; //tie breaker: name ascending is the second level sort if (columnname != "name") { if (prepareforcomparison(a["name"]) > prepareforcomparison(b["name"])) return 1; if (prepareforcomparison(a["name"]) < prepareforcomparison(b["name"])) return -1; } return 0; } table.sort(columnsort); //se...
...for strings, lowercases them function prepareforcomparison(o) { if (typeof o == "string") { return o.tolowercase(); } return o; } function gettopvisiblerow() { return tree.treeboxobject.getfirstvisiblerow(); } function settopvisiblerow(topvisiblerow) { return 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 returns 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 returned from the query.
... if the query returns six results, six listitems will be generated.
...you can return 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 returns an nsiatom for the column, making it fast to do comparisons.
...it returns the number of rows that can be displayed in the tree.
...it should return 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, return 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="return dook();" ondialogcancel="return docancel();"> <script> function dook(){ alert("you pressed ok!"); return true; } function docancel(){ alert("you pressed cancel!"); return 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 return true, which indicates that the dialog should be closed.
... if the dialog shouldn't be closed, false should be returned 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="return dosave();" buttonlabelcancel="cancel" buttonaccesskeycancel="n" ondialogcancel="return docancel();"> <script> function dosave(){ //dosomething() return true; } function docancel(){ return 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 returns a window that matches it.
...the cookie manager has an enumerator method which returns an object which implements nsisimpleenumerator.
...an enumerator has a hasmoreelements() method which will return true until we get to the last cookie.
...since an enumerator just returns 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 return 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 returns true if afile implements the nsilocalfile interface.
... isdirectory() returns 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) return 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) return 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
return 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 return 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)) return 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 } } } return 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 return 0; } // for definitions of the remaining functions see xulplanet.com listobj.onprogresschange = function() { return 0 }; listobj.onstatuschange = function() { return 0 }; listobj.onsecuritychange = function() { return 0 }; listobj.onlinkiconavailable = function() { return 0 }; /* i use the progress listener to trap the end of a local html "template" file loa...
promptBox - Archive of obsolete content
it's returned by the tabbrowser method gettabmodalpromptbox method.
... return value an nsidomelement object representing the new prompt.
... listprompts() returns a list of all the prompts on the tabbrowser.
... return value a nodelist containing all of the prompt elements on the tabbrowser.
radio - Archive of obsolete content
ArchiveMozillaXULradio
« 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 returns the enclosing radiogroup that the radio element is contained within, which may or may not be its direct parent.
scale - Archive of obsolete content
ArchiveMozillaXULscale
insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata decrease() return type: no return value decreases the value of the scale or number box by the increment.
... decreasepage() return type: no return value decreases the value of the scale by the pageincrement.
... increase() return type: no return value increases the value of the scale or number box by the increment.
... increasepage() return type: no return 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 returns the xpcom object which holds information about the user's locale.
... stringbundle type: nsistringbundle returns the xpcom string bundle object which implements nsistringbundle.
... methods getformattedstring( key, strarray ) return type: string looks up the format string for the given key name in the string bundle and returns a formatted copy where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
... getstring( key ) return type: string returns the string with the given key name from the string bundle.
tree - Archive of obsolete content
ArchiveMozillaXULtree
columns type: nsitreecolumns returns 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 ) return type: no return 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 ) return type: no return 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 returns 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); } return arr; } to get the text value for a specific column (for exa...
NPEvent - Archive of obsolete content
if your instance accepts key events, return true, and key events will be sent to the instance until it receives a losefocusevent.
... if your plug-in ignores key events, return 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 return true.
... if you don't want a special cursor, return false and the browser will use the standard arrow cursor.
NPN_GetAuthenticationInfo - Archive of obsolete content
the length of the returned username buffer.
...the length of the returned password buffer.
... returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns an error code.
NPN_GetIntIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns 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 returned.
... returns an npidentifier identifying the integer.
... description all calls for the same integer are guaranteed to return the same exact identifier.
NPN_GetStringIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns 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 returned.
... returns an npidentifier identifying the string.
... description all calls for the same string are guaranteed to return the same exact identifier.
NPN_GetStringIdentifiers - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns 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 returned.
... returns on return, 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 return the same exact identifiers.
NPN_GetURLNotify - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
...it returns immediately and only later handles the request and calls npp_urlnotify().
... if this function is called with a target parameter value of _self or a parent to _self, this function should return nperr_invalid_param.
NPN_GetValueForURL - Archive of obsolete content
when multiple cookies are returned for a given url, the format of the return value is: cookie1=value1;cookie2=value2;cookie3=value3 len out parameter.
... the length of the returned value buffer.
... returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns an error code.
NPN NewStream - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
...the stream is returned in the stream parameter.
...if the new stream has the target of _self, this function should return an invalid_param np error.
NPN_RequestRead - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns an error code.
...the plug-in can free these as soon as the call returns.
... if npn_requestread() is called on a stream that is not inherently seekable and not initially in mode np_seek, it returns the error code nperr_stream_not_seekable.
NPN_UTF8FromIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns 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 returned.
... returns 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 returned string, the caller is responsible for deallocating the memory used by the string by calling npn_memfree().
NPP_Destroy - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
...upon the user's return 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 returns.
NPP_Write - Archive of obsolete content
the buffer is allocated by the browser and is deleted after returning from the function, so the plug-in should make a copy of the data it needs to keep.
... returns the plug-in should return the number of bytes written (consumed by the instance).
... if the return 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 returning 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 returned to the plug-in to restore the data in future instances of the plug-in.
...this information can be returned to another instance of the same plug-in if the user returns 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 return it to the browser as an output parameter.
...if the user revisits a web page that contains a plug-in, the browser returns 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 returns 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 returned 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) { return 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 returns 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 returned, instead of the normal element.
... the * selector returns 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 returned by the .
...consider var element = <dogs> <fido color="brown"/> <spike color="black"/> <killer color="brown"/> </dogs>; var list = element.*.(@color == "brown"); originally, elements.* returns a list with all 3 dogs in it.
The global XML object - Archive of obsolete content
the following example defines the foocount() method, which returns the amount of <foo> elements in the xml: xml.prototype.function::foocount = function foocount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // returns 3 ignorecomments true by default.
...this means that if ignorecomments is true, the list returned by .comments() will be empty.
... observe: var element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // returns 0 element.toxmlstring(); // returns <foo><bar/></foo> xml.ignorecomments = false; element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // returns 1 element.toxmlstring(); // returns <foo><!-- my comment --><bar/></foo> ignoreprocessinginstructions true by default.
...for example var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // returns <foo><bar/></foo> xml.ignoreprocessinginstructions = false; var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // returns <foo><?process x="true"?><bar/><?process x="false"?></foo> ignorewhitespace true by default.
Date.getVarDate() - Archive of obsolete content
the getvardate method returns a vt_date value from a date object.
... return value returns 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 return date values in vt_date format.
...the actual format of the returned value depends on regional settings.
Enumerator.atEnd - Archive of obsolete content
the enumerator.atend method returns a boolean value indicating if the enumerator is at the end of the collection.
... the atend method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined.
... otherwise, it returns 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(); } return(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 returns the current item in the collection.
... the item method returns the current item.
... if the collection is empty or the current item is undefined, it returns 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(); } return(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
return 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 return an object.
... var p = new proxy({}, { enumerate(target) { console.log('called'); return ['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) { return 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 returned from our main loop's most recent call to requestanimationframe().
...this value is returned 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 return 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 return their values as they are really used.
...however, the type idl attribute will return the string "text".
...when using idl attributes, you read or set values of the desired type, so input.maxlength is always going to return 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"'); return false; } } else if (href.match(/#$/, '') || href.match(/^#/, '')) { alert('fragment identifiers are disallowed in an xinclude "href" attribute'); return 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 return 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'); return 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); } } } return 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 return true.
...while time may display in 12-hour format, the value returned 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 returned 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>&lt;blockquote&gt;</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>&lt;blockquote&gt;</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 return, 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 returning 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 returns control of the processor.
...the fetching of an image from the server), and then wait until the result has returned before running another operation: main thread: task a task b promise: |__async operation__| since the operation is happening somewhere else, the main thread is not blocked while the async operation is being processed.
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 return values the last essential concept you must know about a function is return values.
... some functions don't return 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 return 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 return specific information.
... let's return 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 returned containing the requested resource, and it is now available.
...we know the response will be successfully returned and available after the load event has fired (unless an error occurred), so we save the response containing the returned 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 returns 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 returns 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 return 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() { return this.todos.filter(todo => { return 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 return the result of this.incomplete.length === 1, and then call that in our template.
... get todocountisone() { return 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 return 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; }); return ref.current; } now we'll define a wasediting constant beneath the hooks at the top of todo().
...just above the return 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; }); return ref.current; } now add the following, above the return 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() { return { 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() { return { 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() { return 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() { return { 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() { return { 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() { return { 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 returns 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 returns the top level document the whole load group is bound to.
... note: the processnexturi method early returns when state of the update is different then downloading.
... on finished state loadcompleted just early returns.
A bird's-eye view of the Mozilla framework
if nsirdfnode doesn't support nsirdfliteral, it returns 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 return the value of the link.
... otherwise it returns null.
... if (link) return link.value; else return 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": return this.nodefortreeindex(arowindex).uri; break; // index of node in parent container case "indexinparent": return this.nodefortreeindex(arowindex).bookmarkindex; break; // is the row even or odd?
... case "parity": return (arowindex % 2 === 0 ?
... return 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 return the xul <browser> that these documents / windows belong to.
... both return 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 returns the result.
...we know it's blocked waiting for the synchronous message to return, 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 returns true if the notification panel is currently visible, false if it is not.
... return value the corresponding notification object, or null if no such notification exists.
... return value returns the notification object corresponding to the added notification.
...the anchorelement property returns the notification's anchor element.
Deferred
a deferred object is returned 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(); }); return deferred.promise; would be return 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'); return promise.defer(); } else if (typeof(promiseutils) != 'undefined' && promiseutils.defer) { //need import of promiseutils.jsm for example: cu.import('resource:/gree/modules/promiseutils.jsm'); return 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'); return 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) returns the original source, line, and column information for the generated source's line and column positions provided.
... and an object is returned with the following properties: source: the original source file, or null if this information is not available.
... sourcenode.prototype.tostring() return the string representation of this source node.
... sourcenode.prototype.tostringwithsourcemap(startofsourcemap) returns 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 * @return 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 * @return a pair: [function that gets the right plural form, * function that returns 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 returned functions.
... (you can use destructured assignment in javascript 1.7 to keep things clean.) the returned 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'); return in_array($locale, $rtl_locales); } ?> <html lang="<?= $locale?>" dir="<?= isrtl($locale) ?
...this is useful for strings occurring in the webapp multiple times, like "return 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 returned by localeconv() in php.
...good: function num_format($num, $decimals) { $locale_info = localeconv(); return 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 return its log file descriptor (or -1 on error).
... tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, returning 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 return.
... type "export nspr_log_file=~/desktop/cookie-log.txt" and press return.
... type "export nspr_log_modules=cookie:4" and press return.
... run firefox by typing "./firefox-bin" and pressing return (note that firefox will launch behind windows for other applications).
NSPR Types
miscellaneous types are used for representing size, pointer difference, boolean values, and return 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 ) { return; }; 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 return values size type prsize pointer difference types types for pointer difference.
... prbool prpackedbool status type for return values prstatus ...
PL_HashTableLookup
looks up the entry with the specified key and return its value.
... returns 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 returns null.
... this means that one cannot tell whether a null return value means the entry does not exist or the value of the entry is null.
PR_FindSymbol
pr_findsymbol() will return 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 returned by pr_loadlibrary, or null.
... returns an untyped pointer.
... description this function finds and returns 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 returned by pr_getlibrarypath.
... returns if successful, returns a new character string containing a constructed path name.
... in case of error, returns null.
... if sufficient storage cannot be allocated to contain the constructed path name, the function returns null.
PR_GetLibraryPath
returns a copy of the default library pathname string.
... in case of error, returns null.
... description this function retrieves the current default library pathname, copies it, and returns the copy.
... if sufficient storage cannot be allocated to contain the copy, the function returns null.
PR_Initialize
returning from prmain leads to termination of the process.
... returns the value returned from the root function, prmain.
...this allows main to be treated like any other function, signaling its completion by returning and allowing the runtime to coordinate the completion of the other threads of the runtime.
... pr_initialize does not return to its caller until all user threads have terminated.
PR_Now
returns the current time.
... returns the current time as a prtime value.
... description pr_now() returns 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 returned by pr_now() are monotonically increasing because the system clock of the computer may be reset.
PR_Writev
returns one of the following values: a positive number indicates the number of bytes successfully written.
...therefore, the return value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure).
... note that if pr_writev returns -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 returns -1 with the error code pr_io_timeout_error.
Function_Name
one-line description of what the function does (more than just what it returns).
... syntax #include <headers.h> returntype 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 return 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.
... returns full description of the return 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 return 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 returns 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 returns 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 return 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 returned 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 returns 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 returns 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 return a new pk11uri object.
... previously, ssl_versionrangeset and ssl_versionrangesetdefault returned a failure if the requested version range wasn't fully allowed by the systemwide crypto policy.
... they have been changed to return 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 returns 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 return secfailure and set the ssl_error_unsupported_experimental_api code if the selected api is not available.
... experimental functions will always return this result if they are disabled or removed from a later nss release.
... bugs fixed in nss 3.35 this bugzilla query returns 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 returning the password to the nss * key database.
... */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_geterror()); return; } 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); return; } 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); return; } 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) return pl_strdup("test"); else return 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 returns information about the token in the specified slot.
... on return, 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.
... return value ckr_ok token information was successfully copied.
... fc_gettokeninfo should return ckr_arguments_bad if pinfo is null.
ssltyp.html
secstatus the return value for many ssl functions.
...in this case the value returned by pr_geterror is meaningless.
... returns the function returns one of these values: if successful, secsuccess.
... returns the function returns one of these values: if successful, secsuccess.
Pork Tools
outparamdel outparamdel converts functions to return via return value instead of an outparam.
... if (!*aresult) return ns_error_failure; return 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) return nsnull; // error returns are changed to nsnull //instead ns_ok, actual result is returned return 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 return already_addrefed<nsifoo>.
Scripting Java
all the methods return an array of file objects.
... being able to view the parameters and return type of java methods is particularly useful in exploratory programming where we might be investigating a method and are unsure of the parameter or return types.
... public class overload { public string f(object o) { return "f(object)"; } public string f(string s) { return "f(string)"; } public string f(int i) { return "f(int)"; } public string g(string s, int i) { return "g(string,int)"; } public string g(int i, string s) { return "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 { return 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 returned 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; return function () { x++; } } closes over x in f.
...it lacks observed type information for its arguments, its return value, or both.
JSErrorReport
macros name description jsreport_is_warning(flags) returns true if flags has jsreport_warning.
... jsreport_is_exception(flags) returns true if flags has jsreport_exception.
... jsreport_is_strict(flags) returns true if flags has jsreport_strict.
... jsreport_is_strict_mode_error(flags) returns true if flags has jsreport_strict_mode_error.
JS_GetFunctionObject
description js_getfunctionobject returns the javascript function object for a specified function pointer, fun.
...in other cases, the object returned by js_getfunctionobject is not necessarily safe to call and should not be exposed to script.
...calling the jsobject returned by it could cause a crash or worse.
... js_getfunctionobject always returns 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, returns a pointer to the object's private data.
... otherwise it returns 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 returns 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 returning null.
JS_GetScopeChain
description js_getscopechain returns 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 returns a pointer to the first jsobject on the current scope chain.
... otherwise, if cx has a global object, js_getscopechain returns that.
... otherwise, an error is reported and js_getscopechain returns null.
JS_InstanceOf
js_instanceof returns true if obj is of the given class and false otherwise.
... that is, it returns js_getclass(obj) == clasp.
...if obj is of the given class, it returns true.
... otherwise, it returns false; it also reports a typeerror containing the function's name.
JS_InternString
description js_internstring and js_internstringn return an interned javascript string with a specified value, s.
...if an interned string already exists with the desired value, these functions return the existing string.
...on success, these functions return a pointer to the interned string.
... otherwise they report an error and return null.
JS_MapGCRoots
the map function should return js_map_gcroot_remove to cause the currently enumerated root to be removed.
... to stop enumeration, return js_map_gcroot_stop.
... to continue mapping, return js_map_gcroot_next.
... js_mapgcroots returns the count of roots that were successfully mapped.
JS_NewScriptObject
return the javascript script object that wraps a compiled script.
... description js_newscriptobject returns the script object associated with the given jsscript.
... on success, js_newscriptobject returns a pointer to the script's object.
... otherwise it returns 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 return false.
... for example, if making the object requires an allocation, and that allocation fails, out-of-memory might be reported, and js_preventextensions would return false.
... var target = {}; var handler = { preventextensions: function(obj) { return 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 returns true (that is, does not fail).
... thus you should always check the return value of js_preventextensions, and only if that is true check the value of *succeeded.
JS_SetElement
on success, js_setelement returns true.
... on error or exception, js_setelement returns false.
... obsolete since jsapi 29 on success, js_setelement returns true and the value left in *vp is left unchanged unless an addproperty hook or setter modified it.
... on error or exception, js_setelement returns false and the value left in *vp is unspecified.
JS_SetGCCallback
obsolete since jsapi 13 js_setgccallback returns a pointer to the previously used callback function upon completion.
... the application may store this return value in order to restore the original callback when the new callback is no longer needed.
...the callback may prevent gc from starting by returning false.
... but even if the callback returns 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 returns js_false, and the value left in *foundp is undefined.
...then, if the property exists, but is associated with a different object, js_setpropertyattributes returns js_true.
...if the attributes can be set, js_setpropertyattributes returns js_true.
... if not, it returns js_false.
JS_ValueToFunction
if v is a function object, this returns the associated jsfunction.
... if v is null, undefined, a boolean, a number, or a string, a typeerror is reported and js_valuetofunction returns null.
... the object's jsobjectops.defaultvalue method is called with hint=jstype_function.) js_valuetofunction returns a pointer to the converted function.
... if conversion fails with an error or exception, js_valuetofunction returns null.
Fun With XBL and XPConnect
now accesses to autocompletesession will return the xp-connect object.
... <method name="autocomplete"> <argument name="asearchstring"/> <argument name="resultlistener"/> <body> <![cdata[ return 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_return" 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; return 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); } return 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) { return mcreator(aouter, aiid, aresult); } ns_imethodimp nsgenericfactory::lockfactory(prbool alock) { return 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(); ...
... return 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 returns the string "hello world!".
...if not // provided, the default factory is used, which returns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
... // define the function we want to expose in our interface hello: function() { return "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() { return "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 returns and the application may exit normally.
...it is possible that xpcom will return 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 returned 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)) return -1; nscomptr<nsicookiemanager> cookiemanager; rv = servman->getservicebycontractid("@mozilla.org/cookiemanager", ns_get_iid(nsicookiemanager), getter_addrefs(cookiemanager)); if (ns_failed(rv)) return -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 returned: 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
MozillaTechXPCOMGuideStreams
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(); // returns 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) { return 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) { return 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) return; /* 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 return 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); return ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & aname) { mname.assign(aname); return ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::add(print32 a, print32 b, print32 *_retval) { *_retval = a + b; return 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); return; } 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 returned 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 returned by components.constructor() varies depending upon the arguments given to components.constructor() when called.
...the component is then returned 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); } return instance; } return ctor; } ...
NS_GetComponentManager
« xpcom api reference summary the ns_getcomponentmanager function returns a reference to the xpcom component manager.
... return values the ns_getcomponentmanager function returns ns_ok if successful.
... otherwise, it returns an error code.
... remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called.
NS_GetComponentRegistrar
« xpcom api reference summary the ns_getcomponentregistrar function returns a reference to the xpcom component registrar.
... return values the ns_getcomponentregistrar function returns ns_ok if successful.
... otherwise, it returns an error code.
... remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called.
NS_GetMemoryManager
« xpcom api reference summary the ns_getmemorymanager function returns a reference to the xpcom memory manager.
... return values the ns_getmemorymanager function returns ns_ok if successful.
... otherwise, it returns an error code.
... remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called.
NS_GetServiceManager
« xpcom api reference summary the ns_getservicemanager function returns a reference to the xpcom service manager.
... return values the ns_getservicemanager function returns ns_ok if successful.
... otherwise, it returns an error code.
... remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called.
NS_InitXPCOM2
you may pass null if you are not interested in this return value.
...the resulting interface pointer is addref'd upon return and must either be release'd explicitly or passed to ns_shutdownxpcom when the application is finished with xpcom.
... return values the ns_initxpcom2 function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_InitXPCOM3
you may pass null if you are not interested in this return value.
...the resulting interface pointer is addref'd upon return and must either be release'd explicitly or passed to ns_shutdownxpcom when the application is finished with xpcom.
... return values the ns_initxpcom3 function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_NewLocalFile
return values the ns_newlocalfile function returns ns_ok if successful.
... otherwise, it returns an error code.
...this error is returned 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)) return rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
NS_NewNativeLocalFile
return values the ns_newnativelocalfile function returns ns_ok if successful.
... otherwise, it returns an error code.
...this error is returned 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)) return 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 returned by ns_initxpcom2 (or ns_initxpcom3) or null.
... return values the ns_shutdownxpcom function returns ns_ok if successful.
... otherwise, it returns an error code.
...once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to return object instances.
nsACString_internal
the caller must not modify the characters at the returned address.
... @returns the length of the buffer in characters.
... the caller may modify the characters at the returned address (up to but not exceeding the length of the string).
... @returns the length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions.
operator+=
return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
nsAString_internal
the caller must not modify the characters at the returned address.
... @returns the length of the buffer in characters.
... the caller may modify the characters at the returned address (up to but not exceeding the length of the string).
... @returns 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 returned address.
... @returns the length of the buffer in characters.
... the caller may modify the characters at the returned address (up to but not exceeding the length of the string).
... @returns 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 returned address.
... @returns the length of the buffer in characters.
... the caller may modify the characters at the returned address (up to but not exceeding the length of the string).
... @returns the length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions.
operator=
return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
operator=
return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
mozIStorageFunction
return value an nsivariant this is the return 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); return value * value; }); // run some query that uses the function.
...var squarefunction = { onfunctioncall: function(aarguments) { let value = aarguments.getint32(0); return 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); return ns_ok; } }; // now, register our function with the database connection.
GetChildAt
« nsiaccessible page summary this method returns nth accessible child using zero-based index.
...return value returns nth accessible child using zero-based index.
... if child index is less than zero then returns last child.
... if child index is greater than children count then returns null.
GetChildAtPoint
« nsiaccessible page summary this method returns an accessible child which contains the coordinate at (x, y) in screen pixels.
...return value returns 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 returned.
... if the point is in neither the current accessible or a child, then null will be returned.
nsIChannel
the stream listener's methods are called on the thread that calls asyncopen and are not called until after asyncopen returns.
... if asyncopen returns successfully, the channel promises to call at least onstartrequest and onstoprequest.
... if asyncopen returns successfully, the channel is responsible for keeping itself alive until it has called onstoprequest on alistener or called onchannelredirect.
... return value blocking input stream to the channel's data.
nsIChromeRegistry
a new nsiuri is returned; the original is left unmodified.
... return value a new nsiuri object containing the loadable uri for the specified chrome url.
... violates the xpcom interface guidelines wrappersenabled() returns whether xpcnativewrappers are enabled for the specified uri.
... return value true if xpcnativewrappers are enabled for the specified uri; otherwise false.
nsIClipboardDragDropHooks
return value true indicates to the operating system that if a drop does happen on this browser, it will be accepted.
... return value true if the drag can proceed.
... return value true to indicate that copy/drag can proceed.
... return value true to indicate the action was handled, do not perform built-in behavior.
nsIConsoleService
if no messages are logged, this function will return 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 return 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, {}); return 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); return 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 = {}; return 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 return value clonenode() nsidomnode clonenode( in boolean deep ); parameters deep return value hasattributes() boolean hasattributes(); parameters none.
... return value haschildnodes() boolean haschildnodes(); parameters none.
... return value insertbefore() nsidomnode insertbefore( in nsidomnode newchild, in nsidomnode refchild ); parameters newchild refchild return value issupported() boolean issupported( in domstring feature, in domstring version ); parameters feature version return value normalize() void normalize(); parameters none.
... removechild() nsidomnode removechild( in nsidomnode oldchild ); parameters oldchild return value replacechild() nsidomnode replacechild( in nsidomnode newchild, in nsidomnode oldchild ); parameters newchild oldchild return value see also document object model (dom) level 2 core specificationrec ...
nsIDOMWindow
when setting this attribute, an ns_error_not_implemented error may be returned by implementations not supporting zoom.
... this attribute should always return 1.0 for implementations not supporting text zoom.
... nsidomcssstyledeclaration getcomputedstyle( in nsidomelement elt, in domstring pseudoelt optional ); parameters elt pseudoelt optional return value getselection() returns the nsiselection object indicating what if any content is currently selected in the window.
... return value the nsiselection object for the window.
nsIDirectoryServiceProvider2
xpcom/io/nsidirectoryservice.idlscriptable an extension of nsidirectoryserviceprovider which allows multiple files to be returned for the given key.
... return value an enumerator for a list of file locations.
...use an xpcom return 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.returncode, 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 returned by nsieventlistenerservice.getlistenerinfofor, which provides a list of all the listeners to a given event target.
... methods getdebugobject() returns the debugger object if the debug service is active.
...return value if jsdidebuggerservice is active and the listener is implemented in js, this returns the listener as a jsdivalue.
...return value returns 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() returns 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 return until the event has been processed.
...return value returns 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, returns false.
nsIFileView
note: a quirk of the nsifileview is that it requires an appropriate treecols section in the tree tag, by default fileview will return the file size in the column.
... if the treecol id is "filenamecolumn" fileview will return the file name, if the id is "lastmodifiedcolumn" it will return the date of last modification.
... showonlydirectories boolean if true only directory entries will be returned.
... setfilter() set the filter to be applied to the file list, for example "*.jpg" would only return 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 returns the underlying db connection the form history module is using.
... hasentries boolean returns true if the form history has any entries.
...boolean entryexists( in astring name, in astring value ); parameters name value return value nameexists() returns true if there is no entry that is paired with a name.
... boolean nameexists( in astring name ); parameters name return value removeallentries() removes all entries in the entire form history.
nsIFrameScriptLoader
getdelayedframescripts() returns all delayed scripts that will be loaded once a (remote) frame becomes available.
... the return value is a list of pairs [<url>, <wasloadedinglobalscope>].
... returns list of the delayed scripts.
... each script is returned as a pair: [<url>, <wasloadedinglobalscope>].
nsILoginInfo
methods clone() returns a clone of this login.
... return value an nsilogininfo containing a clone of the login on which this method was invoked.
... return value true if the two logins are exactly equal or false if they're not.
... return value true if the two logins are equivilant or false if they're not.
nsILoginManagerCrypto
methods decrypt() decrypts the specified string, returning the plain text value.
... return value the decrypted string.
... encrypt() encrypts the specified string, returning the ciphertext value.
... return value the encrypted string.
nsIMicrosummaryGenerator
if the generator doesn't specify an interval, null is returned.
... return value the interval in milliseconds until the next update request.
... return value a boolean indicating if the two generators are equal.
... return value the text result of processing the template.
nsIModule
return value indicates to the caller whether or not the component module can be unloaded.
... returning 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 returning true.
... returning false guaratees that the module will not be unloaded.
nsIPermissionManager
return value a pruint32 representing the permission, or unknown_action if no permission exists.
... return value a pruint32 representing the permission, or unknown_action if no permission exists.
... return value a pruint32 representing the permission, or unknown_action if no permission exists.
... return 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 returned if one exists, otherwise a default value will be returned.
... return value nsiprefbranch - the object representing the requested branch.
...when using a get method a default value will always be returned.
... return value nsiprefbranch - the object representing the requested default branch.
nsIProcessScriptLoader
getdelayedprocessscripts() returns all delayed scripts that will be loaded once a child process becomes available.
... the return value is a list of pairs [<url>, false].
... returns list of the delayed scripts.
... each script is returned as a pair: [<url>, false].
nsIProfile
getprofilelist() returns 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 return, contains the number of profiles in the profilenames array.
... profilenames on return, contains an array of all of the available profiles' names.
... return value true if there is a profile with the specified name.
nsIProtocolHandler
uri_does_not_return_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not return any usable data.
... return value return true if the override is approved; otherwise, return false.
... return value return the newly constructed channel.
... return value the new uri object suitable for loading using the protocol.
nsIPushSubscription
methods getkey() returns a byte array containing the key material for this subscription.
...when called from javascript, nsipushsubscription.getkey() only takes name as a parameter, and returns key.
... bool quotaapplies(); nsipushsubscription.quotaapplies() always returns false for system subscriptions.
... bool isexpired(); nsipushsubscription.isexpired() always returns false for system subscriptions.
nsISimpleEnumerator
must be preceded by a call to hasmoreelements() which returns pr_true.
...return value ns_ok if the call succeeded in returning a non-null value through the out parameter.
...hasmoreelements() called to determine whether or not the enumerator has any elements that can be returned via getnext().
...return value pr_true if there are remaining elements in the enumerator.
nsIStringBundleService
chrome://global/locale/global.properties return value a string bundle corresponding to the properties file.
... on the return value object on you can call functions like getstringfromname and formatstringfromname see nsistringbundle.
... return value an extensible bundle corresponding to the properties file(s).
... return value the formatted message.
nsIStringEnumerator
must be preceded by a call to hasmoreelements() which returns pr_true.
...return value the next string in the enumerator.
...hasmore() called to determine whether or not the enumerator has any strings that can be returned via getnext().
...return value true if there are remaining strings in the enumerator.
nsITaskbarPreviewController
return value true if you want a frame drawn around the preview, otherwise false.
... return value true if you want a frame drawn around the thumbnail, otherwise false.
... return 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 returned by the nsitaskbarwindowpreview.getbutton().
nsIThreadManager
methods native code only!getthreadfromprthread given a prthread, this method returns the corresponding nsithread.
... returns null if there isn't a corresponding nsithread.
... return value the nsithread matching the specified prthread, or null if there is no matching nsithread.
... return value the newly created nsithread.
nsIToolkitProfileService
this will always return 0, 1, or 2; if there are more than 2 profiles, 2 is always returned.
... return value an nsitoolkitprofile object representing the newly-created profile.
... return value an nsitoolkitprofile object describing the specified profile.
... return 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 returns ns_base_stream_would_block.
... return 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 returns ns_base_stream_would_block.
... return value seteventsink() set the transport event sink.
nsITreeSelection
getrangeat() returns two objects whose value properties represent the minimum and maximum indices of the given selection range.
... getrangecount() returns a count of selection ranges.
...return value long - number of selection ranges invalidateselection() can be used to invalidate the selection.
... return value rangedselect() select the range specified by the indices.
Storage
no results to be returned 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); return statement->execute(); // once this function returns, mspecialstatement will be reset, and statement will // be destroyed.
...if your function returns without calling commit on the helper object, the transaction will be rolled back.
... return 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; return 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); } return 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); return 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 return values from gettransferdata.
Weak reference
nsresult nsobservable::addobserver( nsiobserver* aobserver ) { mobserver = getter_addrefs( ns_getweakreference(aobserver) ); // ...or append this to the list of observers return 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 return ns_ok; } // ...
...subsequent attempts to reach that part must return nsnull.
... sometimes our queryinterface through the weak pointer would return a pointer to the `real' interface, and sometimes it would return nsnull.
... in javascript, just make sure that your queryinterface method returns 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 returned 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 returned 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) return; 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 returned 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); return cr.ns_success; } } return 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)) return 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)) return rv; nscomptr<nsimsgcopyservice> copyservic...
...e = do_queryinterface(ptr); if (copyservice) copyservice->undo(folder); } return (*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 return "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 returns the elapsed time since system startup, then fetch and output that value.
... const clock = lib.declare("clock", ctypes.default_abi, ctypes.unsigned_long); console.log("clocks since startup: " + clock()); the clock() function requires no input parameters; it simply returns an unsigned long.
... returned values if the return 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 return a javascript number.
... for everything else it returns a ctypes object representing the return value (including 64-bit integers).
ABI
method overview string tosource() string tostring() methods tosource() returns the string "ctypes.***_abi".
... return value a javascript expression that evaluates to the abi.
... tostring() returns a string identifying the abi.
... return value a string identifying the abi.
Mozilla
it synchronously returns 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 returned by mozilla apis the following tables list errors that can occur when calling various mozilla apis.
...these are memory allocation routines that never return null; that is, they always successfully return the requested block of memory.
... this is in contrast to a traditional, fallible memory allocator that can return 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/return, 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 returned.
... 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 return.
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, returning the sorted array.
... selectionsort() implements a selection sort, returning the sorted array.
... quicksort() implements quicksort, returning the sorted array.
Attr.localName - Web APIs
WebAPIAttrlocalName
the attr.localname read-only property returns the local part of the qualified name of an attribute.
... syntax name = attribute.localname return value a domstring representing the local part of the attribute's qualified name.
... note: in gecko 1.9.2 and earlier, the property returns 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 returns 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 returns a mediastreamtrackaudiosourcenode which represents an audio source whose data comes from the specified mediastreamtrack.
... return 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 returned 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 returns a new audiocontext object.
... audiocontext.baselatency read only returns 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 returns an estimation of the output latency of the current audio context.
... audiocontext.getoutputtimestamp() returns a new audiotimestamp object containing two audio timestamp values relating to the current audio context.
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
it is possible to connect an audionode to another audionode, which in turn connects back to the first audionode, creating a cycle.
... return value if the destination is a node, connect() returns a reference to the destination audionode object, allowing you to chain multiple connect() calls.
... in some browsers, older implementations of this interface return undefined.
... if the destination is an audioparam, connect() returns undefined.
AudioTrack.label - Web APIs
WebAPIAudioTracklabel
the read-only audiotrack property label returns a string specifying the audio track's human-readable label, if one is available; otherwise, it returns an empty string.
...otherwise, an empty string ("") is returned.
... example this example returns 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 }); } }); return 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
returns 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 returns 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 returns 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 }); } }); return 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 returns an integer that represents the ever-increasing current sample-frame of the audio block being processed.
... currenttime read only returns a double that represents the ever-increasing context time of the audio block being processed.
... samplerate read only returns 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) { return 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 returns a messageport used for bidirectional communication between the node and its associated audioworkletprocessor.
... audioworkletnode.parameters read only returns an audioparammap — a collection of audioparam objects.
...if the audioworkletprocessor has a static parameterdescriptors getter, the audioparamdescriptor array returned 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 } }) return 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 returns a messageport used for bidirectional communication between the processor and the audioworkletnode which it belongs to.
...the array of audioparamdescriptor-based objects returned 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 } }) return 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 returns 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() returned true (navigator.bluetooth.requestdevice() might not resolve with a bluetoothdevice).
... also, user can configure user agent to return a fixed value instead of a real one.
... return value a promise that resolves with boolean.
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
it returns a promise that resolves with an arraybuffer.
... return 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) { return 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) { return 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 returns a cssrulelist of the css rules in the media rule.
... csskeyframesrule.findrule() returns a keyframe rule corresponding to the given key.
... the key is a domstring containing an index of the keyframe to be returned, resolving to a percentage between 0% and 100%.
... if no such keyframe exists, findrule returns null.
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
the cssstyledeclaration.getpropertycssvalue() method interface returns a cssvalue containing the css value for a property.
... note that it returns null if the property name is a shorthand property.
... return value value is a cssvalue containing the css value for a property.
... if none exists, returns null.
CSSStyleDeclaration.item() - Web APIs
the cssstyledeclaration.item() method interface returns a css property name from a cssstyledeclaration by index.
... this method doesn't throw exceptions as long as you provide arguments; the empty string is returned if the index is out of range and a typeerror is thrown if no argument is provided.
... return value propertyname is a domstring that is the name of the css property at the specified index.
... javascript has a special simpler syntax for obtaining an item from a nodelist by index: var propertyname = style[index]; example var style = document.getelementbyid('div1').style; var propertyname = style.item(1); // or simply style[1] - returns the second style listed specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.item()' in that specification.
CSSUnparsedValue - Web APIs
properties cssunparsedvalue.length returns the number of items in the cssunparsedvalue object.
... methods cssunparsedvalue.entries() returns 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() returns a new array iterator object that contains the keys for each index in the cssunparsedvalue object.
... cssunparsedvalue.values() returns 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 returns the element's layout width and height, while getboundingclientrect() returns the rendering width and height.
... as an example, if the element has width: 100px; and transform: scale(0.5); the getboundingclientrect() will return 50 as the width, while offsetwidth will return 100.
...these return 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 return 600 while scrollheight will return 400.
Cache.add() - Web APIs
WebAPICacheadd
the add() method is functionally equivalent to the following: fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) for more complex operations, you'll need to use cache.put() directly.
... return 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 return 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) { return 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 returns a promise that resolves to true.
... return value a promise that resolves to true if the cache object is found and deleted, and false otherwise.
...we return 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) { return promise.all(keylist.map(function(key) { if (cachestokeep.indexof(key) === -1) { return caches.delete(key); } })); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: delete' in that specification.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
the keys() method of the cachestorage interface returns 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.
... return value a promise that resolves with an array of the cache names inside the cachestorage object.
...we return 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) { return promise.all(keylist.map(function(key) { if (cachewhitelist.indexof(key) === -1) { return caches.delete(key); } }); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: keys' in that specification.
CacheStorage.open() - Web APIs
WebAPICacheStorageopen
the open() method of the cachestorage interface returns 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 returned.
... return value a promise that resolves to the requested cache object.
... self.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); specifications specification ...
Clients - Web APIs
WebAPIClients
methods clients.get() returns a promise for a client matching a given id.
... clients.matchall() returns a promise for an array of client objects.
... an options argument allows you to control the types of clients returned.
... clients.openwindow() opens a new browser window for a given url and returns a promise for the new windowclient.
Clipboard.read() - Web APIs
WebAPIClipboardread
the read() method of the clipboard interface requests a copy of the clipboard's contents, delivering the data to the returned promise when the promise is resolved.
... unlike readtext(), the read() method can return arbitrary data, such as images.
... this method can also return text.
... return value a promise that resolves with a datatransfer object containing the clipboard's contents.
Clipboard.readText() - Web APIs
the clipboard interface's readtext() method returns a promise which resolves with a copy of the textual contents of the system clipboard..
... return value a promise that resolves with a domstring containing the textual contents of the clipboard.
... returns 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 returned text into an element's contents.
ClipboardItem.getType() - Web APIs
the gettype() method of the clipboarditem interface returns a promise that resolves with a blob of the requested mime type or an error if the mime type is not found.
... return value a promise that resolves with a blob object.
... examples in the following example, we're returning all items on the clipboard via the clipboard.read() method.
... then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object.
ClipboardItem.types - Web APIs
the read-only types property of the clipboarditem interface returns 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 returning all items on the clipboard via the clipboard.read() method.
... then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object.
... if no clipboards contents is found for the specified type, an error is returned.
ContentIndex.getAll() - Web APIs
the getall() method of the contentindex interface returns a promise that resolves with an iterable list of content index entries.
... return value returns a promise that resolves with an array of contentdescription items.
... contentdescription each item returned 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 returned.
CredentialsContainer - Web APIs
methods credentialscontainer.create()secure context returns 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 returns 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 returns an empty promise.
... credentialscontainer.store()secure context stores a set of credentials for a user, inside a provided credential instance and returns that instance in a promise.
CustomElementRegistry.get() - Web APIs
the get() method of the customelementregistry interface returns 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 return a reference to.
... return 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)); } }) // return 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() returns the constuctor for the named custom element, or undefined if the custom element is not defined.
... customelementregistry.whendefined() returns an empty promise that resolves when a custom element becomes defined with the given name.
... if such a custom element is already defined, the returned 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 return 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() returns a domexception object with a specified message and name.
... properties domexception.code read only returns a short that contains one of the error code constants, or 0 if none match.
... domexception.message read only returns a domstring representing a message or description associated with the given error name.
... domexception.name read only returns a domstring that contains one of the strings associated with an error name.
DOMImplementation.hasFeature() - Web APIs
the domimplementation.hasfeature() method returns a boolean flag indicating if a given feature is supported.
... it is deprecated and modern browsers return true in all cases.
...the latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
... living standard modified to always return true except for svg features.
DOMRectReadOnly - Web APIs
note that this constructor cannot be called by 3rd party javascript; doing so returns an "illegal constructor" typeerror.
... domrectreadonly.top read only returns the top coordinate value of the domrect (usually the same as y.) domrectreadonly.right read only returns the right coordinate value of the domrect (usually the same as x + width).
... domrectreadonly.bottom read only returns the bottom coordinate value of the domrect (usually the same as y + height).
... domrectreadonly.left read only returns the left coordinate value of the domrect (usually the same as x).
DOMStringList - Web APIs
a type returned by some apis which contains a list of domstring (strings).
... properties domstringlist.length read only returns the length of the list.
... methods domstringlist.item() returns a domstring.
... domstringlist.contains() returns 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
WebAPIDOMTokenListitem
the item() method of the domtokenlist interface returns 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 return.
... return value a domstring representing the returned item.
... it returns 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() returns false immediately, without adding the new token to the token list.
... return value a boolean value, which is true if oldtoken was successfully replaced, or false if not.
... note: in older browsers, replace() returns 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); return true; } return 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 returns false.
... if token doesn't exist it's added and the function returns true.
... force optional a boolean that, if included, turns the toggle into a one way-only operation.
... return 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 returns an empty string.
... return 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 returns an empty string.
...this may result in unexpected behavior, being datatransfer.getdata() not returning an expected value.
DataTransfer.mozTypesAt() - Web APIs
the datatransfer.moztypesat() method returns 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 returned.
... return 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 returned.
DataTransferItemList.DataTransferItem() - Web APIs
syntax dataitem = datatransferitem[index]; parameters index the zero-based index of the item in the drag data list to return.
... return 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 returned.
... the returned value is never null.
Document.execCommand() - Web APIs
syntax document.execcommand(acommandname, ashowdefaultui, avalueargument) return value a boolean that is false if the command is unsupported or disabled.
... note: only returns true if part of a user interaction.
... don't try using the return value to verify browser support before calling a command.
... insertbronreturn 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 returns a string containing the date and time on which the current document was last modified.
... alert(document.lastmodified); // returns: 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 returns the time string in utc; gecko and internet explorer return a time in the local timezone.
... (see: bug 4363 – document.lastmodified returns date in utc time, but should return 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 returns 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; return value the element object that's currently in full-screen mode; if full-screen mode isn't currently in use by the document>, the returned value is null.
... example this example presents a function, isvideoinfullscreen(), which looks at the value returned 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 returns true, indicating that the video is in full-screen mode.
... function isvideoinfullscreen() { if (document.fullscreenelement && document.fullscreenelement.nodename == 'video') { return true; } return 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 returns 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; // returns a shadowroot obj closed: denies access to the node(s) of a closed shadow root from javascript outside it: element.shadowroot; // returns null delegatesfocus a boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability.
... return value returns 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 return 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) returns an array of all animation objects affecting this element or which are scheduled to do so in future.
... it can optionally return 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 returned as well.
... return 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 returned promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode.
... return 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 returned.
... detecting full-screen activation you can determine whether or not your attempt to switch to full-screen mode is successful by using the promise returned by requestfullscreen(), as seen in the example below.
Element.tagName - Web APIs
WebAPIElementtagName
the tagname read-only property of the element interface returns 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 returned tag name is always in the canonical upper-case form.
... for example, tagname called on a <div> element returns "div".
... the tag names of elements in an xml dom tree are returned in the same case in which they're written in the original xml file.
ExtendableMessageEvent - Web APIs
extendablemessageevent.data read only returns the event's data.
... extendablemessageevent.origin read only returns the origin of the client that sent the message.
... extendablemessageevent.source read only returns a reference to the client object that sent the message.
... extendablemessageevent.ports read only returns the array containing the messageport objects representing the ports of the associated message channel.
FeaturePolicy - Web APIs
featurepolicy methods featurepolicy.allowsfeature returns a boolean that indicates whether or not a particular feature is enabled in the specified context.
... featurepolicy.features returns a list of names of all features supported by the user agent.
... featurepolicy.allowedfeatures returns a list of names of all features supported by the user agent and allowed by the feature policy.
... featurepolicy.getallowlistforfeature returns the allow list for the specified feature.
FetchEvent.request - Web APIs
the request read-only property of the fetchevent interface returns the request that triggered the event handler.
...it will return 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); return response; } console.log('no response found in cache.
... about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return 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() returns 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 return.
... return 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() returns 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 return.
... return 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
WebAPIFontFace
constructor fontface() constructs and returns a new fontface object, built from an external resource described by an url or from an arraybuffer.
... fontface.loaded read only returns 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 returns 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 returns a promise that resolves with the current fontface object.
FormData.get() - Web APIs
WebAPIFormDataget
the get() method of the formdata interface returns the first value associated with a given key from within a formdata object.
... return value a formdataentryvalue containing the value.
... if the key doesn't exist, the method returns 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 return the first username value appended: formdata.get('username'); // returns "chris" specifications specification status comment xmlhttprequestthe definition of 'get()' in that specification.
FormData.getAll() - Web APIs
WebAPIFormDatagetAll
the getall() method of the formdata interface returns all the values associated with a given key from within a formdata object.
... returns an array of formdataentryvalues whose key matches the value passed in the name parameter.
... if the key doesn't exist, the method returns 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 return both username values in an array: formdata.getall('username'); // returns ["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) return; // 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() returns a list of explicitly observed performanceentry objects based on the list of entry types given to performanceobserver.observe().
... performanceobserverentrylist.getentriesbytype() returns a list of explicitly observed performanceentry objects of the given entry type.
... performanceobserverentrylist.getentriesbyname() returns 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, returning the updated location.
...a geolocationposition instance is returned 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 returned by an unsuccessful call to one of the methods contained inside geolocation, inside an error callback, and contains an error code and message.
...returns a geolocation object instance, from which all other functionality can be accessed.
HTMLCanvasElement.getContext() - Web APIs
the htmlcanvaselement.getcontext() method returns 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 return the same drawing context instance as was returned the last time the method was invoked with the same contexttype argument.
... return 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 returned.
HTMLCollection.item - Web APIs
the htmlcollection method item() returns 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 returned.
... return 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 returns a numbered element from an htmlcollection.
HTMLDialogElement.close() - Web APIs
an optional domstring may be passed as an argument, updating the returnvalue of the the dialog.
... syntax dialoginstance.close(returnvalue); parameters returnvalue optional a domstring representing an updated value for the htmldialogelement.returnvalue of the dialog.
... return 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.returnvalue = '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 returns 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 returned, or the body if there are no ancestor table elements either.
... note: offsetparent returns 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 returns <body>).
HTMLImageElement.decode() - Web APIs
the decode() method of the htmlimageelement interface returns 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.
... return value a promise which is resolved once the image data is ready to be used.
...without a promise-returning 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 returning 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 returning control to other javascript code.
... queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not return a value.
...an urgent callback has run!"); let dowork = () => { let result = 1; queuemicrotask(urgentcallback); for (let i=2; i<=10; i++) { result *= i; } return result; }; log("main program started"); settimeout(callback, 0); log(`10!
Headers.getAll() - Web APIs
WebAPIHeadersgetAll
the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one.
... if the requested header doesn't exist in the headers object, it returns an empty array.
... returns 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'); // returns [ "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'); // returns [ "deflate", "gzip" ] note: use headers.get to return 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) { return; } 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) { return surl.replace(rsearch, "") + ("?" + surl.replace(rhost, "&").replace(rview, sviewmode ?
... "&" + sviewkey + "=" + sviewmode : "").slice(1)).replace(rendqstmark, ""); } function getpage (spage) { if (bisloading) { return; } 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); return false; } return 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() returns immediately and closes the connection to a database in a separate thread.
... idbdatabase.createobjectstore() creates and returns a new object store or index.
... idbdatabase.transaction() immediately returns a transaction object (idbtransaction) containing the idbtransaction.objectstore method, which you can use to access your object store.
... error fired when a request returns an error and the event bubbles up to the connection object.
IDBFactory.deleteDatabase() - Web APIs
the method returns 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 returned from this method, with its result set to undefined.
... if an error occurs while the database is being deleted, then an error event is fired on the request object that is returned from this method.
... 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.) return value a idbopendbrequest on which subsequent events related to this request are fired.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
the method returns 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 returned from this method, with its result attribute set to the new idbdatabase object for the connection.
... if an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method.
... return value a idbopendbrequest object on which subsequent events related to this request are fired.
IDBIndex.count() - Web APIs
WebAPIIDBIndexcount
the count() method of the idbindex interface returns an idbrequest object, and in a separate thread, returns the number of records within a key range.
... return 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 returned 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 returns.
IDBIndex.openKeyCursor() - Web APIs
the openkeycursor() method of the idbindex interface returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index.
... note: cursors returned by openkeycursor() do not make the referenced value available as idbindex.opencursor does.
... return 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 returned records are sorted based on the index, not the primary key.
IDBKeyRange.includes() - Web APIs
the includes() method of the idbkeyrange interface returns a boolean indicating whether a specified key is inside the key range.
... return value a boolean.
... example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns 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) return false; if (!r.loweropen && c < 0) return false; } if (r.upper !== undefined) { c = indexeddb.cmp(key, r.upper); if (r.upperopen && c >= 0) return false; if (!r.upperopen && c > 0) return false; } return 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 returns 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 return 1 if the row exists and 0 if it doesn't.
... count optional specifies the number of values to return if more than one is found.
... return value an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.put() - Web APIs
it returns 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 returned 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.
... return 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 returned 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
WebAPIIDBRequesterror
the error read-only property of the idbrequest interface returns the error in the event of an unsuccessful request.
...in chrome 48+/firefox 58+ this property returns a domexception because domerror has been removed from the dom standard.
... the following error codes are returned 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 returned 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 returns 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, returns the same idbobjectstore instance.
... if this method is called on a different transaction object, a different idbobjectstore instance is returned.
... return value an idbobjectstore object for accessing an object store.
IDBTransaction - Web APIs
idbtransaction.error read only returns a domexception indicating the type of error that occured when there is an unsuccessful transaction.
... idbtransaction.objectstorenames read only returns a domstringlist of the names of idbobjectstore objects associated with the transaction.
... idbtransaction.objectstore() returns an idbobjectstore object representing an object store that is part of the scope of this transaction.
... error fired when a request returns an error and the event bubbles up to the transaction object.
getVersion - Web APIs
getversion returns an object representing the version number from the client version registry for the specified component.
... returns if software installation is disabled, this method returns null.
... otherwise, it returns 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 returns null.
IntersectionObserverEntry - Web APIs
properties intersectionobserverentry.boundingclientrect read only returns the bounds rectangle of the target element as a domrectreadonly.
... intersectionobserverentry.intersectionratio read only returns the ratio of the intersectionrect to the boundingclientrect.
... intersectionobserverentry.intersectionrect read only returns a domrectreadonly representing the target's visible area.
... intersectionobserverentry.rootbounds read only returns a domrectreadonly for the intersection observer's root.
KeyboardEvent.location - Web APIs
the keyboardevent.location read-only property returns an unsigned long representing the location of the key on the keyboard or other input device.
... note: when numlock is locked, gecko always returns 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 returns dom_key_location_numpad too.
... note: gecko always returns dom_key_location_mobile on android (prior to 18) and maemo.
LayoutShift - Web APIs
properties layoutshift.value returns the impact fraction (fraction of the viewport that was shifted) times the distance fraction (distance moved as a fraction of viewport).
... layoutshift.hadrecentinput returns true if there was a user input in the past 500 milliseconds.
... layoutshift.lastinputtime returns the time of the most recent user input.
... layoutshift.sources returns an array of layoutshiftattribution objects with information on the elements that were shifted.
MediaMetadata - Web APIs
properties mediametadata.title returns or sets the title of the media to be played.
... mediametadata.artist returns or sets the name of the artist, group, creator, etc.
... mediametadata.album returns or sets the name of the album or collection containing the media to be played.
... mediametadata.artwork returns or sets an array of images associated with playing media.
MediaSettingsRange - Web APIs
properties mediasettingsrange.max returns the maximum value of this settings.
... mediasettingsrange.min returns the minimum value of this setting.
... mediasettingsrange.step returns 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); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error =...
Media Source API - Web APIs
returned by the htmlvideoelement.getvideoplaybackquality() method.
... htmlmediaelement.seekable when a mediasource object is played by an html media element, this property will return a timeranges object that contains the time ranges that the user is able to seek to.
... htmlvideoelement.getvideoplaybackquality() returns a videoplaybackquality object for the currently played video.
... audiotrack.sourcebuffer, videotrack.sourcebuffer, texttrack.sourcebuffer returns the sourcebuffer that created the track in question.
MimeTypeArray - Web APIs
the mimetypearray interface returns an array of mimetype instances, each of which contains information about a supported browser plugins.
... this object is returned by navigatorplugins.mimetypes.
... methods mimetypearray.item() returns the mimetype object with the specified index.
... mimetypearray.nameditem() returns the mimetype object with the specified name.
NameList - Web APIs
WebAPINameList
properties namelist.length read only methods namelist.contains() returns a boolean.
... namelist.containsns() returns a boolean.
... namelist.getname() returns a domstring.
... namelist.getnamespaceuri() returns a domstring.
NamedNodeMap - Web APIs
namednodemap.length read only returns the amount of objects in the map.
... namednodemap.getnameditem() returns a attr, corresponding to the given name.
... namednodemap.item() returns the attr at the given index, or null if the index is higher or equal to the number of nodes.
... namednodemap.getnameditemns() returns a attr identified by a namespace and related local name.
Navigator.requestMediaKeySystemAccess() - Web APIs
the navigator.requestmediakeysystemaccess() method returns 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 returned mediakeysystemaccess object's createmediakeys() method.
... return 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 returned promise is rejected with a domexception whose name indicates what kind of error occurred.
Node.firstChild - Web APIs
WebAPINodefirstChild
the node.firstchild read-only property returns the node's first child in the tree, or null if the node has no children.
... if the node is a document, it returns the first node in the list of its direct children.
...any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.
... to avoid the issue with node.firstchild returning #text or #comment nodes, parentnode.firstelementchild can be used to return only the first element node.
Node.localName - Web APIs
WebAPINodelocalName
the node.localname read-only property returns 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 returns 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 returns 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 return in the upper case for html elements in html doms.
Node.lookupNamespaceURI() - Web APIs
the node.lookupnamespaceuri() method accepts a prefix and returns the namespace uri associated with it on the given node if found (and null if not).
...if this parameter is null, the method will return the default namespace uri, if any.
... return value a domstring containing the the namespace uri.
... if the prefix is not found, it returns null.
NodeIterator.nextNode() - Web APIs
the nodeiterator.nextnode() method returns 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() returns the first node in the set.
... this method returns 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) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node specifications specification status comment domthe definition of 'nodeiterator.nextnode' in that specification.
NodeList.item() - Web APIs
WebAPINodeListitem
returns a node from a nodelist by index.
...a value of null is returned 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 returned by the item method.
... alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the second table in the dom specifications specification status comment domthe definition of 'nodelist: item' in that specification.
NotificationEvent - Web APIs
notificationevent.notification read only returns a notification object representing the notification that was clicked to fire the event.
... notificationevent.action read only returns the string id of the notification button the user clicked.
... this value returns 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) return client.focus(); } if (clients.openwindow) return 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 returns 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 return 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 returns 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(); returns 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 returned promise with a domexception.
... if (await supportsapplepay) { // show apple pay logo, for instance return; } // 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 return; } // 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 returns 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 returns null, even the developer provides a selected a shipping option.
... syntax // returns the id of the selected paymentshippingoption var shippingoption = request.shippingoption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched.
...=== 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); return { ...details, shippingoptions, total }; } catch (err) { return { ...details, error: `sorry!
performance.getEntriesByType() - Web APIs
the getentriesbytype() method returns a list of performanceentry objects for a given type.
... return 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 returned.
...performance.mark not supported"); return; } // 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 returns the time at which event dispatch started.
... performanceeventtiming.processingend returns the time at which the event dispatch ended.
... performanceeventtiming.cancelable returns the associated event's cancelable attribute.
... performanceeventtiming.target returns 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 returns "frame".
... performanceentry.name returns the document's address.
... performanceentry.starttime returns the timestamp when the frame was started.
... performanceentry.duration returns 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 returns "mark".
... performanceentry.name returns the name given to the mark when it was created via a call to performance.mark().
... performanceentry.starttime returns the domhighrestimestamp when performance.mark() was called.
... performanceentry.duration returns "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 returns "measure".
... performanceentry.name returns the name given to the measure when it was created via a call to performance.measure().
... performanceentry.starttime returns a timestamp given to the measure when performance.measure() was called.
... performanceentry.duration returns 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 returns a list of explicitly observed performance entry objects for a given filter.
... return 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 returned.
... if no argument is given, all entries are returned.
PerformanceObserverEntryList.getEntriesByName() - Web APIs
the getentriesbyname() method of the performanceobserverentrylist interface returns a list of explicitly observed performance entry objects for a given name and entry type.
... return 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 return.
...if no objects meet the specified criteria, an empty list is returned.
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 returns "paint".
... performanceentry.name returns either "first-paint" or "first-contentful-paint".
... performanceentry.starttime returns the timestamp when the paint ocurred.
... performanceentry.duration returns 0.
PerformanceResourceTiming.secureConnectionStart - Web APIs
the secureconnectionstart read-only property returns a timestamp immediately before the browser starts the handshake process to secure the current connection.
... if a secure connection is not used, the property returns zero.
... syntax resource.secureconnectionstart; return value if the resource is fetched over a secure connection, a domhighrestimestamp immediately before the browser starts the handshake process to secure the current connection.
... if a secure connection is not used, this property returns zero.
Performance API - Web APIs
the now() method returns a domhighrestimestamp whose value that depends on the navigation start and scope.
... the tojson() method returns a serialization of the performance object, for those attributes that can be serialized.
...the timing property returns 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 returns 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() returns 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() returns the recorded performance entries based on the specified name and optionally the performance type.
... getentriesbytype() returns 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 returns 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 returned by the window.navigator.plugins property.
... methods pluginarray.item returns the plugin at the specified index into the array.
... pluginarray.nameditem returns the plugin with the specified name.
... examples the following example function returns 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 return a position.
... the default value is infinity, meaning that getcurrentposition() won't return 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 return.
...if set to infinity the device must return a cached position regardless of its age.
RTCIceCandidatePairStats.availableIncomingBitrate - Web APIs
the rtcicecandidatepairstats property availableincomingbitrate returns a value indicative of the available inbound capacity of the network connection represented by the candidate pair.
... the value returned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair.
... the returned value doesn't take into account overhead introduced by underlying protocols, including ip, udp, or tcp.
... note: the returned 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 returns 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.
... return value a newly-created rtcpeerconnection object, configured as described by configuration, if specified; otherwise, configured to appropriate basic defaults.
RTCPeerConnection.addTrack() - Web APIs
return value the rtcrtpsender object which will be used to transmit the media data.
... reused senders this method may return 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 () { return 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 returned 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 returns 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 returns (they may still be in the process of stopping, but for all intents and purposes, they're stopped).
... once this method returns, the signaling state as returned by rtcpeerconnection.signalingstate is closed.
RTCPeerConnection.getStreamById() - Web APIs
the rtcpeerconnection.getstreambyid() method returns the mediastream with the given id that is associated with local or remote end of the connection.
... if no stream matches, it returns null.
... syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to return.
... // 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) return localstreams[i]; } for (i = 0; i < remotestreams.length; i++) { if (remotestreams[i].id == id) return remotestreams[i]; } } catch(e) {} return null; } ...
RTCPeerConnection.setLocalDescription() - Web APIs
the method takes a single parameter—the session description—and it returns a promise which is fulfilled once the description has been changed, asynchronously.
...they're interchangeable: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(offer); }); this is equivalent to: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(new rtcsessiondescription(offer)); }); for this reason, the rtcsessiondescription() constructor is deprecated.
... return 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 returns 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, returning 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) { return stats; } } return 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 returned.
... if no match is found, the function returns null.
Reporting API - Web APIs
indicated by a report.body property with a deprecationreportbody return value.
...indicated by a report.body property with a interventionreportbody return value.
...indicated by a report.body property with a crashreportbody return value.
...after the first time we call reportingobserver.takerecords(), which returns 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 returned is null.
... svganimationelement.getstarttime() returns 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() returns a float representing the current time in seconds relative to time zero for the given time container.
... svganimationelement.getsimpleduration() returns a float representing the number of seconds for the simple duration for this animation.
SVGEllipseElement - Web APIs
svgellipseelement.cx read only this property returns a svganimatedlength reflecting the cx attribute of the given <ellipse> element.
... svgellipseelement.cy read only this property returns a svganimatedlength reflecting the cy attribute of the given <ellipse> element.
... svgellipseelement.rx read only this property returns a svganimatedlength reflecting the rx attribute of the given <ellipse> element.
... svgellipseelement.ry read only this property returns a svganimatedlength reflecting the ry attribute of the given <ellipse> element.
SVGLengthList - Web APIs
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
...the return value is the item inserted into the list.
... getitem(in unsigned long index) svglength returns the specified item from the list.
... the returned item is the item itself and not a copy.
SVGLineElement - Web APIs
svglineelement.x1 read only returns an svganimatedlength that corresponds to attribute x1 on the given <line> element.
... svglineelement.y1 read only returns an svganimatedlength that corresponds to attribute y1 on the given <line> element.
... svglineelement.x2 read only returns an svganimatedlength that corresponds to attribute x2 on the given <line> element.
... svglineelement.y2 read only returns an svganimatedlength that corresponds to attribute y2 on the given <line> element.
SVGNumberList - Web APIs
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
...the return value is the item inserted into the list.
... getitem(in unsigned long index) svgnumber returns the specified item from the list.
... the returned item is the item itself and not a copy.
SVGPointList - Web APIs
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
...the return value is the item inserted into the list.
... getitem(in unsigned long index) svgpoint returns the specified item from the list.
... the returned item is the item itself and not a copy.
SVGStringList - Web APIs
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
...the return value is the item inserted into the list.
... getitem(in unsigned long index) domstring returns the specified item from the list.
... the returned item is the item itself and not a copy.
ServiceWorker - Web APIs
serviceworker.scripturl read only returns the serviceworker serialized script url defined as part of serviceworkerregistration.
... serviceworker.state read only returns the state of the service worker.
... it returns one of the following values: installing, installed, activating, activated, or redundant.
...the code listens for any change in the serviceworker.state and returns its value.
ServiceWorkerGlobalScope.onfetch - Web APIs
when fired, the code returns a promise that resolves to the first matching request in the cache object.
...it will return 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); return response; } console.log('no response found in cache.
... about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return 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 returns the event's data.
... serviceworkermessageevent.origin read only returns the origin of the service worker's environment settings object.
... serviceworkermessageevent.source read only returns a reference to the service worker that sent the message.
... serviceworkermessageevent.ports read only returns an array of messageport objects.
ServiceWorkerRegistration.getNotifications() - Web APIs
the getnotifications() method of the serviceworkerregistration interface returns 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 returned.
...if specified, only notifications that have this tag will be returned.
... return value a promise that resolves to a list of notification objects.
SpeechSynthesis.getVoices() - Web APIs
the getvoices() method of the speechsynthesis interface returns a list of speechsynthesisvoice objects representing all the available voices on the current device.
... return value a list (array) of speechsynthesisvoice objects.
... note: the spec wrongly lists this method as returning as a speechsynthesisvoicelist object, but this was in fact removed from the spec.
... example javascript function populatevoicelist() { if(typeof speechsynthesis === 'undefined') { return; } 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 returns the index position of the character in the speechsynthesisutterance.text that was being spoken when the event was triggered.
... speechsynthesisevent.elapsedtime read only returns the elapsed time in milliseconds after the speechsynthesisutterance.text started being spoken that the event was triggered at.
... speechsynthesisevent.name read only returns 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 returns the speechsynthesisutterance instance that the event was triggered on.
Storage Access API - Web APIs
in firefox, when the promise returned 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() returns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage.
... document.requeststorageaccess() returns 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 returned 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 returns a promise which will be fulfilled with an arraybuffer containing the derived bits.
... this method is very similar to subtlecrypto.derivekey(), except that derivekey() returns a cryptokey object rather than an arraybuffer.
... return 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(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user.
SubtleCrypto.digest() - Web APIs
it returns a promise which will be fulfilled with the digest.
... return 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); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings.
...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 return 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; return 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 returns true if the lengths are the same and returns false otherwise.
... function touches_in_target(ev) { // return true if all of the touches are within the target element; // otherwise return false.
... return (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); return 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 }) { return { 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 returns 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) { return i; } } return -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)) return; 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 returns the first value associated to the given search parameter.
... syntax urlsearchparams.get(name) parameters name the name of the parameter to return.
... return 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 return 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 returns a query string suitable for use in a url.
... note: this method returns the query string without the question mark.
... return value a domstring, without the question mark.
... (returns 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 returns 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; // returns:'#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 returned 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 returned the hash percent encoded.
URLUtilsReadOnly - Web APIs
urlutilsreadonly.origin read only returns a domstring containing the canonical form of the origin of the specific location.
... urlutilsreadonly.tostring() returns 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 returned 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 returned the hash percent encoded.
USBEndpoint - Web APIs
properties usbendpoint.endpointnumber returns 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 returns the direction in which this endpoint transfers data, one of: "in" - data is transferred from device to host.
... usbendpoint.type returns the type of this endpoint, one of: "bulk" - provides reliable data transfer for large payloads.
... usbendpoint.packetsize returns the size of the packets that data sent through this endpoint will be divided into.
USBInterface - Web APIs
properties usbinterface.interfacenumberread only returns the interface number of this interface.
... usbinterface.alternateread only returns the currently selected alternative configuration of this interface.
... usbinterface.alternatesread only returns an array containing instances of the usbalternateinterface interface describing each of the alternative configurations possible for this interface.
... usbinterface.claimedread only returns whether or not this interface has been claimed by the current page by calling usbdevice.claiminterface().
VideoTrack.label - Web APIs
WebAPIVideoTracklabel
the read-only videotrack property label returns a string specifying the video track's human-readable label, if one is available; otherwise, it returns an empty string.
...otherwise, an empty string ("") is returned.
... example this example returns 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 }); } }); return 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 returns information about the buffer.
...possible values: gl.buffer_size: returns a glint indicating the size of the buffer in bytes.
... gl.buffer_usage: returns a glenum indicating the usage pattern of the buffer.
... return value depends on the requested information (as specified with pname).
WebGLRenderingContext.getContextAttributes() - Web APIs
the webglrenderingcontext.getcontextattributes() method returns a webglcontextattributes object that contains the actual context parameters.
... might return null, if the context is lost.
... syntax gl.getcontextattributes(); return 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 returns 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 returns error information.
... return value constant description gl.no_error no error has been recorded.
... gl.context_lost_webgl if the webgl context is lost, this error is returned on the first call to geterror.
... afterwards and until the context has been restored, it returns gl.no_error.
WebGLRenderingContext.getTexParameter() - Web APIs
the webglrenderingcontext.gettexparameter() method of the webgl api returns information about the given texture.
...possible values: pname return type description possible return values available in a webgl 1 context gl.texture_mag_filter glenum texture magnification filter gl.linear (default value), gl.nearest.
... return value returns the requested texture information (as specified with pname).
... if an error occurs, null is returned.
Using DTMF with WebRTC - Web APIs
if it is, we call it on callerpc and get the first entry in the returned 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 returned 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); return callerpc.setlocaldescription(offer); }) .then(function() { log("setting receiver's remote description to the same as caller's local"); return receiverpc.setremotedescription(callerpc.localdescription) }) .then(function() { log("creating answer"); return receiverpc.createanswer(); }) .then(function(answer) { log("setting receiver's local description to " + answer.sd...
...p); return receiverpc.setlocaldescription(answer); }) .then(function() { log("setting caller's remote description to match"); return callerpc.setremotedescription(receiverpc.localdescription); }) .catch(err => log("error during negotiation: " + err.message)); } since the various methods involved in negotiating the connection return 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 returns 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 returns an xrsystem object through which the entire webxr device api is then exposed.
... navigator.xr read only this property, added to the navigator interface, returns the xrsystem object through which the webxr api is exposed.
... webxr interfaces xr the navigator.xr property returns the window's instance of xrsystem, which is the mechanism by which your code accesses the webxr api.
...returns 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 returned 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 return 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() { return 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 returns 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 returns it: function playsourcenode(audiocontext, audiobuffer) { const soundsource = audiocontext.createbuffersource(); soundsource.buffer = audiobuffer; soundsource.connect(audiocontext.destination); soundsource.start(); return 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 returned on: myfrequencyarray = myfrequencyarray.map(function(item, index) { return 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 returns a double representing the horizontal scroll amount.
... wheelevent.deltayread only returns a double representing the vertical scroll amount.
... wheelevent.deltazread only returns a double representing the scroll amount for the z-axis.
... wheelevent.deltamoderead only returns an unsigned long representing the unit of the delta* values' scroll amount.
Window.getDefaultComputedStyle() - Web APIs
return value the returned style is a cssstyledeclaration object.
... the object is of the same type as the object returned 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); // returns 'none' </script> notes the returned 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 return 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
WebAPIWindowlocation
the window.location read-only property returns 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; return; } 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; return; } _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; return; } if (_scrol...
...lid > -1) { clearinterval(_scrollid); _scrollid = -1; } } if (window.addeventlistener) { window.addeventlistener("scroll", _chkowner, false); } else if (window.attachevent) { window.attachevent("onscroll", _chkowner); } return 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
WebAPIWindowopener
the window interface's opener property returns a reference to the window that opened the window using open().
... in other words, if window a opens window b, b.opener returns a.
...if this window was not opened by being linked to or created by another, returns 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 return null.
WorkerGlobalScope.performance - Web APIs
the performance read-only property of the workerglobalscope interface returns a performance object to be used on the worker.
... syntax var perfobj = self.performance; return 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 return 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 return strange results, but this should be fixed soon.
XRInputSource.targetRaySpace - Web APIs
the read-only xrinputsource property targetrayspace returns an xrspace (typically an xrreferencespace) representing the position and orientation of the target ray in the virtual space.
... the native origin of the returned 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 returned 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 returned 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 return value of the xrsession property inputsources.
... entries() returns an iterator you can use to walk the list of key/value pairs in the list.
... each item returned is an array whose first value is the index and whose second value is the xrinputsource at that index.
... values() returns an iterator you can use to go through all the values in the list.
XRReferenceSpace - Web APIs
getoffsetreferencespace() creates and returns 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 returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace.
... the "interface" column in the table below indicates which of the two types is returned 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 returned object.
XRSystem - Web APIs
WebAPIXRSystem
methods in addition to inheriting methods from its parent interface, eventtarget, the xrsystem interface includes the following methods: issessionsupported() returns a promise which resolves to true if the browser supports the given xrsessionmode.
... requestsession() returns 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 returned promise resolves, we call a function onsessionstarted() to set up our session for rendering and so forth.
...when the returned 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 return its child offset within the parent.
...navigating previous requires returning 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 returned.
...not only can this save extra calls, but it will always return the visual line of text when used with the gettext methods and line boundaries.
Operable - Accessibility
for example, if you press enter/return on a focused button to open an options window, you should be able to close that window again and return 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, -1turn=1turn, 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 === "") { return false; } if (stringtotest === "inherit") { return false; } if (stringtotest === "transparent") { return 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)") { return true; } image.style.color = "rgb(255, 255, 255)"; image.style.color = stringtotest; return image.styl...
...*/ hsl(270,60%,70%) hsl(270, 60%, 70%) hsl(270 60% 70%) hsl(270deg, 60%, 70%) hsl(4.71239rad, 60%, 70%) hsl(.75turn, 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"; } return 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"; } return 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"; } return 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"; } return 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"; } return 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"; } return 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"; } return 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"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); specifications specification status comment css transitionsthe definition of 'transition-duration' in that specification.
exsl:node-set() - EXSLT
WebEXSLTexslnode-set
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes exsl:node-set() returns a node-set from a result tree fragment, which is what you get when you look at the xsl:variable instead of its select attribute to fetch a variable's value.
... 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 return the corresponding node-set.
... returns the node-set corresponding to the specified object.
regexp:match() - EXSLT
WebEXSLTregexpmatch
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes regexp:match() performs regular expression matching on a string, returning the submatches found as a result.
... the character flags are: g global match the submatches from every match in the string are returned.
... if this flag isn't specified, only the submatches from the first match are returned.
... returns 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
WebEXSLTsetdifference
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:difference() returns the difference between two node-sets.
... in other words, it returns 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 returned.
... returns a node-set containing the nodes that are in nodeset1 but not in nodeset2.
Media buffering, seeking, and time ranges - Developer guides
it returns 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; // returns 2 myaudio.buffered.start(0); // returns 0 myaudio.buffered.end(0); // returns 5 myaudio.buffered.start(1); // returns 15 myaudio.buffered.end(1); // returns 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 returns 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; // returns 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/return 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) { return true ; } alert("uncheck \"show html\"."); odoc.focus(); return 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()) { return; } 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;return true;}return 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 &lt;h1&gt;</option> <option value="h2">title 2 &lt;h2&gt;</option> <option value="h3">title 3 &lt;h3&gt;</option> <option value="h4">title 4 &lt;h4&gt;</opt...
Parsing and serializing XML - Developer guides
domparser constructs a dom tree by parsing a string containing xml, returning a xmldocument or document as appropriate based on the input data.
... xmlhttprequest loads content from a url; xml content is returned 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 returned 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 return 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 return 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 return their values as they are really used.
...however, the type idl attribute will return the string "text".
...when using idl attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength, it wants a number.
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
the text must not include carriage returns or line feeds.
... mozactionhint a string indicating the type of action that will be taken when the user presses the enter or return 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 return 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 return key while editing the field.
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
the text must not include carriage returns or line feeds.
... mozactionhint a string indicating the type of action that will be taken when the user presses the enter or return 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 return 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
WebHTMLElementinputtext
the text must not include carriage returns or line feeds.
... the value returned 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 return 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 return key while editing the field.
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
currenttime reading currenttime returns 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 returned.
...if no media is present on the element, or the media is not valid, the returned value is nan.
...specifically, the image would raster at these dimensions and naturalwidth/naturalheight on images would return the values specified in this attribute.
Range - HTTP
WebHTTPHeadersRange
the range http request header indicates the part of a document that the server should return.
...if the ranges are invalid, the server returns the 416 range not satisfiable error.
... the server can also ignore the range header and return 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 return.
HTTP response status codes - HTTP
WebHTTPStatus
203 non-authoritative information this response code means the returned meta-information is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy.
...the two mandatory methods, get and head, must never be disabled and should not return this error code.
... 413 payload too large request entity is larger than limits defined by server; the server might close the connection or return an retry-after header field.
...the only methods that servers are required to support (and therefore that must not return 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) { return this._getpropertynames(obj, true, false, this._enumerable); // or could use for..in filtered with hasownproperty or just this: return object.keys(obj); }, getownnonenumerables: function(obj) { return this._getpropertynames(obj, true, false, this._notenumerable); }, getownenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, true,...
... false, this._enumerableandnotenumerable); // or just use: return object.getownpropertynames(obj); }, getprototypeenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._enumerable); }, getprototypenonenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._notenumerable); }, getprototypeenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._enumerableandnotenumerable); }, getownandprototypeenumerables: function(obj) { return this._getpropertynames(obj, true, true, this._enumerable); // or could use unfiltered for..in }, getownandprototypenonenumerables: function(obj) { return this._getpropertynames(obj...
..., true, true, this._notenumerable); }, getownandprototypeenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, true, true, this._enumerableandnotenumerable); }, // private static property checker callbacks _enumerable: function(obj, prop) { return obj.propertyisenumerable(prop); }, _notenumerable: function(obj, prop) { return !obj.propertyisenumerable(prop); }, _enumerableandnotenumerable: function(obj, prop) { return 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)); return 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 return a + b + 11 } function bar(x) { let y = 3 return foo(x * y) } console.log(bar(7)) //returns 42 when calling bar, a first frame is created containing bar's arguments and local variables.
...when foo returns, the top frame element is popped out of the stack (leaving only bar's call frame).
... when bar returns, 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 return or an xhr request to return, 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 return value is not iterable (chrome) error type typeerror what went wrong?
...you must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method.
... const myemptyiterable = { [symbol.iterator]() { return [] // [] 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]() { return [][symbol.iterator]() } } array.from(myemptyiterable); // [] ...
Array.prototype.concat() - JavaScript
this method does not change the existing arrays, but instead returns a new array.
...if all valuen parameters are omitted, concat returns a shallow copy of the existing array on which it is called.
... return value a new array instance.
... the concat method does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays.
Array.prototype.fill() - JavaScript
it returns the modified array.
... return value the modified array, filled with value.
... fill is a mutator method: it will change the array itself and return it, not a copy of it.
... return 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
return value true if the value is an array; otherwise, false.
... description if the value is an array, true is returned; otherwise, false is.
...given a typedarray instance, false is always returned.
... if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return 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 return 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 returns 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 returned without using the separator.
... return value a string with all array elements joined.
... if arr.length is 0, the empty string is returned.
Array.prototype.pop() - JavaScript
the pop() method removes the last element from an array and returns that element.
... syntax arrname.pop() return 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 returns that value to the caller.
... if you call pop() on an empty array, it returns undefined.
Array.prototype.reverse() - JavaScript
syntax a.reverse() return value the reversed array.
... description the reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.
...the call to reverse() returns a reference to the reversed array a.
...the call to reverse() returns a reference to the reversed array-like object a.
Array.prototype.shift() - JavaScript
the shift() method removes the first element from an array and returns that removed element.
... syntax arr.shift() return 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 returns the removed value.
... if the length property is 0, undefined is returned.
Array.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the array.
... syntax arr.tosource() return value a string representing the source code of the array.
... description the tosource method returns the following values: for the built-in array object, tosource returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns 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(); //returns ['a', 'b', 'c'] specifications not part of any standard.
Array.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements.
... syntax arr.tostring() return value a string representing the elements of the array.
...for array objects, the tostring method joins the array and returns one string containing each array element separated by commas.
...object.prototype.tostring() will be called, and the resulting value will be returned.
get ArrayBuffer[@@species] - JavaScript
the arraybuffer[@@species] accessor property returns the arraybuffer constructor.
... description the species accessor property returns the default constructor for arraybuffer objects.
... examples species in ordinary objects the species property returns 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 return parent arraybuffer objects in your derived class methods: class myarraybuffer extends arraybuffer { // overwrite myarraybuffer species to the parent arraybuffer constructor static get [symbol.species]() { return arraybuffer; } } specifications specification ecmascript (ecma-262)the definition of 'get arraybuffer [ @@species ]' in that specification.
Atomics.notify() - JavaScript
it will return 0 on non-shared arraybuffer objects.
... return value returns the number of woken up agents.
... returns 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 return the new value (123).
BigInt.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns 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 returned are entirely implementation-dependent.
... return 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 returned.
Date.prototype[@@toPrimitive] - JavaScript
syntax date()[symbol.toprimitive](hint); return value the primitive value of the given date object.
... depending on the argument, the method can return either a string or a number.
... description the [@@toprimitive]() method of the date object returns a primitive value, that is either of type number or of type string.
... examples returning date primitives const testdate = new date(1590757517834); // "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('string'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('number'); // returns "1590757517834" testdate[symbol.toprimitive]('default'); // returns "date fri may 29 2020 14:05:17 gmt+...
Date.UTC() - JavaScript
it returns the number of milliseconds since january 1, 1970, 00:00:00 utc.
... return 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 returns the number of milliseconds between january 1, 1970, 00:00:00, universal time and the specified date and time.
... date.utc() returns a time value as a number instead of creating a date object.
Date.prototype.getFullYear() - JavaScript
the getfullyear() method returns the year of the specified date according to local time.
... syntax dateobj.getfullyear() return value a number corresponding to the year of the given date, according to local time.
... description the value returned by getfullyear() is an absolute number.
... for dates between the years 1000 and 9999, getfullyear() returns a four-digit number, for example, 1995.
Date.prototype.getTimezoneOffset() - JavaScript
the gettimezoneoffset() method returns the time zone difference, in minutes, from current locale (host system settings) to utc.
... syntax dateobj.gettimezoneoffset() return 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 returned.
... current locale utc-8 utc utc+3 return value 480 0 -180 the time zone offset returned is the one that applies for the date that it's called on.
Date.prototype.setMonth() - JavaScript
return 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 returned 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 return the new date.
... for example, if the current value is 31st august 2016, calling setmonth with a value of 1 will return 2nd march 2016.
Date.prototype.toISOString() - JavaScript
the toisostring() method returns 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() return 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) { return '0' + number; } return number; } date.prototype.toisostring = function() { return 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()) // returns 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 returns a string representing the specified date object.
... syntax dateobj.tostring() return value a string representing the given date.
...date.prototype.tostring() returns 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 returned by date.prototype.tostring was implementation dependent.
Date.prototype.toUTCString() - JavaScript
syntax dateobj.toutcstring() return value a string representing the given date using the utc time zone.
... description the value returned 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 return value varied according to the platform.
... the most common return 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 returns the function that invoked the specified function.
... it returns null for strict, async function and generator function callers.
... the special property __caller__, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.
... function myfunc() { if (myfunc.caller == null) { return 'the function was called from the top!'; } else { return 'this function\'s caller was ' + myfunc.caller; } } specifications not part of any standard.
Function.prototype.toString() - JavaScript
the tostring() method returns a string representing the source code of the function.
... syntax function.tostring() return value a string representing the source code of the function.
...for user-defined function objects, the tostring method returns 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() returns 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() returns 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 returns an object with two properties done and value.
... return 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 return value of the iterator.
... value any javascript value returned by the iterator.
Intl.DateTimeFormat - JavaScript
static methods intl.datetimeformat.supportedlocalesof() returns 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() returns an array of objects representing the date string in parts that can be used for custom locale-aware formatting.
... intl.datetimeformat.prototype.resolvedoptions() returns 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 returns 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() returns 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() returns a language-specific formatted string representing the elements of the list.
... intl.listformat.prototype.formattoparts() returns 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 returning 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 returns a substring of the locale's string representation, containing core information about the locale.
...the basename property returns basic, core information about the locale in the form of a substring of the complete data string.
... specifically, the property returns the substring containing the language, and the script and region if available.
... basename returns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar.
Intl.NumberFormat - JavaScript
static methods intl.numberformat.supportedlocalesof() returns 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() returns an array of objects representing the number string in parts that can be used for custom locale-aware formatting.
... intl.numberformat.prototype.resolvedoptions() returns 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 returned.
Intl.RelativeTimeFormat - JavaScript
static methods intl.relativetimeformat.supportedlocalesof() returns 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() returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
... intl.relativetimeformat.prototype.resolvedoptions() returns 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 returning 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 returns the map constructor.
... description the species accessor property returns the default constructor for map objects.
... examples species in ordinary objects the species property returns 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 return parent map objects in your derived class methods: class mymap extends map { // overwrite mymap species to the parent map constructor static get [symbol.species]() { return map; } } specifications specification ecmascript (ecma-262)the definition of 'get map [ @@species ]' in that specification.
Map.prototype.get() - JavaScript
the get() method returns a specified element from a map object.
... syntax mymap.get(key) parameters key the key of the element to return from the map object.
... return 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'); // returns "foo" mymap.get('baz'); // returns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification.
Math.abs() - JavaScript
the math.abs() function returns 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.
... return 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 returns nan.
... passing null, an empty string or an empty array returns 0.
Math.cos() - JavaScript
the math.cos() static function returns 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 return the cosine.
... return value the cosine of the given number.
... description the math.cos() method returns a numeric value between -1 and 1, which represents the cosine of the angle.
Math.imul() - JavaScript
the math.imul() function returns the result of the c-like 32-bit multiplication of the two parameters.
... return 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 return ((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; return 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() returns 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 returned.
... return value the smallest of the given numbers.
... if any one or more of the parameters cannot be converted into a number, nan is returned.
Math.pow() - JavaScript
the math.pow() function returns the base to the exponent power, that is, baseexponent.
... return value a number representing the given base taken to the power of the given exponent.
... description the math.pow() function returns 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 return 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 returns 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.
... return value the square root of the given number.
... if the number is negative, nan is returned.
... description if the value of x is negative, math.sqrt() returns nan.
Math.trunc() - JavaScript
the math.trunc() function returns the integer part of a number by removing any fractional digits.
... return value the integer part of the given number.
... polyfill if (!math.trunc) { math.trunc = function(v) { v = +v; if (!isfinite(v)) return v; return (v - v % 1) || (v < 0 ?
...v : 0); // returns: // 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) { return v < 0 ?
Number.isNaN() - JavaScript
return 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, return true.
... number.isnan = number.isnan || function isnan(input) { return 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 return 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 returns 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 returned.
... return 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 return value of that function.
Object.create() - JavaScript
return 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 returned.
... 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; return 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() { return 10; }, set: function(value) { console.log('setting `o.bar` to', value); } /* with es2015 accessors our code can look like this get() { return 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 returns 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 returned.
... return value an array of all symbol properties found directly upon the given object.
... as all objects have no own symbol properties initially, object.getownpropertysymbols() returns an empty array unless you have set symbol properties on your object.
Object.getPrototypeOf() - JavaScript
the object.getprototypeof() method returns the prototype (i.e.
... syntax object.getprototypeof(obj) parameters obj the object whose prototype is to be returned.
... return value the prototype of the given object.
... if there are no inherited properties, null is returned.
Object.isSealed() - JavaScript
return value a boolean indicating whether or not the given object is sealed.
... description returns 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() { return 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 return true.
Promise.prototype.finally() - JavaScript
the finally() method returns a promise.
... return value returns a promise whose finally handler is set to the specified function, onfinally.
... note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw.
... examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.error(error); /* this line can also throw, e.g.
handler.construct() - JavaScript
return value the construct method must return an object.
... const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { console.log('called: ' + argumentslist.join(', ')); return { 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) { return 1; } }); new p(); // typeerror is thrown the following code improperly initializes the proxy.
... const p = new proxy({}, { construct: function(target, argumentslist, newtarget) { return {}; } }); 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
return value the getownpropertydescriptor() method must return 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 return an object or undefined.
... const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); return { 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) { return undefined; } }); object.getownpropertydescriptor(p, 'a'); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[getownproperty]]' in that specification.
handler.isExtensible() - JavaScript
return value the isextensible() method must return 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 return the same value as object.isextensible(target).
... const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant.
... const p = new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification.
handler.preventExtensions() - JavaScript
return value the preventextensions() method must return 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 returns true if object.isextensible(proxy) is false.
... const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant.
... const p = new proxy({}, { preventextensions: function(target) { return true; } }); object.preventextensions(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[preventextensions]]' in that specification.
handler.setPrototypeOf() - JavaScript
return value the setprototypeof() method returns 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 return false, or it can throw an exception.
... approach 1: returning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself.
... const handlerreturnsfalse = { setprototypeof(target, newproto) { return false; } }; const newproto = {}, target = {}; const p1 = new proxy(target, handlerreturnsfalse); object.setprototypeof(p1, newproto); // throws a typeerror reflect.setprototypeof(p1, newproto); // returns false approach 2: throwing an exception the latter approach will cause any operation that attempts to mutate, to throw.
Reflect.getPrototypeOf() - JavaScript
it returns the prototype (i.e.
... return value the prototype of the given object.
... if there are no inherited properties, null is returned.
... description the reflect.getprototypeof method returns the prototype (i.e.
Reflect.ownKeys() - JavaScript
the static reflect.ownkeys() method returns an array of the target object's own property keys.
... return value an array of the target object's own property keys.
... description the reflect.ownkeys method returns an array of the target object's own property keys.
... its return value is equivalent to object.getownpropertynames(target).concat(object.getownpropertysymbols(target)).
RegExp.prototype[@@matchAll]() - JavaScript
the [@@matchall] method returns all matches of the regular expression against a string.
... return value an iterator.
...for example, the following two examples return same result.
... for example, to return an array instead of an iterator: class myregexp extends regexp { [symbol.matchall](str) { const result = regexp.prototype[symbol.matchall].call(this, str); if (!result) { return null; } else { return 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 returns the result of the replacement as a new string.
... return value a new string with some or all matches of a pattern replaced by a replacement.
... for example, following two examples return same result.
... var result = str; for (var i = 0; i < this.count; i++) { result = regexp.prototype[symbol.replace].call(this, result, replacement); } return 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
return value integer if successful, [@@search]() returns the index of the first match of the regular expression inside the string.
... otherwise, it returns -1.
...for example, the following two examples return the same result.
... class myregexp extends regexp { constructor(str) { super(str) this.pattern = str; } [symbol.search](str) { return 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 returns the regexp constructor.
... description the species accessor property returns the default constructor for regexp objects.
... examples species in ordinary objects the species property returns 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 return parent regexp objects in your derived class methods: class myregexp extends regexp { // overwrite myregexp species to the parent regexp constructor static get [symbol.species]() { return regexp; } } specifications specification ecmascript (ecma-262)the definition of 'get regexp [ @@species ]' in that specification.
RegExp.prototype.exec() - JavaScript
returns a result array, or null.
... return value if the match succeeds, the exec() method returns an array (with extra properties index and input; see below) and updates the lastindex property of the regular expression object.
... the returned 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 returns null, and sets lastindex to 0.
RegExp.prototype.toString() - JavaScript
the tostring() method returns a string representing the regular expression.
... syntax regexobj.tostring(); return value a string representing the given object.
...for regexp objects, the tostring() method returns 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 returns 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 returns the set constructor.
... description the species accessor property returns the default constructor for set objects.
... examples species in ordinary objects the species property returns 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 return parent set objects in your derived class methods: class myset extends set { // overwrite myset species to the parent set constructor static get [symbol.species]() { return set; } } specifications specification ecmascript (ecma-262)the definition of 'get set [ @@species ]' in that specification.
Set.prototype.delete() - JavaScript
return value returns 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'); // returns false.
...myset.delete('foo'); // returns true.
... myset.has('foo'); // returns false.
String.prototype.concat() - JavaScript
the concat() method concatenates the string arguments to the calling string and returns a new string.
... return 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 returns a new string.
... changes to the original string or the returned string don't affect the other.
String.prototype.includes() - JavaScript
the includes() method determines whether one string may be found within another string, returning true or false as appropriate.
...(defaults to 0.) return value true if the search string is found anywhere within the given string; otherwise, false if not.
...for example, the following expression returns false: 'blue whale'.includes('blue') // returns 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; } return 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
return value a string containing an <a> html element.
...the returned 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 returns the user to the mozilla developer network.
... var hottext = 'mdn'; var url = 'https://developer.mozilla.org/'; console.log('click to return to ' + hottext.link(url)); // click to return 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 returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
... return 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) return ''; // 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); return 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 returns 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 returned substring.
... return 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 return * @return {string} */ string.prototype.substr = function(substr) { return function(start, length) { // call the original method return 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 returns the calling string value converted to upper case, according to any locale-specific case mappings.
... return value a new string representing the calling string converted to upper case, according to any locale-specific case mappings.
... description the tolocaleuppercase() method returns the value of the string converted to upper case according to any locale-specific case mappings.
...the following can return 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 returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
... syntax str.touppercase() return value a new string representing the calling string converted to upper case.
... description the touppercase() method returns 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() { return 'abcdef'; } }); const b = string.prototype.touppercase.call(true); // prints out 'abcdef true'.
get TypedArray[@@species] - JavaScript
the typedarray[@@species] accessor property returns the constructor of a typed array.
... description the species accessor property returns the default constructor for typed array objects.
... examples species in ordinary objects the species property returns 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 return 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]() { return uint8array; } } specifications specification ecmascript (ecma-262)the definition of 'get %typedarray% [ @@species ]' in that specification.
TypedArray.prototype.filter() - JavaScript
return true to keep the element, false otherwise.
... return 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 returns a true value.
... function isbigenough(element, index, array) { return 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 returned in the last invocation of the callback, or initialvalue, if supplied (see below).
... return 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 returned without calling callback.
... examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduce(function(a, b) { return 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 returned in the last invocation of the callback, or initialvalue, if supplied (see below).
... return 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 returned without calling callback.
... examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { return 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() returns 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 return 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) { return; } 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
return 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); // returns false.
...ws.delete(window); // returns true.
... ws.has(window); // returns false.
WebAssembly.instantiate() - JavaScript
the returned promise resolves to both a compiled webassembly.module and its first webassembly.instance.
... the secondary overload takes an already-compiled webassembly.module and returns a promise that resolves to an instance of that module.
... return value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module.
... return value a promise that resolves to an webassembly.instance object.
encodeURIComponent() - JavaScript
return 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) { return encodeuricomponent(str).replace(/[!'()*]/g, function(c) { return '%' + 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) { return 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) { return encodeuricomponent(str).
Lexical grammar - JavaScript
\n u+000d carriage return <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 return 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 return the ecmascript specification mentions three rules of semicolon insertion.
...these statements with "no lineterminator here" rules are: postfixexpressions (++ and --) continue break return yield, yield* module return a + b // is transformed by asi into return; 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 return value of undefined.
... when used with function calls, it returns undefined if the given function does not exist.
...if obj.first is null or undefined, the expression automatically short-circuits, returning undefined.
... using optional chaining with function calls causes the expression to automatically return 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 returns 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 returning 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 returns the fulfilled value.
... function resolveafter2seconds(x) { return 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; returns this if the function doesn't return an object.
... the object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole new expression.
... if the constructor function doesn't explicitly return an object, the object created in step 1 is used instead.
... (normally constructors don't return 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); return true; } catch { return 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.
... returning from a finally-block if the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return 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'); return; } } catch (ex) { console.error('outer', ex.message); } })(); // output: // "inner" "oops" // "finally" the outer "oops" is not thrown because of the return in the finally-block.
... the same would apply to any value returned from the catch-block.
Autoplay guide for media and Web Audio APIs - Web media technologies
play() returns 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 return a value.
... returning a promise to allow you to determine success or failure of the operation was added more recently.
... if the promise returned 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 returns 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 returning 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 returned.
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) { return registration.pushmanager.getsubscription() .then(async function(subscription) { // registration part }); }) .then(function(subscription) { // subscription part }); it is a little bit more complicated than the service worker we saw in the js13kpwa demo.
... in the registration part, the code looks like this: if(subscription) { return subscription; } if the user has already subscribed, we then return the subscription object and move to the subscription part.
... return registration.pushmanager.subscribe({ uservisibleonly: true, applicationserverkey: convertedvapidkey }); now let's move to the subscription part — the app first sends the subscription details as json to the server using fetch.
...you can use the following ones:"); console.log(webpush.generatevapidkeys()); return; } 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() returns 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 returned by the .
...thus within all of the following three expressions the current function (not the entire expressions) returns the same node.
...returns the bar node, which may be different from the current node.
id - XPath
WebXPathFunctionsid
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the id function finds nodes matching the given ids and returns a node-set containing the identified nodes.
...the returned node set is the nodes corresponding to those ids.
...the returned node set is the nodes corresponding to those ids.
... returns 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 returns a string that is the rest of a given string after a given substring.
...part of this string will be returned.
...everything after the first occurrence ofneedle inhaystack will be returned.
... returns a string.
substring-before - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the substring-before function returns a string that is the part of a given string before a given substring.
...part of this string will be returned.
...everything before the first occurrence ofneedle inhaystack will be returned.
... returns a string.
system-property - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the system-property function returns an object representing the given system-property.
...the system-property function returns 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 returned.
... returns an object representing the given system-property.
Exported WebAssembly functions - WebAssembly
they are real functions in the previous example, the return 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 returned.
...testfunc.tostring() returns 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 returns 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") return; // 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) return; // 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 return a localized string in the locale currently set for firefox.
... if this function can't find the string referenced by the identifier parameter, it returns the identifier itself.
... returns 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() returns thumbnail data uri of the page currently loaded in this tab.
...optional returns worker : the worker object can be used to communicate with the content script.
... returns the mime type that the document currently loaded in the tab is being rendered as.
console/traceback - Archive of obsolete content
returns traceback : json representation of the traceback or null if not found.
... get() returns json : returns 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, returns 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) { return 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 returns 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 returns a promise which is fulfilled with the reply.
event/target - Archive of obsolete content
returns eventtarget : returns 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.
... returns eventtarget : returns the eventtarget instance removelistener(type, listener) removes an event listener for the given event type.
... returns eventtarget : returns 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(); } } return 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.
... returns string : a string containing the bytes read.
... if the stream is at the end, returns the empty string.
net/url - Archive of obsolete content
globals functions readuri(uri, options) reads a uri and returns a promise.
... options : object optional options: name type sync boolean if this option is set to true, the promise returned will be resolved synchronously.
... returns 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 returns 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 return favicon urls for visited sites.
... returns promise : a promise that resolves with the favicon url.
system/xul-app - Archive of obsolete content
returns boolean : true if the host application is name and false otherwise.
... returns boolean : true if the host application is one of the names and false otherwise.
... returns 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 returns its value.
... parameters fun : function the function to execute after the error message msg : string the error message to display returns * : the returned 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 returns.
util/object - Archive of obsolete content
returns object : the source object.
... extend(arguments) returns an object that inherits from the first argument and contains all of the properties from all following arguments, with precedence from right to left.
... returns object : the new, merged object.
util/uuid - Archive of obsolete content
if this argument is supplied, it will be converted to an nsid and returned.
... otherwise a new nsid will be generated and returned.
... returns 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 return 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 return, send the "text-entered" // message to main.js.
...type some text and press "return" and you should see the output in the console.
Localization - Archive of obsolete content
then it retrieves and returns 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 returns the identifier itself.
... then when the locale is "en-us", the system would fail to find a .properties file, and return "hello!".
File I/O - Archive of obsolete content
it returns the user-specified file as nsifile.
... return; } // the file data is contained within inputstream.
... return; } // 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); return; } 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) { return; } 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(); return 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); return 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 return null return node.lookupprefix(namespaceuri); } if (namespaceuri === null || namespaceuri === '') { return null; } switch (node.nodetype) { case 1: // node.element_node return _lookupnamespaceprefix(namespaceuri, node); case 9: // node.document_node return _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 return null; // type is unknown case 2: // node.attribute_node if (node.ownerelement) { return _lookupnamespaceprefix(namespaceuri, node.ownerelement); } return null; default: if (node.parentnode) { // entityreferences may have to be skipped to get to it return _lookupnamespaceprefix(namespaceuri, node.parentnode); } return 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) { return ...
...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 ) { return localname; } } } if (originalelement.parentnode) { // entityreferences may have to be skipped to get to it return _lookupnamespaceprefix(namespaceuri, originalelement.parentnode); } return 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 returns, 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; return 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; return 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, return 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)) return this; if (iid.equals(myilocation)) return this; components.returncode = components.results.ns_error_no_interface; return null; }, get locationfile() { return __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__ returns 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() { return components.id(`{${aboutpage_id}}`); } static get classdescription() { return aboutpage_description; } static get contractid() { return `@mozilla.org/network/protocol/about;1?what=${aboutpage_word}`; } static get queryinterface() { return xpcomutils.generateqi([ci.nsiaboutmodule]); } constructor() { object.freeze(this); } geturiflags(auri) { return 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; return channel; } } class factory { constructor(component) { this.component = component; this.register(); object.freeze(this); } createinstance(outer, iid) { if (outer) { throw cr.ns_error_no_aggregation; } return 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) { return } // ...
Jetpack Processes - Archive of obsolete content
it returns an array whose elements are the return 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 returns it.
... createsandbox() this creates a new javascript sandbox and returns 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() { return this._letfunc(this._plus); }, _plus: function(a, b) { return a + b; }, pop: function() { return 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 return 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) { return 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 return vk_return 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 returned from execution.
... addeventlistener("load", myaddon.init.bind(myaddon), true); settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() returns a new function.
... try { myaddon.doneaddtab(rv); } catch (ex) { /* might handle this */ } // return the original result return 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 returned from the remote server.
...let's assume that the xml returned 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 returns a dom document with the results of the transformation, whereas, the nsixsltprocessor.transformtofragment() method returns 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") { return; } 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 return to fetch easily-parsed stock quote data for google (ticker symbol goog).
...finally, we send the request to the server and return.
...we then fetch the result returned by the web server into the variable output from the xmlhttprequest.responsetext property.
Dehydra Function Reference - Archive of obsolete content
it also returns 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 return it as a string.
Drag and Drop Example - Archive of obsolete content
var boardobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appendflavour("text/unicode"); return 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 return 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"); return 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 returns an object that implements nsidragsession.
...the second argument, index, should be the index of the item to return.
... isdataflavorsupported(flavor) returns 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 returns 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 returned 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)); return; } } } </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 returns 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 returns 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 return 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 returned.
...the return value of the script represents the value of the property that will be returned to the requestor.
Using XPInstall to Install Plugins - Archive of obsolete content
errror conde: " + err); return err; } err = addfile(null, cult_version, component_file, componentsfolder, null); if (err != 0) { alert("installation of myplugin component failed.
...error conde: " + err); return 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); return 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); return 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"); return(false); } return(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() ; } return(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 // (returned from getfolder) "", // subdir name to create relative to fprogram true); // force flag logcomment("adddirectory() returned: " + err); // check return value if(err == success) { err = performinstall(); logcomment("performinstall() returned: " + err); } else cancelinstall(err); } else cancelinstall(insufficient_disk_space); // end main ...
dirGetParent - Archive of obsolete content
dirgetparent returns an object representing the parent directory of the current directory or file.
... returns a filespecobject if successful; null if not successful.
... example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); err = file.getparent(f) // returns "program" ...
windowsGetShortName - Archive of obsolete content
summary returns a path that conforms to the windows 8.3 file naming convention.
... returns a string with the windows shortname.
... if the path already conforms to 8.3, the return value is null.
addDirectory - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
... in some situations, adddirectory may return other errors.
getWinProfile - Archive of obsolete content
returns a winprofile object.
...for information on the returned object, see winprofile.
... this method returns null on unix and macintosh platforms.
getWinRegistry - Archive of obsolete content
returns a winreg object.
...for information on the returned object, see winreg.
... this method returns null on unix and macintosh platforms.
performInstall - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
... in some situations the method may return other errors.
registerChrome - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
... in some situations the method may return other errors.
getString - Archive of obsolete content
key the key in that section whose value to return.
... returns 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 return a list of keys in a section.
isKeyWritable - Archive of obsolete content
iskeywritable returns 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 returns 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 returned true } else { //iskeywritable returned false } ...
keyExists - Archive of obsolete content
keyexists returns 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 returns boolean value description if the user does not have read access to the given key, this will also return false.
... example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.keyexists("software\\mozilla")) { //keyexists returned true } else { //keyexists returned false } } ...
valueExists - Archive of obsolete content
valueexists returns whether a value for the given key exists.
... returns 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 returned true } else { //valueexists returned false } } ...
Methods - Archive of obsolete content
iskeywritable returns whether the given key is writable.
... keyexists returns whether the given key exists or is readable.
... valueexists returns 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 returns 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); return 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]; // returns 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) { return a < b ?
... getelementsbyattribute returns 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 returns 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 ) return type: element create a new notification and display it.
... if the return 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: return 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 ) return type: element removes the child item in the element at the specified index.
... the method returns the removed item.
... <script language="javascript"> function removeselecteditem(){ var mylistbox = document.getelementbyid('mylistbox'); if(mylistbox.selectedindex == -1){ return; // no item selected so return }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 return 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()) return; 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 return false, however the second time, the method will return 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 returns.
...<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")) return; 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 returns early if not.
textbox.label - Archive of obsolete content
otherwise it returns the value of the associated label element, if applicable.
... otherwise it returns the placeholder or emptytext property.
... note: prior to firefox 3, and always in thunderbird and seamonkey, the label property of an autocomplete textbox returns its value, for compatibility with the menulist element.
Rule Compilation - Archive of obsolete content
this will return a table of result records which are then used to generate output.
...var length = vbox.childnodes.length; this request to return 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 returned.
XML Templates - Archive of obsolete content
just place an expr attribute on the query element containing an xpath expression returns the set of results to output.
...for instance, the following query returns only those results for female people.
... <query expr="person[@gender='female']"/> as long as the expression returns 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) return num2; else return num1; } xbl: <method name="getmaximum"> <parameter name="num1"/> <parameter name="num2"/> <body> if (num1 &lt;= num2) return num2; else return num1; </body> </method> this function, getmaximum, returns the largest of the values, each passed as a parameter to the method.
...the function returns an array of elements, which is the anonymous content.
...in the returned 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 return 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") return "row "+row; else return "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ return false; }, isseparator: function(row){ return false; }, issorted: function(){ return false; }, getlevel: function(row){ return 0; }, getimagesrc: function(row,col){ return 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") return "row "+row; else return "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ return false; }, isseparator: function(row){ return false; }, issorted: function(){ return false; }, getlevel: function(row){ return 0; }, getimagesrc: function(row,col){ return 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 returned.
...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 returned.
...this causes only the descendants of this list to be returned.
Tree Selection - Archive of obsolete content
the first function returns the number of selection ranges there are.
...then, we iterate over the set of ranges, the number of which is returned by the getrangecount() function.
...it takes a row index as an argument and returns true if that row is selected.
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
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(); return true; } return 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 ) return type: no return value if the specified element is not currently visible to the user, the displayed items are scrolled so that it is.
... scrollbyindex( lines ) return type: no return value scrolls the contents of the arrowscrollbox by a certain number of lines.
... scrollbypixels( pixels ) return type: no return value scrolls the contents of the arrowscrollbox by a certain number of pixels.
editor - Archive of obsolete content
methods geteditor( window ) return type: nsieditor returns the editing interface for the editor which contains numerous methods for manipulating the document.
... gethtmleditor( window ) return type: nsihtmleditor returns the html editing interface for the editor which contains methods for manipulating an html document.
... makeeditable( editortype, waitforload ) return type: no return 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 returns the accessibility object for the element.
... selectedindex type: integer returns the index of the currently selected item.
...returns -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)) return 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; } return 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)) return this; throw components.results.ns_error_no_interface; }, /* nsimodule */ getclassobject : function mod_gch(acompmgr, acid, aiid) { if (acid.equals(class_id)) return 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) { return true; } }; function nsgetmodule(acompmgr, afilespec) { return 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 return 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 returned 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 return, contains the value returned by the script.
... returns true if the script was evaluated successfully, otherwise false.
... note: the caller must call npn_releasevariantvalue() to release the returned value when it's no longer needed.
NPN_GetProperty - Archive of obsolete content
<tt>result</tt> on return, contains the value of the specified property.
... returns true if the value was retrieved successfully, otherwise false.
... note: the caller must call npn_releasevariantvalue() to release the returned value when it's no longer needed.
NPN_IntFromIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns 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 returned.
... returns an integer corresponding to the specified <tt>identifier</tt>.
NPN_MemFlush - Archive of obsolete content
returns if successful, the function returns the amount of freed memory, in bytes.
... if no memory can be freed, the browser returns 0.
...to request that the browser free as much memory as possible, call npn_memflush() repeatedly until it returns 0.
NPN_PluginThreadAsyncCall - Archive of obsolete content
returns nothing.
...calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to npn_pluginthreadasynccall() returns immediately.
... after control returns to the browser, it is free to call the function with its argument from this thread.
NPN_PostURL - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
...npn_posturl is typically asynchronous: it returns immediately and only later handles the request.
NPN_Write - Archive of obsolete content
returns if successful, the function returns a positive integer representing the number of bytes written (consumed by the browser).
... if unsuccessful, the plug-in returns a negative integer.
...the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired.
NPP_New - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns an error code.
... if instance data was saved from a previous instance of the plug-in by the npp_destroy function, it is returned in the saved parameter for the current instance to use.
NPP_WriteReady - Archive of obsolete content
returns returns 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 returned by npp_writeready.
...if the plug-in is allocating memory for the entire stream at once (an as_file stream), it can return 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, returned by the function.
... returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns 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 returns with <tt>pr_io_timeout_error</tt>.
... if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call, the io function returns with <tt>pr_pending_interrupt_error</tt>.
...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 returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... return 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) return source.slice(0, length); var sourceview = new uint8array(source), destview = new uint8array(new arraybuffer(length)); destview.set(sourceview); return destview.buffer; }; } specifications specification status comment arraybuffer.prototype.transfer proposal draft stage 2 draft ...
Date.prototype.toLocaleFormat() - Archive of obsolete content
return 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() returns 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) { return this.format(formatstring); }; }()); } specifications not part of any standard.
VBArray.lbound - Archive of obsolete content
the vbarray.lbound method returns 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 returns 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 />"; } return (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 returns the highest index value used in the specified dimension of the vbarray.
... remarks if the vbarray is empty, the ubound method returns 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 />"; } return (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') { return 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() { return this.name; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return 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() { return 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 return 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.
... return value an iterator with the enumerable own and inherited properties of the target object.
... description the reflect.enumerate method returns an iterator with the enumerable own and inherited properties of the target object.
JavaObject - Archive of obsolete content
created by any java method which returns an object type.
... var thestring = new java.lang.string("hello, world"); thestring.startswith("hello"); // returns 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(); // returns 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() { return "exposed to the browser"; } function notexposed() { return "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 return "can't see me!"; } function exposed() { // runs on the server, callable from the browser return "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, returning 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(){ return 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 return 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); return 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(); return 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); return true; </body> </method> </implementation> </binding> ...
Troubleshooting XForms Forms - Archive of obsolete content
instance(...) not working be aware that the instance(...) returns an element node, and not the document node.
... submission not working if you are trying to replace="instance" make sure that the document being returned 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 return 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) { } }; return 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 return 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); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing.
... let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); return track; } let's also create a playtrack() function, which we can call once a file has been fetched.
... 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); } return 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 returns the tile contained at the specified column and row.
... if tiles were a 2d matrix, then the returned 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) { return 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 return (\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 returning to the beginning of the line.
... learn moreedit general knowledge newline on wikipedia carriage return 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() { return "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.
... return 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, return 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 return a value.
...an outer function is a function containing a function (addsquares in this case): function addsquares(a,b) { function square(x) { return x * x; } return square(a) + square(b); }; //using ecmascript 2015 arrow notation const addsquares = (a,b) => { const square = x => x*x; return square(a) + square(b); }; a recursive function is a function that calls itself.
... function loop(x) { if (x >= 10) return; loop(x + 1); }; //using ecmascript 2015 arrow notation const loop = x => { if (x >= 10) return; 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/return 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/return 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/return 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 return 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 return 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 return) 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 return 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 returns, and page breaks) and spaces percent-escaped.
...you'll return to links later on in the course when you start to look at styling them.
... next up for html, we'll return 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
returning 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 returns true will be displayed.
...this provides a default case that will apply when none of the media conditions return 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) { return 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 returned object is the same type as that which is returned when you grab a reference to an existing <img> element).
... now add the following code to the bottom of the javascript: function degtorad(degrees) { return degrees * math.pi / 180; }; function rand(min, max) { return 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 returns a random number between given lower and upper bounds, length and moveoffset vari...
What is JavaScript? - Learn web development
for example, let's return 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 returned 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 returned.
Object-oriented JavaScript for beginners - Learn web development
to start this off, we could return to our person object type from our first objects article, which defines the generic data and functionality of a person.
...i\'m ' + obj.name + '.'); }; return 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 return it?
...notice that it has all the features you'd expect in a function, although it doesn't return 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() { return 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 returned 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 returns 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)); return 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); return 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 return 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 return 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 return 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 return 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)) { return ns_error_unexpected; } dosomethingwith(internalevent->mbar); aevent->preventdefault(); return 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 return 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 returned.
... browser.safebrowsing.provider.idnum.keyurl an url that returns a private key to be used for encrypting of other requests.
...this request must be encrypted using the private key returned 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 return (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 returns 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() returns 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 return a cross process object wrapper that gives the chrome code synchronous access to the content.
...in this case, the shim will return a javascript object that looks somewhat like a window or a document for about:blank.
...it will return 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() { return 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)) return ci.nsicontentpolicy.accept; return 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); returns a domrequest for handling the screenshot request.
... mimetype optional a mime type specifying the format of the image to be returned; if not specified, the default used is image/jpeg.
... use image/png to capture the alpha channel of the rendered result by returning 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 returns it as json.
... syntax var instanceofdomrequest = instanceofhtmliframeelement.getstructureddata(); returns 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 returned, 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 returnvalue 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 returnvalue or returnvalue is false, no mozbrowseractivitydone event will be generated as of the landing of bug 1194525 in firefox os 2.5.
... details the details property returns 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 returns 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 returned.
... numberofmatches a number indicating the number of matches returned 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() { return new protocolparent(); } bool deallocpprotocol() { return 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: returnresult(nsstring result); __delete__(); } in this situation, there is a guaranteed sequence of messages that will be sent.
... following actor construction, the parent will send a kickoffquery message and presumably ignore the actor until it receives returnresult, at which point it will be deleted.
Introduction to Layout in Mozilla
creates a parser, returned 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 returned 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 returned “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), returns via reflow metrics parent frame sizes child frame and view based on child’s metrics n.b.
InstallListener
a listener may return false to cancel the download.
...a listener may return false to cancel the download.
...a listener may return false to cancel the install.
Add-on Manager
many functions in the add-on manager interface operate asynchronously returning results through callbacks passed to the functions.
...the callback may well only be called after the api function returns.
...any available update is returned as an addoninstall which is ready to be downloaded and installed.
FxAccountsProfileClient.jsm
constructor fxaccountsprofileclient() creates and returns a new fxaccountsprofileclient object.
... return value a newly created fxaccountsprofileclient object implementing the methods described in this article.
...parameters none return value promise resolves: object - successful response from the '/profile' endpoint.
OS.File.Info
object tomsg( in os.file.info value ) arguments returns 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 returns false for hard links) size the number of bytes in the file.
...on unix systems it was returning the last modified date and thus it was deprecated.
PerfMeasurement.jsm
return value a new perfmeasurement object configured to record the specified event types.
...return value if even one of the event types can be recorded, this will return true.
... otherwise, it returns false.
Localization formats
$array["getting started"] = "débuter avec firefox" the php code searches the array and returns the translation that is associated with the english term used by the web developer.
... <h1><?php echo ___("getting started")?></h1> function ___($str) { return $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 return to their repository to make changes.
JS::PerfMeasurement
static bool perfmeasurement::canmeasuresomething() this class method returns 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 returns true on linux when the <linux/perf_event.h> api is available (kernel 2.6.31 or later), and false everywhere else.
... it will return null if javascript passed in something with the wrong dynamic type.
NSPR's Position On Abrupt Thread Termination
all threads must unwind and return from their root function.
...this process continues until the thread either recovers from the malady or returns from the root function.
...the definition of the language c is such that returning 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 returns 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 returns pr_true.
... remark this function should return 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 returning.
... description by default, pr_close returns 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 returns 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 return its previous contents.
... returns the function returns the prior value of the referenced variable.
...the returned value is the value that was readbefore memory was updated.
PR_CEnterMonitor
returns the function returns one of the following values: if successful, the function returns 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 returns null.
...in the former case, the entry count is simply incremented and the function returns.
PR_CreateIOLayerStub
returns a new file descriptor for the specified layer.
...the file descriptor returned contains the pointer to the i/o methods table provided.
... the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack.
PR_CreatePipe
on return, this parameter contains the file descriptor for the read end of the pipe.
...on return, this parameter contains the file descriptor for the write end of the pipe.
... returns the function returns one of these values: if the pipe is successfully created, pr_success.
PR_CreateThread
returning from this function is the only way to terminate a thread.
... returns the function returns one of the following values: if successful, a pointer to the new thread.
... this pointer remains valid until the thread returns from its root function.
PR_DELETE
syntax #include <prmem.h> void pr_delete(_ptr); parameter _ptr the address of memory to be returned to the heap.
... returns nothing.
... description this macro returns 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 returned to the heap.
... returns nothing.
... description this macro returns memory to the heap when _ptr is not null.
PR FreeAddrInfo
destroys the praddrinfo structure returned 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 returned by a successful call to pr_getaddrinfobyname.
... returns the function doesn't return anything.
PR_GMTParameters
returns the time zone offset information that maps the specified prexplodedtime to gmt.
... returns a time parameters structure that expresses the time zone offsets at the specified time.
... this is a trivial function; for any input, it returns a prtimeparameters structure with both fields set to zero.
PR_GetConnectStatus
returns the function returns one of these values: if successful, pr_success.
... if pr_geterror returns 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 returns, call pr_getconnectstatus on the socket to determine whether the nonblocking connect has succeeded or failed.
PR_GetNameForIdentity
returns the function returns one of the following values: if successful, the function returns a pointer to the string associated with the specified layer.
... if unsuccessful, the function returns null.
...the string is copied by the runtime, and pr_getnameforidentity returns a pointer to that copy.
PR_GetProtoByName
buffer a pointer to a scratch buffer for the runtime to return result.
...on output, this structure is filled in by the runtime if the function returns pr_success.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetProtoByNumber
buffer a pointer to a scratch buffer for the runtime to return result.
...on output, this structure is filled in by the runtime if the function returns pr_success.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetSpecialFD
returns if the id parameter is valid, pr_getspecialfd returns a file descriptor that represents the corresponding standard i/o stream.
... otherwise, pr_getspecialfd returns 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 returned by pr_getspecialfd are owned by the runtime and should not be closed by the caller.
PR_Interrupt
returns the function returns 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 return to some control point.
...the interrupted thread returns pr_failure (-1) with an error code (see pr_geterror) for blocking operations that return a prstatus (such as i/o operations, monitor waits, or waiting on a condition).
PR_IntervalNow
returns the value of nspr's free-running interval timer.
... syntax #include <prinrval.h> printervaltime pr_intervalnow(void); returns a printervaltime object.
... description you can use the value returned by pr_intervalnow() to establish epochs and to determine intervals (that is, compute the difference between two times).
PR_JoinThread
returns the function returns 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 returns to the caller only after the target thread returns from its root function.
... pr_jointhread must not be called until after pr_createthread has returned.
PR_LIST_HEAD
returns the head of a circular list.
... returns a pointer to a list element.
... description pr_list_head returns the head of the specified circular list.
PR_LIST_TAIL
returns the tail of a circular list.
... returns a pointer to a list element.
... description pr_list_tail returns the tail of the specified circular list.
PR_NEW
returns 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 returned by the libc function.
... description this macro allocates memory whose size is sizeof(_struct) and returns a pointer to that memory.
PR_NEXT_LINK
returns the next element in a list.
... returns a pointer to a list element.
... description pr_next_link returns a pointer to the element following the specified element.
PR_NormalizeTime
returns nothing; the time parameter is altered by the callback function.
...on return, 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() returns, time will be in time zone b.
PR_OpenDir
returns if the directory is successfully opened, a prdir object is dynamically allocated and the function returns a pointer to it.
... if the directory cannot be opened, the function returns null.
... description pr_opendir opens the directory specified by the pathname name and returns 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
returns the preceding element in a list.
... returns a pointer to a list element.
... description pr_prev_link returns a pointer to the element preceding the specified element.
PR_TicksPerSecond
returns the number of ticks per second currently used to determine the value of printervaltime.
... syntax #include <prinrval.h> pruint32 pr_tickspersecond(void); returns an integer between 1000 and 100000 indicating the number of ticks per second counted by printervaltime on the current platform.
... description the value returned 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 returned from pr_loadlibrary.
... returns the function returns one of the following values: if successful, pr_success.
...after calling this function, future references to the library using its identity as returned by pr_loadlibrary will be invalid.
PR_Write
returns one of the following values: a positive number indicates the number of bytes successfully written.
...therefore, the return value is equal to either amount (success) or -1 (failure).
... note that if pr_write returns -1, some data (less than amount bytes) may have been written before an error occurred.
NSS_3.12.1_release_notes.html
returns a string that must be freed with port_free().
...pk11_getallslotsforcert (see pk11pub.h) pk11_getallslotsforcert returns 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 returns 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 - returns 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 return when clients send the status_request extension.
... bugs fixed in nss 3.15 this bugzilla query returns 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 returns 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 returns 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 return 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 returns 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 returns 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* return 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
MozillaProjectsNSSPKCS11FAQ
if you do not actually do the operation specified by that function, you can return 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 return value such as ckr_function_not_supported.
FC_DigestFinal
description fc_digestfinal finishes a multi-part digest operation by returning the complete digest and clearing the operation context.
... if pdigest is null the length of the digest is returned and fc_digestfinal may be called again with pdigest set to retrieve the digest.
... return value examples see also fc_digestinit, nsc_digestfinal ...
FC_Finalize
return value fc_finalize always returns ckr_ok.
... fc_finalize should check the preserved argument and return ckr_arguments_bad if preserved is not null.
... fc_finalize should return ckr_cryptoki_not_initialized if the library is not initialized.
FC_FindObjects
pusobjectcount [out] pointer to location to receive the number of returned handles.
... description fc_findobjects returns 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.
... return value examples see also fc_findobjectsinit, nsc_findobjects ...
FC_GetSessionInfo
pinfo [out] pointer to the ck_session_info structure to be returned.
...if the nss cryptographic module is in the error state, fc_getsessioninfo returns ckr_device_error.
... return value examples see also fc_closesession, nsc_opensession ...
FC_SignFinal
description fc_signfinal finishes a multi-part signing operation by returning the complete signature and clearing the operation context.
... if psignature is null the length of the signature is returned and fc_signfinal may be called again with psignature set to retrieve the signature.
... return value examples see also fc_signupdate, nsc_signfinal ...
NSS Key Functions
seckey_getdefaultkeydb seckey_destroyprivatekey seckey_getdefaultkeydb returns a handle to the default key database opened by nss_init.
... syntax include <key.h> include <keyt.h> seckeykeydbhandle *seckey_getdefaultkeydb(void); returns the function returns a handle of type seckeykeydbhandle.
...seckeykeydbhandle returns a handle to the key database opened by nss_init.
NSS tools : pk12util
the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file.
... return 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 returns the error no security module can perform the requested operation.
sslkey.html
seckey_getdefaultkeydb seckey_destroyprivatekey seckey_getdefaultkeydb returns a handle to the default key database opened by nss_init.
... syntax #include <key.h> #include <keyt.h> seckeykeydbhandle *seckey_getdefaultkeydb(void); returns the function returns a handle of type seckeykeydbhandle.
...seckeykeydbhandle returns a handle to the key database opened by nss_init.
NSS tools : pk12util
the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file.
... return 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 returns 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 returns an nsiproxyinfo if so.
...if this protocol handler does not support proxies, resolve returns 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 returned.
Rhino serialization
they're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 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() { return 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() { return 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 returning 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 return 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 returns a pointer to the newly created object.
... if the class of funobj is not function, then js::clonefunctionobject returns funobj itself.
... on failure, it returns null.
JS::GetDeflatedUTF8StringLength
this article covers features introduced in spidermonkey 38 returns the length of the char buffer required to encode given string as utf8.
... description js::getdeflatedutf8stringlength returns the length of the char buffer required to encode s as utf8.
... the returned length does not include the null-terminator.
JS::HandleValueArray
methods method description size_t length() const returns the length of the array.
... const value *begin() const returns the pointer to the first element of the array.
... js::handlevalue operator[](size_t i) const returns i-th element of the array.
JS::IsCallable
this article covers features introduced in spidermonkey 38 return whether the given function object is callable/a valid constructor.
... description js::iscallable returns whether the given function object is callable.
... js::isconstructor returns whether the given function object is a valid constructor.
JS::ToString
description js::tostring returns a string representation of a javascript value.
... on success, js::tostring returns a jsstring instance.
... on error or exception, it returns nullptr.
JSExtendedClass
return the current outer object.
...return the current inner object.
...creates and returns a new iterator.
JSExtendedClass.wrappedObject
the specific cases where this happens are: the default tostring method returns 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 returned.
...if it returns 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 returned as an integer jsval in *idp, if idp is non-null, and provided the number of enumerable properties is known.
...return the next jsid in the iteration using *idp.
... the return value is used to indicate success, with a value of false indicating failure.
JS_AddArgumentFormatter
on success, it returns js_true.
... otherwise it returns js_false.
... callback description the conversion function should return true on success, and return 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 returns js_true.
...if the property name you specify does not exist, js_aliaselement reports an error, and returns 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 returns js_false.
JS_AliasProperty
if the alias is successfully created and associated with the property, js_aliasproperty returns js_true.
...if the property name you specify does not exist, js_aliasproperty reports an error, and returns 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 returns js_false.
JS_AlreadyHasOwnProperty
if the property is found on obj, this sets *foundp to true and returns true.
... if the property is not found on obj, this sets *foundp to false and returns true (to indicate that no error occurred).
... if the search fails with an error or exception, this returns false.
JS_ClearContextThread
js_setcontextthread returns the thread id of the thread previously associated with this context.
... when the function is used properly, the return value is always zero, indicating that no thread was previously associated with the context.
...it returns the thread id of the last thread to be associated with this context.
JS_CloneFunctionObject
on success, js_clonefunctionobject returns a pointer to the newly created object.
... if the class of funobj is not function, then js_clonefunctionobject returns funobj itself.
... on failure, it returns null.
JS_ConvertArguments
if argc is less than the number of arguments required by format, js_convertargument reports an error and returns false.
... on success, js_convertargument returns true.
... if any argument conversion fails or there are not enough arguments, it returns false.
JS_DecompileFunctionBody
indent unsigned if it's not js_dont_pretty_print, js_decompilefunction returns pretty printed source code of the function.
...if successful, js_decompilefunctionbody returns a string containing the source code of the function body.
... otherwise, it returns null.
JS_DeleteElement
if deletion is successful, js_deleteelement returns true.
... otherwise it returns 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 returning false.
JS_DeleteElement2
if deletion is successful, js_deleteelement2 stores true to *succeeded and returns true.
... otherwise it returns 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 returns false.
JS_DeleteProperty2
if the hook returns false, the error is propagated.
... these functions return true on success, regardless of whether a property was actually deleted.
... on error or exception, the return value is false, and the value left in *succeeded is unspecified.
JS_EnterCompartment
on success, js_entercompartment returns a pointer to the previously entered compartment.
... to return to that compartment, pass it to js_leavecompartment.
... js_entercompartment is infallible, so a null return value doesn't indicate failure.
JS_Enumerate
on success, js_enumerate returns a pointer to the first element of an array of property ids.
...on error or exception, js_enumerate returns null.
... the property ids in the returned 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 return the address of that struct.
... otherwise, it returns nullptr.
... the lifetime of the error report struct that might be returned is the same as the lifetime of the exception object.
JS_FlattenString
description js_flattenstring flattens a string str and returns a pointer to jsflatstring.
... to catch errors, an opaque jsflatstring type is returned.
...example: // in a fallible situation jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) return 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&lt;jsobject*&gt; the object whose constructor is to be returned.
...if the result is a function object, js_getconstructor returns a pointer to that object.
... otherwise, it reports an error and returns null.
JS_GetContextThread
returns the id of the associated thread for a context.
... description js_getcontextthread returns the id of the thread currently associated with this context.
... if the context is not currently associated with any thread, the return value is 0.
JS_GetElement
find a specified numeric property of an object and return its current value.
...if not, it sets *vp to undefined and returns true (to indicate no error occurred).
... if the search fails with an error or exception, js_getelement returns false, and the value left in *vp is undefined.
JS_GetEmptyString
this article covers features introduced in spidermonkey 1.8.5 returns the empty string as a jsstring object.
... syntax jsstring * js_getemptystring(jsruntime *rt); name type description rt jsruntime * the runtime for which to return the empty string.
... description the returned empty string has the length 0.
JS_GetGlobalForObject
returns the global object for the given object.
... description js_getglobalforobject returns 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 returned by js_getglobalforobject.
JS_GetNaNValue
description js_getnanvalue returns 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 return value of a numeric operation when an argument is invalid or conversion fails.
... for example, 0/0 and math.sqrt(-1) both return nan.
JS_GetPropertyAttributes
if an error occurs, the return value is js_false, and the values left in *attrsp and *foundp are unspecified.
...the return 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 returns js_true.
JS_GetSecurityCallbacks
subsumes jssubsumesop a pointe to the function which returns whether the first principal subsumes the second.
... js_getsecuritycallbacks returns the runtime's current security callbacks.
... if the callbacks are default value, it returns 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 return a specified character from a string.
... on successful, js_getstringcharat returns true and stores the character code into *res, otherwise returns false.
... js_getflatstringcharat always succeeds, and returns the character code.
JS_GetStringChars
description js_getstringchars obsolete since javascript 1.8.5 returns a pointer to the first element of an array of jschars.
... the array returned 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 returns either a null-terminated string or null, indicating out-of-memory.
JS_HasArrayLength
on success, js_hasarraylength returns js_true, and *lengthp receives the current value of the length property.
... on failure, js_hasarraylength returns js_false, and the value left in *lengthp is undefined.
...this function may return 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 returns true.
... on error or exception, it returns false, and the value left in *bp is undefined.
...otherwise js_hasinstance returns false.
JS_HasOwnProperty
if the property exists, this function sets *foundp to true and returns true.
... if the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred).
... if an error occurs during the search, the function returns false, and the value of *foundp is undefined.
JS_HasProperty
if the property exists, this function sets *foundp to true and returns true.
... if the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred).
... if an error occurs during the search, the function returns false, and the value of *foundp is undefined.
JS_InitClass
instead it must create a new object and return it.
...on success, js_initclass returns a pointer to a js object that is the prototype for the newly initialized class.
... if js_initclass fails, it returns null.
JS_IsConstructing
js_isconstructing returns 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 returns js_false.
... ordinary non-constructor jsnatives have no need to call this; it always returns js_false for such functions.
JS_IsConstructor
this article covers features introduced in spidermonkey 24 return whether the given function is a valid constructor.
...if so, js_isconstructor returns true.
... otherwise it returns false.
JS_IsExceptionPending
description js_isexceptionpending returns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared.
... otherwise, it returns 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)) return false; js_clearpendingexception(cx); } /* ...
JS_IsNativeFunction
this article covers features introduced in spidermonkey 17 return whether the given function object equals the specified native function.
...if so, js_isnativefunction returns true.
... otherwise it returns false.
JS_LookupElement
if the property obj[index] exists, js_lookupelement sets *vp to the property's stored value and returns true.
... if no such property exists, js_lookupelement sets *vp to undefined and returns true (to indicate that no error occurred).
... on error or exception, js_lookupelement returns 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 return value is true.
... if neither obj nor any of its prototypes have such a property, *vp receives undefined and the return value is true (to indicate no error occurred).
... on error or exception (such as running out of memory during the search), the return value is false, and the value left in *vp is undefined.
JS_NewArrayObject
on success, js_newarrayobject returns the new array object.
... otherwise it reports an error as though by calling js_reportoutofmemory and returns 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 returned object in a gc root, and then populate its elements with js_setelement or js_defineelement.
JS_NewDouble
on success, js_newdouble returns a pointer to the new number.
... otherwise it returns null.
... the application must treat the returned pointer as read-only.
JS_NewGlobalObject
on success, js_newglobalobject returns a pointer to the new object.
... otherwise it returns 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 returning.
JS_NewRuntime
the returned jsruntime can be used from the calling thread only.
... (the engine may use helper threads internally, though.) on success, js_newruntime returns a pointer to the newly created runtime, which the caller must later destroy using js_destroyruntime.
... otherwise it returns null.
JS_NewUCString
description js_newstring creates and returns 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 return a pointer to the new string.
... on error or exception, they return null.
JS_NewStringCopyZ
on success, js_newstringcopyz returns a pointer to the new javascript string.
... on error, it returns null.
... if s is null, an empty javascript string is returned.
JS_NextProperty
iterobj js::handleobject the opaque iterator object returned by a previous call to js_newpropertyiterator.
... description on success, js_nextproperty returns 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 returns false, and the value left in *idp is undefined.
JS_PushArguments
if successful, js_pusharguments would return 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 returns 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 returns null.
JS_PutEscapedString
returns the length of the written output, not including the nul.
... thus, a return value of size or more means that the output was truncated.
... if buffer is null, just returns the length of the output.
JS_SetOptions
this function returns 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 return 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 returning from the outermost api call, prevent uncaught exceptions from being converted to error reports.
JS_SuspendRequest
savedepth jsrefcount (only in js_resumerequest) the valued returned by the matching js_suspendrequest call.
...the return value is the number of nested requests that were suspended.
...the savedepth argument must be the value returned by the matching js_suspendrequest call.
JS_ValueToNumber
js_valuetonumber always succeeds in this case, returning js_true.
... on success, js_valuetonumber stores the converted value in *dp and returns js_true.
... on error or exception, it returns js_false, and the value left in *dp is undefined.
JS_ValueToString
if that method returns a primitive value, the value is converted to a string as described above and conversion succeeds.
... on success, js_valuetostring returns a pointer to a string.
... on error or exception, it returns 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 returns a newly allocated, writable buffer which the application must js_free.
... a new gc parameter, jsgc_stackpool_lifespan, controls how eagerly spidermonkey returns unused memory back to the system.
Using the Places favicon service
nsifaviconservice.getfaviconimageforpage() returns an annotation uri for the favicon for a given page, and nsifaviconservice.getfaviconlinkforicon() returns an annotation uri for the given favicon.
...if the page has no favicon, or we have never heard of the page, this function will return 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 returned by the annotation service's protocol handler.
extIApplication
boolean quit() return value boolean value indicating whether the shutdown was successful.
... boolean restart() return value boolean value indicating whether the restart was successful.
... void getextensions(extiextensionscallback acallback) return 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); return ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & aname) { mname.assign(aname); return ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::add(print32 a, print32 b, print32 *_retval) { *_retval = a + b; return 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 returned will be the javascript value undefined.
... a new xpcom component instance can be created from the returned 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 return 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
return value the module's global object.
... use of the return 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); ...returns 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); ...returns false.
Components.utils
createarrayin() removed in gecko 31 returns an array created in specified compartment.
... getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example).
... nondeterministicgetweakmapkeys() return 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 returns the argument you passed in.
... returns if the argument obj is an xray, this function returns 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 returns 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 returns a reference to the xpcom component manager.ns_getcomponentregistrarthe ns_getcomponentregistrar function returns a reference to the xpcom component registrar.ns_getmemorymanagerthe ns_getmemorymanager function returns a reference to the xpcom memory manager.ns_getservicemanagerthe ns_getservicemanager function returns 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 returned by an xpcom function; these are typically error or status codes.
... for a list of defined result values, see error codes returned by mozilla apis.
operator=
return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
operator+=
return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
nsACString
methods beginreading the beginreading function returns a const pointer to the first element of the string's internal buffer.
... endreading the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer.
... length the length function returns the number of storage units in the string's internal buffer (not including the null-terminator if present).
operator=
return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
... return values this operator returns a reference back to the object being modified to allow operator chaining.
nsAString
methods beginreading the beginreading function returns a const pointer to the first element of the string's internal buffer.
... endreading the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer.
... length the length function returns 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 returns a reference to xpcom's global nsimemory object.
... static nsimemory* getglobalmemoryservice(); return values this function returns nsnull if the global memory manager does not exist or could not be initialized.
... remarks this function returns the same value as the ns_getmemorymanager function.
imgILoader
channelpolicy return value loadimagewithchannel() start the load and decode of an image.
... return value supportimagewithmimetype() checks if a decoder for the an image with the given mime type is available.
... return value true if a decoder is available, false otherwise.
mozISpellCheckingEngine
this will be either element from the array returned 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 returning.
... return value returns true if word is spelled correctly according to the dictionary attribute, and returns false if word is misspelled.
nsIAccessNode
return value the nth nsiaccessnode child.
... return value the nsidomcssprimitivevalue computed style value.
... return value the computed style value.
nsIAccessibleEvent
may return null if no accessible is available.
...may return null if accessible for event has been shut down.
... isfromuserinput boolean returns true if the event was caused by explicit user input, as opposed to purely originating from a timer or mouse movement.
nsIAccessibleHyperText
return value an nsiaccessiblehyperlink object.
... return value the index of the link if it's presented on the given character index, otherwise -1.
... return 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 returns the state of accessible (see constants declared in nsiaccessiblestates).
...return value returns true if the state is turned on.
...return value returns 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 returns length of changed text.
... start long returns offset of changed text in accessible.
...return value true if text was inserted, otherwise false.
nsIArray
if the interface in question had intended the array to be modified, it would have returned an nsimutablearray!
...return value a new enumerator positioned at the start of the array.
... return 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 return 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() return true.
...the error code returned 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 return 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() return true.
...the error code returned 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 return, this parameter should contain the domain entered by the user.
...on return, this parameter should contain the password entered by the user.
...on return, this parameter should contain the username entered by the user.
nsIAuthPrompt
return value true for ok, false for cancel.
... return value true for ok, false for cancel.
... return value true for ok, false for cancel.
nsIBlocklistService
return value the blocklist state of the add-on, one of the constants.
... return value the blocklist state of the plugin, one of the constants.
... return 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 return value deletecrl() delete the crl.
...return value importcrl() import a crl into the certificate database.
...boolean updatecrlfromurl( in wstring url, in wstring key ); parameters url key return 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 return 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 returned.
...if the cache entry is validated, then a descriptor for that entry will be created and returned.
nsIContentSecurityPolicy
return 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 return 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 return value ...
nsIContentViewManager
methods getcontentviewsin() returns 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 return this parameter indicates the number of nsicontentview objects returned in the aresult array.
... aresult on return, an array of nsicontentview objects representing the content views in the specified rectangle.
nsICookiePermission
return value one of the nscookieaccess values: access_default, access_allow, or access_deny.
... return value true if the cookie can be set.
... return value the originating uri.
nsICryptoHMAC
acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string.
... if false, then the returned value is binary data.
... return value a hash of the data that was read by this object.
nsIDOMFontFaceList
methods item() returns 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 return.
... return value an nsidomfontface object representing a single font face.
nsIDOMHTMLAudioElement
returns the current offset of the audio stream, specified as the number of samples that have played since the beginning of the stream.
...return value an unsigned 64-bit value indicating how many audio samples have been played since the stream began playing.
... return value the actual number of bytes written to the stream.
nsIDOMXPathEvaluator
return value an xpath expression, as an nsidomxpathexpression object.
... return value a name space resolver.
... return value an xpath result.
nsIDirectoryServiceProvider
persistent true if the returned file will be cached by directory service.
... return value the nsifile represented by the property.
... __definegetter__("currdir", function getcurrdir() { return components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsidirectoryserviceprovider) .getfile("curworkd",{}).path; }); test it with to see the magic happen.
nsIEditor
returns true if the document has no *meaningful* content.
...returns true if the document is modifed and needs saving.
...returns true if we have a document that is not marked read-only.
nsIEditorMailSupport
return value an nsisupportsarray containing the img and object tags of the current document.
...(vs plaintext) return value the nsidomnode which was inserted.
... return value the nsidomnode which was inserted.
nsIExternalHelperAppService
return 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 returned stream listener.
... return value a nsistreamlistener which the caller should pump the data into.
nsIMessageListener
if the message is synchronous, the possible return value is returned as json (will be changed to use structured clones).
... when there are multiple listeners to synchronous messages, each listener's return value is sent back as an element in an array.
... undefined return values show up as undefined values in the array.
nsIMimeConverter
return value the value of the property.
... return value the value of the property.
... return value the value of the property.
nsIMsgSearchCustomTerm
* * @return true if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailable /** * is this custom term available?
... * * @return 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 * * @return 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.) * * @return 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) returns an array of the names of all installed printers.
... void enumerateprinters( out pruint32 acount, [retval, array, size_is(acount)] out wstring aresult ); parameters acount returns number of printers returned.
... aresult returns 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 returns false.
...exceptions thrown missing exception missing description getnumberofmessagesfortext() returns the number of multi-part sms needed for a given text (160 characters for one sms).
... return value unsigned short.
nsIScreen
methods getavailrect() returns a rectangle indicating the portion of the screen that is available for use.
... note: this returns a rectangle representing the region of the screen that is available for application use.
... getrect() returns a rectangle indicating the entire screen's coordinate space.
nsIScrollable
return value getdefaultscrollbarpreferences() long getdefaultscrollbarpreferences( in long scrollorientation ); parameters scrollorientation an integer representing the orientation of the scrollbar.
... return 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 //returns true if the vertical scrollbar is displayed h.value //returns true if the horizontal scrollbar is displayed ...
nsIServerSocket
attributes attribute type description port long returns the port of this server socket.
... native code only!getaddress returns the address to which this server socket is bound.
... return value the network address to which the socket is bound.
nsISmsService
return value a smsmessage getnumberofmessagesfortext() unsigned short getnumberofmessagesfortext( in domstring text ); parameters text a domstring text to check.
... return value the number of multi-part sms needed for a given text (160 characters for one sms).
... boolean hassupport(); return value boolean.
nsIStructuredCloneContainer
methods deserializetovariant() deserialize the object this container holds, returning it wrapped as an nsivariant.
...return value an nsivariant.
...return value a base-64-encoded string.
nsISupports
return value an integer value that is generally ignored.
... note: the interface pointer, aresult, returned by queryinterface must be released by a call to release() when it is no longer needed.
...return value an integer value that is generally ignored.
nsISyncMessageSender
returns an array containing return values from each listener invoked.
... principal nsiprincipal returns array: an array of structured clones of the objects returned by all the listeners to this message, one element for each listener.
... principal nsiprincipal returns array: an array of structured clones of the objects returned 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; } return true; } catch (e) { return 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)) { return false; } ...
... return value if this handles the notification normally or does nothing, it should return true.
nsITraceableChannel
method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, returning the listener previously assigned to the channel.
... return 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)) { return 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 returns immediately after the transaction's dotransaction() method is called, no references to the transaction are maintained.
...this method returns a boolean value that indicates the merge result.
... return 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 returns an nsiatom for the column, making it fast to do comparisons.
...return value the next nsitreecolumn in the nsitreecolumns.
...return value the previous nsitreecolumn in the nsitreecolumns.
nsITreeContentView
return value a non-negative integer row index if the row was found within the tree.
... returns -1 if the item was not found.
...nsidomelement getitematindex( in long index ); parameters index the row index for which to get the item return value the nsidomelement item.
nsIURLFormatter
return value the formatted url.
...if the preference value cannot be retrieved, a fatal error is reported and the "about:blank" url is returned.
... return value the formatted url returned by formaturl(), or "about:blank".
nsIWebBrowserChrome
void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to return from showasmodal().
...return value true if it's a modal window.
...return value note: the function error code returned by this corresponds to the status value specified in exitmodaleventloop.
nsIWorkerFactory
dom/interfaces/threads/nsidomworkers.idlscriptable creates and returns 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() returns a new chromeworker that will run a specified script.
... return value an nsiworker object representing the new chromeworker.
nsIXULTemplateResult
return value the value for the variable or a null string if it has no value.
...this method may return null for a variable, even if getbindingfor() returns a non-null value for the same variable.
... return value the value for the variable or null if it has no value.
NS ENSURE TRUE
summary macro returns return-value if expr evaluates to false.
... syntax ns_ensure_true( expr, return-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) return ns_error_out_of_memory; // thou shalt not return ns_error_failure..
... int i = 3; ns_ensure_true(i == 3, ns_error_failure); return ns_ok; } char* mozmyclass::dostuff() { char* bar = new char[321]; ns_ensure_true(bar, nsnull); return bar; } ...
NS_CStringCloneData
« xpcom api reference summary the ns_cstringclonedata function returns a null-terminated, heap allocated copy of the string's internal buffer.
... return values the ns_cstringcutdata function returns a pointer to a null-terminated, heap allocated buffer on success.
... on failure it returns nsnull.
NS_CStringContainerInit2
return values the ns_cstringcontainerinit function returns ns_ok if successful.
... otherwise, it returns an error code.
...this is significant as it allows the programmer to be certain that ns_cstringgetdata will return a null-terminated character array.
NS_CStringCopy
return values the ns_cstringcopy function returns ns_ok if successful.
... otherwise, it returns an error code.
... example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacstring& avalue) { return ns_cstringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsacstring& avalue) { return ns_cstringcopy(mvalue, avalue); } history this function was frozen in mozilla 1.7.
NS_StringCloneData
« xpcom api reference summary the ns_stringclonedata function returns a null-terminated, heap allocated copy of the string's internal buffer.
... return values the ns_stringcutdata function returns a pointer to a null-terminated, heap allocated buffer on success.
... on failure it returns nsnull.
NS_StringCopy
return values the ns_stringcopy function returns ns_ok if successful.
... otherwise, it returns an error code.
... example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsastring& avalue) { return ns_stringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsastring& avalue) { return ns_stringcopy(mvalue, avalue); } history this function was frozen for mozilla 1.7.
XPCOM reference
many xpcom pages return an nsresult.
... prior to gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16), this was an integer that simply returned an error code.
...this causes compile-time errors to occur when improper values are returned 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| return rv; } editors note: move this discussion to the efficiency section, and link to it from here.
... any xpcom function that returns an interface pointer, i.e., a `getter', must have already addrefed that pointer.
...if the getter returns 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) return 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) { // return 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 return 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): return a string (or null) getcelltext(row, col): return a string representing the actual text to display in the column from nsimsgcustomcolumnhandler: getsortstringforrow(hdr): return the string value that the column will be sorted by getsortlongforrow(hdr): return the long value that the column will be sorted by isstring(): return true / false warning!
...though they sound similar you may not want to return 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); return hdr.getstringproperty("replyto"); }, getsortstringforrow: function(hdr) {return hdr.getstringproperty("replyto");}, isstring: function() {return true;}, getcellproperties: function(row, col, props){}, getrowproperties: function(row, props){}, getimagesrc: function(row, col) {return null;}, getsortlongforrow: function(hdr) {return 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 returns 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 returned 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 returned from canvasrenderingcontext2d.getimagedata is a uint8clampedarray view for an arraybuffer.
...further, it returns 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, // return 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 return 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 return to search.
... if the string exists in any of the files in the project, the search will return 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 return 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 return 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); } } return 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; return; } // 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); } } return 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..."); return primes; } the waterfall's output will look something like this: the marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.
... 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) { return 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..."); return primes; } in the waterfall you'll now see something like this: ...
Accelerometer - Web APIs
properties accelerometer.x read only returns a double containing the acceleration of the device along the device's x axis.
... accelerometer.y read only returns a double containing the acceleration of the device along the device's y axis.
... accelerometer.z read only returns 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 returned from getfloatfrequencydata() parameters array the float32array that the frequency domain data will be copied to.
... return 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 returned 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
WebAPIAudioNode
properties audionode.context read only returns the associated baseaudiocontext, that is the object representing the processing graph the node is participating in.
... audionode.numberofinputs read only returns the number of inputs feeding the node.
... audionode.numberofoutputs read only returns the number of outputs coming out of the node.
AudioParam.value - Web APIs
WebAPIAudioParamvalue
setting value has the same effect as calling audioparam.setvalueattime with the time returned by the audiocontext's currenttime property..
...one solution is to use the math.fround() method, which returns 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 returns 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 returned 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 () { return [{ 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 ?
... } }) return 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 returns 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 returns 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 }); } }); return tracklist; } specifications specification status comment html living standardthe definition of 'audiotrack.language' in that specification.
AudioTrackList.getTrackById() - Web APIs
the audiotracklist method gettrackbyid() returns the first audiotrack object from the track list whose id matches the specified string.
... return 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 returns null.
AudioWorkletGlobalScope.registerProcessor - Web APIs
return 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 return an array of audioparamdescriptor-based objects.
... // test-processor.js class testprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { return 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 returns the associated audioparammap — that is, a map-like collection of audioparam objects.
... // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { return [{ 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 ?
... } }) return 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 returns an iterable of audioparamdescriptor-based objects.
... // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { return [{ 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 ?
... } }) return 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 returns true and returns false otherwise.
... window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) return; 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 // return 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 returns an array of domstring items containing the platforms on which the event was dispatched.
... beforeinstallpromptevent.userchoice read only returns a promise that resolves to a domstring containing either "accepted" or "dismissed".
...this method returns a promise.
BeforeUnloadEvent - Web APIs
when a non-empty string is assigned to the returnvalue 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.returnvalue = "\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).returnvalue = confirmationmessage; // gecko + ie return 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
WebAPIBlobarrayBuffer
the arraybuffer() method in the blob interface returns a promise that resolves with the contents of the blob as binary data contained in an arraybuffer.
... returns 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() returns a promise rather than being an event-based api, as is the case with the filereader interface's method.
Blob.slice() - Web APIs
WebAPIBlobslice
the blob interface's slice() method creates and returns 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 returned blob has size 0 and contains no data.
... return 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
WebAPIBlobtext
the text() method in the blob interface returns a promise that resolves with a string containing the contents of the blob, interpreted as utf-8.
... returns a promise that resolves with a usvstring which contains the blob's data as a text string.
...there are two key differences: blob.text() returns a promise, whereas filereader.readastext() is an event based api.
Bluetooth.requestDevice() - Web APIs
the bluetooth.requestdevice() method of the bluetooth interface returns a promise to a bluetoothdevice object with the specified options.
... if there is no chooser ui, this method returns the first device matching the criteria.
...}) returns 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 returns true while this script execution environment is connected to this.device.
... bluetoothremotegattserver.getprimaryservice() returns a promise to the primary bluetoothgattservice offered by the bluetooth device for a specified bluetoothserviceuuid.
... bluetoothremotegattserver.getprimaryservices() returns a promise to a list of primary bluetoothgattservice objects offered by the bluetooth device for a specified bluetoothserviceuuid.
Body.text() - Web APIs
WebAPIBodytext
it returns a promise that resolves with a usvstring object (text).
... return 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) { return 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() returns a promise that resolves to a double, indicating the worst-case background operation cost of the provided background operation.
... budgetservice.getbudget() returns a promise that resolves to an array of budgetstate objects, indicating the expected state of the budget at times in the future.
... budgetservice.reserve() returns 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 returns a domstring with the name of the prefix associated to this namespace.
... if there is no such prefix, returns null.
... syntax var prefix = cssnamespacerule.prefix returns a domstring containing the prefix associated to this namespace.
CSSNamespaceRule - Web APIs
it has some specific properties: cssnamespacerule.namespaceuri returns a domstring containing the text of the uri of the given namespace.
... cssnamespacerule.prefix returns a domstring with the name of the prefix associated to this namespace.
... if there is no such prefix, returns null.
CSSNumericValue.equals() - Web APIs
the equals() method of the cssnumericvalue interface returns a boolean indicating whether the passed value are strictly equal.
... to return a value of true, all passed values must be of the same type and value and must be in the same order.
... return value a boolean.
CSSNumericValue.type - Web APIs
the type() method of the cssnumericvalue interface returns the type of cssnumericvalue, one of angle, flex, frequency, length, resolution, percent, percenthint, or time.
... return value a cssnumerictype object.
... examples let mathsum = css.px("23").sub(css.percent("4")).sub(css.cm("3")).sub(css.in("9")); // returns 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 returns the item's position along the web page's horizontal axis.
... csspositionvalue.y returns 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 returned.
CSSStyleDeclaration.getPropertyPriority() - Web APIs
the cssstyledeclaration.getpropertypriority() method interface returns a domstring that provides all explicitly set priorities on the css property.
... return value priority is a domstring that represents the priority (e.g.
...if none exists, returns the empty string.
CSSStyleDeclaration.getPropertyValue() - Web APIs
the cssstyledeclaration.getpropertyvalue() method interface returns a domstring containing the value of a specified css property.
... return value value is a domstring containing the value of the property.
... if not set, returns the empty string.
CSSStyleRule - Web APIs
properties cssstylerule.selectortext returns the textual representation of the selector for this rule, e.g.
... cssstylerule.style read only returns the cssstyledeclaration object for the rule.
... cssstylerule.stylemap read only returns a stylepropertymap object which provides access to the rule's property-value pairs.
CSSStyleSheet.insertRule() - Web APIs
see browser compatibility for details.) return value the newly inserted rule's index within the stylesheet's rule-list.
... /*else*/ return 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 return 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 returns 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 returned value is null.
...if the stylesheet wasn't imported into the document using @import, the returned value is null.
CSSStyleSheet - Web APIs
cssrules read only returns 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 returns 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 returns 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 returns the first value as a cssstylevalue object.
... return value a cssstylevalue object containing the first supplied value.
...the second code block shows the structure of the returned object as it would be rendered in a developer tools console.
CSSUnitValue.CSSUnitValue() - Web APIs
the cssunitvalue() constructor creates a new cssunitvalue object which returns a new cssunitvalue object which represents values that contain a single unit type.
... syntax var cssunitvalue = new cssunitvalue() parameters value returns a double indicating the number of units.
... unit returns a usvstring indicating the type of unit.
CSSUnparsedValue.entries() - Web APIs
the cssunparsedvalue.entries() method returns 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 returned.
... return value an array of the given cssunparsedvalue object's own enumerable property [key, value] pairs.
Cache.addAll() - Web APIs
WebAPICacheaddAll
return 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 return 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) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/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
WebAPICacheStoragehas
the has() method of the cachestorage interface returns a promise that resolves to true if a cache object matches the cachename.
... return 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) { return cache.addall(myassets); }); } }).catch(function() { // handle exception here.
CanvasRenderingContext2D.getImageData() - Web APIs
the canvasrenderingcontext2d method getimagedata() of the canvas 2d api returns 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 returned imagedata object.
... return value an imagedata object containing the image data for the rectangle of the canvas specified.
CanvasRenderingContext2D.setLineDash() - Web APIs
note: to return 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 return to being solid.
... return value undefined.
Applying styles and colors - Web APIs
getlinedash() returns 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(); return 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="return draw();"> <label>miter limit</label> <input type="number" size="3" id="miterlimit"/> <input type="submit" value="redraw"/> </form> ...
... createpattern(image, type) creates and returns 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 return to the previous state.
...in most cases, it is just easier to call the restore method than having to do a reverse translation to return to the original state.
...in each loop, the canvas is translated, the rectangle is drawn, and the canvas is returned back to its original state.
Client.postMessage() - Web APIs
return value undefined.
... if (!event.clientid) return; // get the client.
... if (!client) return; // send a message to the client.
Clients.get() - Web APIs
WebAPIClientsget
the get() method of the clients interface gets a service worker client matching a given id and returns it in a promise.
... syntax self.clients.get(id).then(function(client) { // do something with your returned client }); parameters id a domstring representing the id of the client you want to get.
... return value a promise that resolves to a client object or undefined.
CloseEvent - Web APIs
closeevent.code read only returns an unsigned short containing the close code sent by the server.
... closeevent.reason read only returns a domstring indicating the reason the server closed the connection.
... closeevent.wasclean read only returns a boolean that indicates whether or not the connection was cleanly closed.
ContentIndex - Web APIs
contentindex.getall returns 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) { return; } // 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) return; // 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 returns 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) { return; } // 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) return; // 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 returns any data passed when initializing the event.
... syntax let mydetail = customeventinstance.detail; return 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 return 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 returns a domexception object with a specified message and name.
... name optional returns a domstring that contains one of the strings associated with an error constant.
... return value domexception a newly created domexception object.
DOMImplementationList - Web APIs
returned by domimplementationsource.getdomimplementationlist() and domimplementationregistry.getdomimplementationlist() .
... properties domimplementationlist.length read only returns an integer.
... methods domimplementationlist.item() returns the pos item.
DOMRect - Web APIs
WebAPIDOMRect
the type of box represented by the domrect is specified by the method or property that returned it.
... domrectreadonly.top returns the top coordinate value of the domrect (has the same value as y, or y + height if height is negative.) domrectreadonly.right returns the right coordinate value of the domrect (has the same value as x + width, or x if width is negative.) domrectreadonly.bottom returns the bottom coordinate value of the domrect (has the same value as y + height, or y if height is negative.) domrectreadonly.l...
...eft returns 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 returns 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.
... return value nsivariant the data item requested.
... if the specified item does not exist, null is returned.
DataTransfer.mozSourceNode - Web APIs
for external drags or if the calling function cannot reach the node, null is returned.
... syntax datatransfer.mozsourcenode; return value a node representing node where the drag originated.
... returns 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 returns the drag data item's file object.
... if the item is not a file, this method returns null.
... return value file if the drag data item is a file, a file object is returned; otherwise null is returned.
DataTransferItemList.add() - Web APIs
if the item is successfully added to the list, the newly-created datatransferitem object is returned.
... return 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 returned.
DirectoryReaderSync - Web APIs
if (!data.cmd || data.cmd != 'list') { return; } 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() returns a lost of entries from a specific directory.
... call this method until an empty array is returned.
... entrysync readentries ( ) raises (fileexception); returns 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 returned 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 returned by getdisplaymedia().
... if no audio source is available, or the user agent doesn't support audio tracks with getdisplaymedia(), the returned 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 returned by getdisplaymedia().
... more precise control over the format of the returned 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 returned by getdisplaymedia() should be in whatever format the user agent feels is best.
Document.createNodeIterator() - Web APIs
returns a new nodeiterator object.
...the method should return one of nodefilter.filter_accept, nodefilter.filter_reject, or nodefilter.filter_skip.
... example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode(node) { return node.nodename.tolowercase() === 'p' ?
Document.createTreeWalker() - Web APIs
the document.createtreewalker() creator method returns a newly created treewalker object.
... return value a new treewalker object.
... var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return 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
WebAPIDocumentdoctype
returns the document type declaration (dtd) associated with current document.
... the returned 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 returns null if there is no dtd associated with the current document.
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
returns an xpathresult based on an xpath expression and other given parameters.
... namespaceresolver is a function that will be passed any namespace prefixes and should return a string representing the namespace uri associated with that prefix.
... resulttype is an integer that corresponds to the type of result xpathresult to return.
Document.getElementsByClassName() - Web APIs
the getelementsbyclassname method of document interface returns 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 return 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){ return 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 returns an htmlcollection of elements with the given tag name.
...the returned 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 returns a nodelist in webkit browsers.
Document.lastStyleSheetSet - Web APIs
the document.laststylesheetset property returns the last enabled style sheet set.
... syntax var laststylesheetset = document.laststylesheetset on return, 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 returned value is null.
Document.preferredStyleSheetSet - Web APIs
the preferredstylesheetset property returns the preferred style sheet set as set by the page author.
... syntax preferredstylesheetset = document.preferredstylesheetset on return, 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 returned.
Document.queryCommandEnabled() - Web APIs
return value returns 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 returns true when called from a user-initiated thread.
... the 'paste' command return 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 returns 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 returned by document.hasstorageaccess().
... return 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 returns 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 returns the first matching element.
... examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: 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 returns information about a query target.
... pname a glenum specifying which information to return.
... return 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() returns true if a given object is a webglquery.
... ext.getqueryext() returns information about a query target.
... ext.getqueryobjectext() return the state of a query object.
Element.computedStyleMap() - Web APIs
the computedstylemap() method of the element interface returns a stylepropertymapreadonly interface which provides a read-only representation of a css declaration block that is an alternative to cssstyledeclaration.
... return 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 return back a definition list of all the css property values using computedstylemap().
Element.currentStyle - Web APIs
however, it returns the units set in css while window.getcomputedstyle() returns the values in pixels.
... polyfill this polyfill returns 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() { return window.getcomputedstyle(this); } }); } specification not part of any specification.
Element.getAttributeNames() - Web APIs
the getattributenames() method of the element interface returns the attribute names of the element as an array of strings.
... if the element has no attributes it returns 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; } return result; }; } specifications specification status comment domthe definition of 'element.getattributenames' in that specification.
Element.getElementsByTagName() - Web APIs
the element.getelementsbytagname() method returns a live htmlcollection of elements with the given tag name.
...the returned list is live, which means it updates itself with the dom tree automatically.
... living standard changed the return 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 returns a boolean value indicating whether the specified element has the specified attribute or not.
... syntax var result = element.hasattribute(name); result holds the return 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) { return !!(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 returns a boolean indicating whether the current element has any attributes or not.
... syntax var result = element.hasattributes(); return value result holds the return 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() { return (this.attributes.length > 0); } })(element.prototype); specifications specification status comment domthe definition of 'element.hasattributes()' in that specification.
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
note: if a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerhtml returns these characters as the html entities "&amp;", "&lt;" and "&gt;" respectively.
...the resulting string is returned.
... note: the returned html or xml fragment is generated based on the current contents of the element, so the markup and formatting of the returned 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
WebAPIEventcomposed
the read-only composed property of the event interface returns 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 return false.
... the composed property returns true beause the click event is always able to propagate across shadow boundaries.
Event.composedPath() - Web APIs
the composedpath() method of the event interface returns the event’s path which is an array of the objects on which listeners will be invoked.
... return value an array of eventtarget objects representing the objects on which an event listener will be invoked.
...first, the composed property returns true beause the click event is always able to propagate across shadow boundaries.
EventTarget.dispatchEvent() - Web APIs
return value the return value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault().
... otherwise it returns true.
...all applicable event handlers will execute and return before the code continues on after the call to dispatchevent().
FeaturePolicy.allowedFeatures() - Web APIs
the allowedfeatures() method of the featurepolicy interface returns 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 returns a subset of directives returned by features().
... return 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 returns 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) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network.
... return fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'preloadresponse' in that specification.
FetchEvent.navigationPreload - Web APIs
the navigationpreload read-only property of the fetchevent interface returns a promise that resolves to the instance of navigationpreloadmanager associated with the current service worker registration.
... addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network.
... return fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'navigationpreload' in that specification.
FileEntrySync - Web APIs
returns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
... file() returns a file that represents the current state of the file that this fileentry represents.
... returns 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
WebAPIFileList
an object of this type is returned 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() returns a file object representing the file at the specified index in the file list.
... return value the file representing the requested file.
FileReader - Web APIs
file objects may be obtained from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement.
... constructor filereader() returns a newly constructed filereader.
...upon return, 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 returned.
... getdirectory() returns a filesystemdirectoryentry object representing a directory located at a given path, relative to the directory on which the method is called.
... getfile() returns 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 returns 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 returns its full path.
... function gotfilesystem(fs) { let path = ""; fs.root.getfile("data.json", { create: true, exclusive: true }, function(entry) { path = fullpath; }, handleerror(error)); return 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 returns 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 returns true if the specified filesystementry is both a file and the file's name ends with a given extension.
... function isfilewithextension(entry, extension) { return (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 returns a string containing a url which can be used to identify the file system entry.
... return 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 returned 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 returning values; instead, you have to pass a callback function.
...in contrast, the synchronous api does not use callbacks because the api methods return values.
File and Directory Entries API - Web APIs
the synchronous api is intended to be used inside a worker and will return the values you desire.
... the asynchronous api will not block and functions and the api will not return values; instead, you will need to supply a callback function to handle the response whenever it arrives.
... synchronous api the synchronous api is should only be used in workers; these calls block until they're finished executing, and simply return the results instead of using callbacks.
FontFaceSet.check() - Web APIs
WebAPIFontFaceSetcheck
the check() method of the fontfaceset returns whether all fonts in the given font list have been loaded and are available.
... syntax bool = afontfaceset.check(font); bool = afontfaceset.check(font, text); returns 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"); // returns true if the font courier is available at 12px document.fonts.check("12px myfont", "ß"); // returns true if the font 'myfont' has a ß character.
FormData.has() - Web APIs
WebAPIFormDatahas
the has() method of the formdata interface returns a boolean stating whether a formdata object contains a certain key.
... returns 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'); // returns false formdata.append('username', 'chris'); formdata.has('username'); // returns true specifications specification status comment xmlhttprequestthe definition of 'has()' in that specification.
GeolocationPositionError - Web APIs
geolocationpositionerror.code read only secure context returns an unsigned short representing the error code.
... 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal error.
... geolocationpositionerror.message read only secure context returns 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) { return 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") { return true; } if (nchr !== ssecret.charcodeat(noffset)) { noffset = nchr === ssecret.charcodeat(0) ?
...*/ alert("yesss!!!"); location.assign("https://developer.mozilla.org/"); } return true; }; })(); note: a more complete framework for capturing the typing of hidden words is available on github.
Gyroscope - Web APIs
WebAPIGyroscope
properties gyroscope.x read only returns a double, containing the angular velocity of the device along the device's x axis.
... gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis.
... gyroscope.z read only returns a double, containing the angular velocity of the device along the device's z axis.
HTMLAnchorElement - Web APIs
htmlhyperlinkelementutils.origin read only returns a usvstring containing the origin of the url, that is its scheme, its domain and its port.
... htmlanchorelement.rellist read only returns a domtokenlist that reflects the rel html attribute, as a list of tokens.
... htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url.
HTMLAreaElement - Web APIs
htmlhyperlinkelementutils.origin read only returns a usvstring containing the origin of the url, that is its scheme, its domain and its port.
... htmlareaelement.rellist read only returns a domtokenlist that reflects the rel html attribute, indicating relationships of the current document to the linked resource, as a list of tokens.
... htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url of the script executed in the worker.
Audio() - Web APIs
the audio() constructor creates and returns 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.
... return value a new htmlaudioelement object, configured to be used for playing back the audio from the file specified by url.the new object's preload property is set to auto and its src property is set to the specified url or null if no url is given.
... if a url is specified, the browser begins to asynchronously load the media resource before returning the new object.
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 returns a new htmlaudioelement object, optionally starting the process of loading an audio file into it if the file url is given.
... mozcurrentsampleoffset() returns 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, returning the number of bytes actually written to the stream.
HTMLCanvasElement.captureStream() - Web APIs
the htmlcanvaselement capturestream() method returns 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 returned track's requestframe() method is called.
... return value a reference to a mediastream object, which has a single canvascapturemediastreamtrack in it.
HTMLCanvasElement.toBlob() - Web APIs
return 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) { return 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) { return function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer.
HTMLDialogElement - Web APIs
htmldialogelement.returnvalue a domstring that sets or returns the return value for the dialog.
...an optional domstring may be passed as an argument, updating the returnvalue 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.returnvalue = '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 returns 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 return 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 return 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 returns 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 return value item is a radionodelist , element, or null.
... example html <form> <input id="my-form-control" type="textarea"> </form> javascript // returns 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 returns 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 returned 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 returned by the elements property.
HTMLFormElement.reportValidity() - Web APIs
the htmlformelement.reportvalidity() method returns true if the element's child controls satisfy their validation constraints.
... when false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
... syntax htmlformelement.reportvalidity() return 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 returns a usvstring containing the whole url, and allows the href to be updated.
... htmlhyperlinkelementutils.origin read only this returns a usvstring containing the origin of the url (that is its scheme, its domain and its port).
... htmlhyperlinkelementutils.tostring() this returns a usvstring containing the whole url.
HTMLIFrameElement - Web APIs
htmliframeelement.contentdocument read only returns a document, the active document in the inline frame's nested browsing context.
... htmliframeelement.contentwindow read only returns a windowproxy, the window proxy for the nested browsing context.
... htmliframeelement.featurepolicy read only returns 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 returns the intrinsic (natural), density-corrected width of the image in css pixels.
... the corresponding naturalheight method returns 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 returns 0.
HTMLMediaElement.seekToNextFrame() - Web APIs
this method returns immediately, returning a promise, whose fulfillment handler is called when the seek operation is complete.
... syntax var seekcompletepromise = htmlmediaelement.seektonextframe(); htmlmediaelement.seektonextframe(); return value a promise which is fulfilled once the seek operation has completed.
... firefox 49 returns undefined instead of a promise, and performs the seek operation synchronously.
HTMLMediaElement.sinkId - Web APIs
the htmlmediaelement.sinkid read-only property returns a domstring that is the unique id of the audio device delivering output.
... if it is using the user agent default, it returns an empty string.
... this id should be one of the mediadeviceinfo.deviceid values returned from mediadevices.enumeratedevices(), id-multimedia, or id-communications.
HTMLProgressElement - Web APIs
htmlprogresselement.positionread only returns a double value returning the result of dividing the current value (value) by the maximum value (max); if the progress bar is an indeterminate progress bar, it returns -1.
... htmlprogresselement.value is a double value that reflects the current value; if the progress bar is an indeterminate progress bar, it returns 0.
... htmlprogresselement.labelsread only returns nodelist containing the list of <label> elements that are labels for this element.
HTMLSelectElement.form - Web APIs
the htmlselectelement.form read-only property returns a htmlformelement representing the form that this element is associated with.
... if the element is not associated with of a <form> element, then it returns 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" returns the type of the calling form element.
HTMLSelectElement.item() - Web APIs
the htmlselectelement.item() method returns 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.
... return 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 // returns 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 returns the htmloptionelement corresponding to the htmloptionelement whose name or id match the specified name, or null if no option matches.
... return 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']; // returns 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 returns the <caption> element associated with a given <table>.
... if no <caption> element exists on the table, this method creates it, and then returns it.
... syntax htmltableelement = table.createcaption(); return 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 returns the <tfoot> element associated with a given <table>.
... if no footer exists in the table, this methods creates it, and then returns it.
... syntax htmltablesectionelement = table.createtfoot(); return 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 returns the <thead> element associated with a given <table>.
... if no header exists in the table, this method creates it, and then returns it.
... syntax htmltablesectionelement = table.createthead(); return 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 returns a live htmlcollection of the bodies in a <table>.
... although the property is read-only, the returned object is live and allows the modification of its content.
... the collection returned includes implicit <tbody> elements.
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
the htmlvideoelement method getvideoplaybackquality() creates and returns a videoplaybackquality object containing metrics including how many frames have been lost.
... the data returned can be used to evaluate the quality of the video stream.
... syntax videopq = videoelement.getvideoplaybackquality(); return 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
WebAPIHeadersappend
returns 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'); // returns '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'); // returns 'deflate, gzip' to overwrite the old value with a new one, use headers.set.
Headers.has() - Web APIs
WebAPIHeadershas
the has() method of the headers interface returns a boolean stating whether a headers object contains a certain header.
... returns 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'); // returns true myheaders.has('accept-encoding'); // returns false specifications specification status comment fetchthe definition of 'has()' in that specification.
History - Web APIs
WebAPIHistory
length read only returns 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 returns 1.
... state read only returns 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 returns a connection to a database.
... blocks the calling thread until the connection object is ready to return.
... returns idbdatabasesync an object to access the open database.
IDBIndex.keyPath - Web APIs
WebAPIIDBIndexkeyPath
the keypath property of the idbindex interface returns 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 returned 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 returned as lname.
IDBIndex.multiEntry - Web APIs
the multientry read-only property of the idbindex interface returns 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 returned 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 returned as false.
IDBIndex.objectStore - Web APIs
the objectstore property of the idbindex interface returns 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 returned records are sorted based on the index, not the primary key.
... the current object store is logged to the console: it should be returned 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 returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range.
... return 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 returned records are sorted based on the index, not the primary key.
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
the unique read-only property returns 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 returned 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 returned as false.
IDBKeyRange - Web APIs
idbkeyrange.loweropen read only returns false if the lower-bound value is included in the key range.
... idbkeyrange.upperopen read only returns false if the upper-bound value is included in the key range.
... instance methods idbkeyrange.includes() returns a boolean indicating whether a specified key is inside the key range.
IDBObjectStore.add() - Web APIs
the add() method of the idbobjectstore interface returns 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 returned request object.
... returns an idbrequest object on which subsequent events related to this operation are fired.
IDBObjectStore.count() - Web APIs
the count() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, returns the total number of records that match the provided key or idbkeyrange.
... if no arguments are provided, it returns the total number of records in the store.
... return 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 returns 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 return if more than one is found.
... return 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, return a series of records sorted by that index using a cursor.
... return 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 returned records are sorted based on the index, not the primary key.
IDBRequest.source - Web APIs
WebAPIIDBRequestsource
the source read-only property of the idbrequest interface returns the source of the request, such as an index or an object store.
... if no source exists (such as when calling indexeddb.open), it returns 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 returned 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 returns 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 returned from idbfactory.open — in this case you're just connecting to a database, so there is no transaction to return.
...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 returned 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
WebAPIIDBTransactiondb
the db read-only property of the idbtransaction interface returns the database connection with which this transaction is associated.
...at the end, we return 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>'; }; // return 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, returning 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 returned request.
... returns idbversionchangerequest the request to change the version of a database.
ImageCapture.getPhotoCapabilities() - Web APIs
the getphotocapabilities() method of the imagecapture interface returns a promise that resolves with a photocapabilities object containing the ranges of available configuration options.
... syntax const capabilitiespromise = imagecaptureobj.getphotocapabilities() return 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); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error =...
ImageCapture.getPhotoSettings() - Web APIs
the getphotosettings() method of the imagecapture interface returns a promise that resolves with a photosettings object containing the current photo configuration settings.
... syntax const settingspromise = imagecapture.getphotosettings() return 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); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return 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 returns a promise that resolves with a imagebitmap containing the snapshot.
... syntax const bitmappromise = imagecapture.grabframe() return value a promise that resolves to an imagebitmap object.
...it shows how to use the promise returned by grabframe() to copy the returned 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 returns a promise that resolves with a blob containing the data.
... return value a promise that resolves with a blob.
...it shows how to use the promise returned by takephoto() to copy the returned 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>'; return; } 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() returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (getfullyear() is needed; getyear() is deprecated, and returns a weird value that is not much use to anyone!) var objectstore = db.transaction(['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 returned 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 returned 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() returns an array of intersectionobserverentry objects for all observed targets.
... if (entries[0].intersectionratio <= 0) return; 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 returned by calling getboundingclientrect() on it).
...we then call observe() on the returned 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); return 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
WebAPIKeyboard
methods keyboard.getlayoutmap() returns 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() returns 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 returns synchronously.
KeyboardLayoutMap.get() - Web APIs
the get() method of the keyboardlayoutmap interface returns the element with the given key.
... syntax var value = keyboardlayoutmap.get(key) parameters key the key of the item to return from the map.
... return value the value of the specified key.
KeyframeEffect.getKeyframes() - Web APIs
the getkeyframes() method of a keyframeeffect returns an array of the computed keyframes that make up this animation along with their computed offsets.
... return value returns 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: // return 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() returns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance.
... animationeffect.getcomputedtiming() returns the calculated, current timing values for this keyframe effect.
... keyframeeffect.getkeyframes() returns 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 returned as the area (width * height).
...this property returns an empty string when there is no id.
... methods largestcontentfulpaint.tojson() returns the above properties as json.
LayoutShiftAttribution - Web APIs
properties layoutshiftattribution.node returns the element that has shifted (null if it has been removed).
... layoutshiftattribution.previousrect returns a domrect representing the position of the element before the shift.
... layoutshiftattribution.currentrect returns a domrect representing the position of the element after the shift.
LinearAccelerationSensor - Web APIs
properties linearaccelerationsensor.x read only returns a double containing the linear acceleration of the device along the device's x axis.
... linearaccelerationsensor.y read only returns a double containing the linear acceleration of the device along the device's y axis.
... linearaccelerationsensor.z read only returns a double containing the linear acceleration of the device along the device's z axis.
Location - Web APIs
WebAPILocation
location.href is a stringifier that returns a usvstring containing the entire url.
... location.origin read only returns a usvstring containing the canonical form of the origin of the specific location.
... location.tostring() returns a usvstring containing the whole url.
Lock - Web APIs
WebAPILock
properties lock.mode read only returns the access mode passed to lockmanager.request() when the lock was requested.
... lock.name read only returns the name passed to lockmanager.request() when the lock was requested.
...lockmanager is the object returned by navigator.locks.
MSGraphicsTrust - Web APIs
the msgraphicstrust() constructor returns an object that provides properties for info on protected video playback.
... syntax var trustobject = media.msgraphicstruststatus; parameters constrictionactive a read-only property which returns true when protected media is forced to play in a lower resolution.
... status a read-only property which returns an enum with the driver status when playing protected content.
Magnetometer - Web APIs
properties magnetometer.x read only returns a double containing the magnetic field around the device's x axis.
... magnetometer.y read only returns a double containing the magnetic field around the device's y axis.
... magnetometer.z read only returns a double containing the magnetic field around the device's z axis.
MediaDevices.enumerateDevices() - Web APIs
the returned promise is resolved with a mediadeviceinfo array describing the devices.
... syntax var enumeratorpromise = navigator.mediadevices.enumeratedevices(); return 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."); return; } // 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 returned 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 returned 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() returns an object conforming to mediatracksupportedconstraints indicating which constrainable properties are supported on the mediastreamtrack interface.
...returns 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 returns 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 returned.
... returns the value associated with the given key, or undefined.
MediaKeySystemAccess - Web APIs
properties mediakeysystemaccess.keysystem read only returns a domstring identifying the key system being used.
... methods mediakeysystemaccess.createmediakeys() returns a promise that resolves to a new mediakeys object.
... mediakeysystemaccess.getconfiguration() returns a mediakeysystemconfiguration object with the supported combination of configuration options.
MediaKeySystemConfiguration - Web APIs
properties mediakeysystemconfiguration.initdatatypes read only returns a list of supported initialization data type names.
... mediakeysystemconfiguration.audiocapabilities read only returns a list of supported audio type and capability pairs.
... mediakeysystemconfiguration.videocapabilities read only returns a list of supported video type and capability pairs.
MediaList - Web APIs
WebAPIMediaList
properties medialist.mediatext a stringifier that returns a domstring representing the medialist as text, and also allows you to set a new medialist.
... medialist.length read only returns the number of media queries in the medialist.
... medialist.item() a getter that returns 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 returns 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 return 'video/mp4' ...
... mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent, the value returned later by m.mimetype would then be video/mp4; codecs="avc1.424028, mp4a.40.2".
MediaRecorder.onerror - Web APIs
it returns 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) { return err.name; /* return 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 */ return recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecorder.onerror' in that specification.
MediaSource.isTypeSupported() - Web APIs
the mediasource.istypesupported() static method returns a boolean value which is true if the given mime type is likely to be supported by the current user agent.
...if the returned value is false, then the user agent is certain that it cannot access media of the specified format.
... return 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 returned 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 returned by the htmlmediaelement.seekable property will have an end timestamp no less than this value.
... return 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 returns a sequence that represents all the mediastreamtrack objects in this stream's track set where mediastreamtrack.kind is audio.
... return value an array of mediastreamtrack objects, one for each audio track contained in the stream.
... note: the order of the returned 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 returns a sequence of mediastreamtrack objects representing the video tracks in this stream.
... return 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); return 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 returned 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 returned 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 returned.
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 returned 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 returned 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 returned.
MediaStreamConstraints - Web APIs
the mediastreamconstraints dictionary is used when calling getusermedia() to specify what kinds of tracks should be included in the returned 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 returned 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 returned mediastream.
MediaStreamTrack.getSettings() - Web APIs
the getsettings() method of the mediastreamtrack interface returns a mediatracksettings object containing the current values of each of the constrainable properties for the current mediastreamtrack.
... syntax const settings = track.getsettings() returns a mediatracksettings object describing the current configuration of the track's constrainable properties.
... note: the returned object identifies the current values of every constrainable property, including those which are platform defaults rather than having been expressly set by the site's code.
MediaStream Image Capture API - Web APIs
this method returns a promise that resolves with a mediastream object.
...this returns an array of mediastreamtrack objects.
...if(!capabilities.zoom) { return; } 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 returned 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 returned 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 returned mediatracksettings object's cursor object.
Using the Media Capabilities API - Web APIs
this returns 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 return promises.
... handling the response instead of the assigning the promise to a variable, we can output the values returned 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 returns port1 of the channel.
... messagechannel.port2 read only returns port2 of the channel.
... constructor messagechannel() returns a new messagechannel object with two new messageport objects.
MouseEvent.region - Web APIs
WebAPIMouseEventregion
the mouseevent.region read-only property returns the id of the canvas hit region affected by the event.
... if no hit region is affected, null is returned.
... syntax var hitregion = instanceofmouseevent.region return value a domstring representing the id of the hit region.
Navigation Timing API - Web APIs
interfaces performance the window.performance property returns a performance object.
... performancenavigation the type used to return 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 returns (loadeventend).
Navigator.cookieEnabled - Web APIs
navigator.cookieenabled returns 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 returns true in safari, edge spartan and ie (while trying to set a cookie in such scenario would fail).
... it returns false in firefox and chromium-based browsers.
Navigator.getBattery() - Web APIs
it returns 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(); return 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 returned 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 returns 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> // returns: 20010725 notes on ie, this property returns undefined.
... on apple safari and google chrome this property always returns 20030107.
NavigatorID.appVersion - Web APIs
returns either "4.0" or a string representing version information about the browser.
... note: do not rely on this property to return the correct browser version.
...this lead to the current situation, where browsers had to return fake values from these properties in order not to be locked out of some websites.
NavigatorID.platform - Web APIs
returns a string representing the platform of the browser.
... the specification allows browsers to always return 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, return "win32" even if running on a 64-bit version of windows.
NavigatorLanguage.languages - Web APIs
the navigatorlanguage.languages read-only property returns an array of domstrings representing the user's preferred languages.
...in the returned array they are ordered by preference with the most preferred language first.
... the value of navigator.language is the first element of the returned array.
NavigatorLanguage - Web APIs
navigatorlanguage.language read only returns a domstring representing the preferred language of the user, usually the language of the browser ui.
... the null value is returned when this is unknown.
... navigatorlanguage.languages read only returns an array of domstring representing the languages known to the user, by order of preference.
NavigatorPlugins - Web APIs
properties navigatorplugins.mimetypes read only returns an mimetypearray listing the mime types supported by the browser.
... navigatorplugins.plugins read only returns a pluginarray listing the plugins installed in the browser.
... navigatorplugins.javaenabled() read only returns a boolean flag indicating whether the host browser is java-enabled or not.
Node.compareDocumentPosition() - Web APIs
the return 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.
... return 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 returned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results.
Node.contains() - Web APIs
WebAPINodecontains
the node.contains() method returns 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 returns false.
... function isinpage(node) { return (node === document.body) ?
Node.hasChildNodes() - Web APIs
the node.haschildnodes() method returns a boolean value indicating whether the given node has child nodes or not.
... syntax bool = node.haschildnodes(); return 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() { return !!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
WebAPINodenamespaceURI
the node.namespaceuri read-only property returns the namespace uri of the node, or null if the node is not in a namespace.
... when the node is a document, it returns the xml namespace for the current document.
...if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>.
Node.nodeName - Web APIs
WebAPINodenodeName
the nodename read-only property returns the name of the current node as a string.
...however, in html, text_field's value would read "div", because nodename and tagname return in upper case on html elements in doms flagged as html documents.
...bear in mind, however, that nodename will return "#text" for text nodes while tagname will return undefined.
Node.parentNode - Web APIs
WebAPINodeparentNode
the node.parentnode read-only property returns 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 return null.
... it also returns 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 returns a nodefilter object, that is an object implement an acceptnode(node) method, used to screen nodes.
...this function should return 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) { return 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 returns the previous node in the set represented by the nodeiterator and moves the position of the iterator backwards within the set.
... this method returns 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) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns 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 returns 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; return 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')) { return; } object.defineproperty(item, 'nextelementsibling', { configurable: tru...
...e, enumerable: true, get: function () { var el = this; while (el = el.nextsibling) { if (el.nodetype === 1) { return el; } } return 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 returns 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; return 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')) { return; } object.defineproperty(item, 'previouselementsibling', { configu...
...rable: true, enumerable: true, get: function () { let el = this; while (el = el.previoussibling) { if (el.nodetype === 1) { return el; } } return null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'nondocumenttypechildnode.previouselementsibling' in that specification.
NotificationEvent.action - Web APIs
returns the string id of the notification button the user clicked.
... this value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button.
... returns a domstring object.
NotificationEvent.notification - Web APIs
the notification read-only property of the notificationevent interface returns the instance of the notification that was clicked to fire the event.
... returns 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) return client.focus(); } if (clients.openwindow) return 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) { return false; } return true; } we basically try to see if the .then() method is available on requestpermission().
... if so, we move on and return true.
... if it fails, we return false in the catch() {} block.
OffscreenCanvas.getContext() - Web APIs
the offscreencanvas.getcontext() method returns a drawing context for an offscreen canvas, or null if the context identifier is not supported.
... return 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 returned.
OffscreenCanvas - Web APIs
methods offscreencanvas.getcontext() returns a rendering context for the offscreen canvas.
...this method returns 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 return an offscreencanvas object from an htmlcanvaselement object from the main thread.
OverconstrainedError - Web APIs
properties overconstrainederror.constraint read only returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied.
... overconstrainederror.message read only returns the text supplied in the constructor.
... overconstrainederror.name read only will always return overconstrainederror.
ParentNode.append() - Web APIs
WebAPIParentNodeappend
parentnode.append() has no return value, whereas node.appendchild() returns the appended node object.
... syntax // [throws, unscopable] parentnode.append(...nodesordomstrings) // returns 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')) { return; } 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 returns an unsigned long representing the number of child elements of the given element.
... syntax var count = node.childelementcount; count the return 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++; } return 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 returns a live htmlcollection which contains all of the child elements of the node upon which it was called.
...// returns 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); } } return 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 returns the object's last child element or null if there are no child elements.
...// returns 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) { return node; } } return 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 returning an element representing the first element matching the specified group of selectors which are descendants of the object on which the method was called.
... return 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 returned 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; return await fetch(merchantserverurl).then(response => response.text()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation and payment method documentation.
... the content delivered by the validation server is forwarded to the merchant server and is then returned from the fetch() call's fulfillment handler to the complete() method on the event.
... you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
PaymentRequest: paymentmethodchange event - Web APIs
the code assumes the existence of a method detailsforshipping(), which returns 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 return 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 returns, 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, returns the shipping address chosen by the user for the purposes of calculating shipping.
... paymentrequest.shippingoption read only secure context returns the identifier of the selected shipping option.
... paymentrequest.shippingtype read only secure context returns 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 returned by the paymentrequest.show() method is resolved.
... return 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, returning one of the exceptions listed below.
PaymentResponse.details - Web APIs
the details read-only property of the paymentresponse interface returns 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 returned 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 returned from paymentrequest.show().
performance.getEntries() - Web APIs
the getentries() method returns a list of all performanceentry objects for the page.
... syntax general syntax: entries = window.performance.getentries(); return value entries an array of performanceentry objects.
...performance.mark not supported"); return; } // 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 returns a domstring representing the type of performance metric such as, for example, "mark".
... syntax var type = entry.entrytype; return value the return 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"); return; } // 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 returns a value that further specifies the value returned by the performanceentry.entrytype property.
... syntax var name = entry.name; return value the return 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"); return; } // 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 returns a json representation of the performance entry object.
... syntax json = perfentry.tojson(); arguments none return value json a json object that is the serialization of the performanceentry object.
...performance.mark not supported"); return; } // 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 returns 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 returns 0.
... syntax perfentry.unloadeventstart; return 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 returns a list of explicitly observed performance entry objects for a given performance entry type.
... return 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 returned.
PerformanceObserverEntryList - Web APIs
methods performanceobserverentrylist.getentries() returns a list of explicitly observed performanceentry objects based on the given filter.
... performanceobserverentrylist.getentriesbytype() returns a list of explicitly observed performanceentry objects of the given entry type.
... performanceobserverentrylist.getentriesbyname() returns a list of explicitly observed performanceentry objects based on the given name and entry type.
PerformanceResourceTiming.decodedBodySize - Web APIs
the decodedbodysize read-only property returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings.
... if the resource is retrieved from an application cache or local resources, it returns the size of the payload after removing any applied content-codings.
... syntax resource.decodedbodysize; return value the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings.
PerformanceResourceTiming.nextHopProtocol - Web APIs
when a proxy is used, if a tunnel connection is established, this property returns the alpn protocol id of the tunneled protocol.
... otherwise, this property returns the alpn protocol id of the first hop to the proxy.
... syntax resource.nexthopprotocol; return value a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301).
PerformanceResourceTiming.redirectEnd - Web APIs
the redirectend read-only property returns 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 returns the time immediately after receiving the last byte of the response of the last redirect; otherwise, zero is returned.
... syntax resource.redirectend; return 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 returns a timestamp representing the start time of the fetch which that initiates the redirect.
... if there are http redirects when fetching the resource and if any of the redirects are not from the same origin as the current document, but the timing allow check algorithm passes for each redirected resource, this property returns the starting time of the fetch that initiates the redirect; otherwise, zero is returned.
... syntax resource.redirectstart; return value a timestamp representing the start time of the fetch which initiates the redirect.
PerformanceResourceTiming.requestStart - Web APIs
the requeststart read-only property returns 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 returned will be the start of the retry request.
... syntax resource.requeststart; return 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"); return; } // 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 returns 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"); return; } // 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
WebAPIPermissionsquery
the permissions.query() method of the permissions interface returns the state of a user permission on the global scope.
...by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push.
... returns 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); return color; } the result from this function is a string that can be used when calling <canvas> functions to set drawing colors.
... function copytouch(touch) { return { 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 returns 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) { return i; } } return -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 returns a promise that resolves to a pushsubscription object containing details of an existing subscription.
... returns 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 return; } // 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 returns 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 returned push subscription will only be used for messages whose effect is made visible to the user.
... returns a promise that resolves to a domstring with a value of 'prompt', 'denied', or 'granted'.
PushManager.subscribe() - Web APIs
it returns 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 returned push subscription will only be used for messages whose effect is made visible to the user.
... returns a promise that resolves to a pushsubscription object.
PushSubscription.getKey() - Web APIs
the getkey() method of the pushsubscription interface returns an arraybuffer representing a client public key, which can then be sent to a server and used in encrypting push message data.
... returns 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 return; } // 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() returns an arraybuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data.
... pushsubscription.tojson() standard serializer — returns a json representation of the subscription properties.
... pushsubscription.unsubscribe() starts the asynchronous process of unsubscribing from the push service, returning a promise that resolves to a boolean when the current subscription is successfully unregistered.
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 returns 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; } } }); return results; } note that in this code, the new and connecting states are being treated as a single connectionpending status in the returned 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": return true; case "bluetooth": case "cellular": case "wimax": case "unknown": default: return false; } } if (rtcstats && rtcstats.type === "local-candidate") { if (!isusablenetworktype(rtcstats)) { abortconnection(); return; } } 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() returns an rtciceparameters object which provides information uniquely identifying the local peer for the duration of the ice session.
... return value an rtciceparameters object indicating the usernamefragment and password which uniquely identify the local peer for the duration of the ice session.
... returns null if the parameters have not yet been received.
RTCIceTransport.getRemoteCandidates() - Web APIs
the rtcicetransport method getremotecandidates() returns 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 returned by this function.
... return 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() returns an rtciceparameters object which provides information uniquely identifying the remote peer for the duration of the ice session.
... return value an rtciceparameters object indicating the usernamefragment and password which uniquely identify the remote peer for the duration of the ice session.
... returns null if the parameters haven't been received yet.
RTCIceTransport.getSelectedCandidatePair() - Web APIs
the rtcicetransport method getselectedcandidatepair() returns an rtcicecandidatepair object containing the current best-choice pair of ice candidates describing the configuration of the endpoints of the transport.
... return value a rtcicecandidatepair object describing the configurations of the currently-selected candidate pair's two endpoints.
... the return 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 return a value.
... return 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 returned by this method is rejected, returning 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 returns an rtcconfiguration object which indicates the current configuration of the rtcpeerconnection on which the method is called.
... the returned configuration is the last configuration applied via setconfiguration(), or if setconfiguration() hasn't been called, the configuration the rtcpeerconnection was constructed with.
... return value an rtcconfiguration object describing the rtcpeerconnection's current configuration.
RTCPeerConnection.getDefaultIceServers() - Web APIs
the getdefaulticeservers() method of the rtcpeerconnection interface returns 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(); return 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 returned array is empty; this property's value is never null.
RTCPeerConnection.getReceivers() - Web APIs
the rtcpeerconnection.getreceivers() method returns 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(); return value an array of rtcrtpreceiver objects, one for each track on the connection.
... the order of the returned 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() returns an array of rtcrtpsender objects, each of which represents the rtp sender responsible for transmitting one track's data.
... syntax var senders = rtcpeerconnection.getsenders(); return value an array of rtcrtpsender objects, one for each track on the connection.
... the order of the returned 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 returns 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 return to the "connected" state.
RTCPeerConnection.pendingLocalDescription - Web APIs
the read-only property rtcpeerconnection.pendinglocaldescription returns an rtcsessiondescription object describing a pending configuration change for the local end of the connection.
... syntax sessiondescription = rtcpeerconnection.pendinglocaldescription; return value if a local description change is in progress, this is an rtcsessiondescription describing the proposed configuration.
... otherwise, this returns null.
RTCPeerConnection.pendingRemoteDescription - Web APIs
the read-only property rtcpeerconnection.pendingremotedescription returns an rtcsessiondescription object describing a pending configuration change for the remote end of the connection.
... syntax sessiondescription = rtcpeerconnection.pendingremotedescription; return value if a remote description change is in progress, this is an rtcsessiondescription describing the proposed configuration.
... otherwise, this returns null.
RTCPeerConnection.remoteDescription - Web APIs
the read-only property rtcpeerconnection.remotedescription returns a rtcsessiondescription describing the session (which includes configuration and media information) for the remote end of the connection.
... the returned 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 returned value is the value of rtcpeerconnection.pendingremotedescription if that property isn't null; otherwise, the value of rtcpeerconnection.currentremotedescription is returned.
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.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { return 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 returned 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.
... return value a newly-created rtcpeerconnectioniceevent, configured as specified in the provided options.
RTCRtpReceiver.getParameters() - Web APIs
the getparameters() method of the rtcrtpreceiver interface returns an rtcrtpreceiveparameters object describing the current configuration for the encoding and transmission of media on the receiver's track.
... return value an rtcrtpreceiveparameters object indicating the current configuration of the receiver.
... function getrtcpcname(receiver) { let parameters = receiver.getparameters(); return 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, returning a promise whose fulfillment handler will be called once the results are available.
... syntax var promise = rtcrtpreceiver.getstats(); return value a javascript promise which is fulfilled once the statistics are available.
... the returned 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 returns an rtcrtpsendparameters object describing the current configuration for the encoding and transmission of media on the sender's track.
... return value an rtcrtpsendparameters object indicating the current configuration of the sender.
... function getsendertransactionid(sender) { let parameters = sender.getparameters(); return 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, returning a promise which is fulfilled when the results are available.
... syntax var promise = rtcrtpsender.getstats(); return value a javascript promise which is fulfilled once the statistics are available.
... the returned rtcstatsreport accumulates the statistics for all of the streams being sent using the rtcrtpsender, as well as the statistics for any dependencies those streams have.
RTCRtpSender.replaceTrack() - Web APIs
return value a promise which is fulfilled once the track has been successfully replaced.
... exceptions if the returned 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) { return 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() returns a rtcrtpparameters object describing the current configuration for the encoding and transmission of media on the track.
... rtcrtpsender.getstats() returns 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() returns an rtcrtpcapabilities object describing the system's capabilities for sending a specified kind of media data.
Range.compareNode() - Web APIs
WebAPIRangecompareNode
the range.comparenode() returns 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) return 0; if (!nodeisbefore && nodeisafter) return 1; if (nodeisbefore && nodeisafter) return 2; return 3; } syntax returnvalue = range.comparenode( referencenode ); parameters referencenode the node to compare with the range.
... example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = 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 returns -1, 0, or 1 depending on whether the referencenode is before, the same as, or after the range.
... syntax returnvalue = range.comparepoint(referencenode, offset) parameters referencenode the node to compare with the range.
... example range = document.createrange(); range.selectnode(document.getelementsbytagname('div').item(0)); returnvalue = range.comparepoint(document.getelementsbytagname('p').item(0), 1); specification specification status comment domthe definition of 'range.comparepoint()' in that specification.
ReadableStream.cancel() - Web APIs
return 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; return reader.read().then(function process(result) { if (result.done) { console.log('failed to find match'); return; } 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(); return; } else { console.log('found match, but need more context…'); } // keep reading return reader.read().then(process); }); }).catch(err => { console.log("something went wrong.
ReadableStreamBYOBReader - Web APIs
constructor readablestreambyobreader() creates and returns a readablestreambyobreader object instance.
...returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors.
... readablestreambyobreader.read() returns a promise providing access to the next chunk in the stream's internal queue.
Report.body - Web APIs
WebAPIReportbody
the body read-only property of the report interface returns the body of the report, which is a reportbody object containing the detailed report information.
... syntax let reportbody = reportinstance.body returns a reportbody object containing the detailed report information.
... depending on what type the report is, the object returned will actually be a deprecationreportbody, interventionreportbody, crashreportbody, or featurepolicyviolationreportbody.
ResizeObserver - Web APIs
constructor resizeobserver() creates and returns 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 returns a domrectreadonly object containing the new size of the observed element when the callback is run.
... if the target is an html element, the returned contentrect is the element's content box.
... if the target is an svgelement, the returned contentrect is the svg's bounding box.
Response.error() - Web APIs
WebAPIResponseerror
the error() method of the response interface returns a new response object associated with a network error.
... note: this is mainly relevant to serviceworkers; the error method is used to return an error if you so wish it.
... return value a response object.
SVGGradientElement - Web APIs
svggradientelement.gradientunits read only returns an svganimatedenumeration corresponding to the gradientunits attribute on the given element.
... svggradientelement.gradienttransform read only returns an svganimatedtransformlist corresponding to attribute gradienttransform on the given element.
... svggradientelement.spreadmethod read only returns an svganimatedenumeration corresponding to attribute spreadmethod on the given element.
getBBox() - Web APIs
the coordinates returned 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 return the actual bounding box at the time the method was called—even in case the element has not yet been rendered.
... getbbox returns different values than getboundingclientrect(), as the latter returns value relative to the viewport syntax let bboxrect = object.getbbox(); return value the returned value is a svgrect object, which defines the bounding box.
SVGGraphicsElement - Web APIs
svggraphicselement.getbbox() returns a domrect representing the computed bounding box of the current element.
... svggraphicselement.getctm() returns a dommatrix representing the matrix that transforms the current element's coordinate system to its svg viewport's coordinate system.
... svggraphicselement.getscreenctm() returns 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 return value is the item inserted into the list.
... getitem(in unsigned long index) svgpathseg returns the specified item from the list.
... the returned item is the item itself and not a copy.
Screen.orientation - Web APIs
the orientation read-only property of the screen interface returns the current orientation of the screen.
... syntax var orientation = window.screen.orientation; return value an instance of screenorientation representing the orientation of the screen.
... note that older, prefixed versions returned a domstring equivalent to screenorientation.type.
ScreenOrientation - Web APIs
properties screenorientation.typeread only returns the document's current orientation type, one of "portrait-primary", "portrait-secondary", "landscape-primary", or "landscape-secondary".
... screenorientation.angleread only returns the document's current orientation angle.
... methods screenorientation.lock() locks the orientation of the containing document to its default orientation and returns a promise.
Selection.getRangeAt() - Web APIs
the selection.getrangeat() method returns 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 return.
... return value the specified range object.
Selection.toString() - Web APIs
the selection.tostring() method returns a string currently being represented by the selection object, i.e.
... syntax sel.tostring() return value a string representing the selection.
... description this method returns the currently selected text.
Sensor - Web APIs
WebAPISensor
accelerometer ambientlightsensor gyroscope linearaccelerationsensor magnetometer orientationsensor properties sensor.activated read only returns a boolean indicating whether the sensor is active.
... sensor.hasreading read only returns a boolean indicating whether the sensor has a reading.
... sensor.timestamp read only returns the time stamp of the latest sensor reading.
Sensor APIs - Web APIs
for example, the accelerometer interface returns 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.'); return; } // use the sensor.
... ambientlightsensorsecure context returns the current light level or illuminance of the ambient light around the hosting device.
ServiceWorkerContainer.getRegistration() - Web APIs
the method returns 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 return.
... return value a promise that resolves to a serviceworkerregistration object or undefined.
SourceBuffer - Web APIs
sourcebuffer.buffered read only returns the time ranges that are currently buffered in the sourcebuffer.
...returns a promise which is fulfilled once the buffer has been appended.
...returns 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 return.
... return 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 return undefined.
SpeechGrammar - Web APIs
properties speechgrammar.src sets and returns a string containing the grammar from within in the speechgrammar object instance.
... speechgrammar.weight optional sets and returns 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 return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set in line 4.
SpeechRecognitionEvent.interpretation - Web APIs
the interpretation read-only property of the speechrecognitionevent interface returns 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 returned value can be of any type.
... if no semantic interpretation has been returned by the speec recognition system, null will be returned.
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 returns 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 returns a human-readable name that represents the voice.
... speechsynthesisvoice.voiceuri read only returns the type of uri and location of the speech synthesis service for this voice.
Storage.getItem() - Web APIs
WebAPIStoragegetItem
the getitem() method of the storage interface, when passed a key name, will return that key's value, or null if the key does not exist, in the given storage object.
... return value a domstring containing the value of the key.
... if the key does not exist, null is returned.
Storage.key() - Web APIs
WebAPIStoragekey
the key() method of the storage interface, when passed a number n, returns the name of the nth key in a given storage object.
... return value a domstring containing the name of the key.
... if the index does not exist, null is returned.
Storage.length - Web APIs
WebAPIStoragelength
the length read-only property of the storage interface returns the number of data items stored in a given storage object.
... syntax length = storage.length; return 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 returns the number of items in the storage: function populatestorage() { localstorage.setitem('bgcolor', 'yellow'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'cats.png'); return localstorage.length; // should return 3 } note: for a real world example, see our web storage demo.
Storage - Web APIs
WebAPIStorage
properties storage.length read only returns an integer representing the number of data items stored in the storage object.
... methods storage.key() when passed a number n, this method will return the name of the nth key in the storage.
... storage.getitem() when passed a key name, will return that key's value.
StorageManager.estimate() - Web APIs
this method operates asynchronously, so it returns a promise which resolves once the information is available.
... return value a promise that resolves to an object which conforms to the storageestimate dictionary.
... the returned values are not exact; between compression, deduplication, and obfuscation for security reasons, they will be imprecise.
StorageManager - Web APIs
methods storagemanager.estimate() secure context returns a promise that resolves to a storageestimate object containing usage and quota numbers for your origin.
... storagemanager.persist() secure context returns a promise that resolves to true if the user agent is able to persist your site's storage.
... storagemanager.persisted() secure context returns 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 returns a list of the available storage types.
... methods storagequota.queryinfo returns 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 returns 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 return an empty cookie jar when third-party cookies are blocked.
...if that call returns false, we can then call document.requeststorageaccess(), returning the result so that then we can chain it onto the previous promise call.
... document.hasstorageaccess().then(hasaccess => { if (!hasaccess) { return 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) { return 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(() => { return 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 returns 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 returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc.
... body the response body returned by a successful fetch request is exposed by default as a readablestream, and can have a reader attached to it, etc.
... 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 returns a cssstylevalue object for the first value of the specified property.
... return 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 return a stylepropertymapreadonly object.
SubtleCrypto.exportKey() - Web APIs
return 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) { return 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) { return string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space.
Text.wholeText - Web APIs
WebAPITextwholeText
the text.wholetext read-only property returns the full text of all text nodes logically adjacent to the node.
... however, "); wholetext is just a property of text nodes that returns the string of data making up all the adjacent (i.e.
... now let’s return to our original problem.
getTrackById() - Web APIs
the texttracklist method gettrackbyid() returns the first texttrack object from the track list whose id matches the specified string.
... return 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 returns null.
TimeRanges - Web APIs
properties timeranges.length read only returns an unsigned long representing the number of time ranges represented by the time range object.
... methods timeranges.start() returns the time for the start of the range with the specified index.
... timeranges.end() returns the time for the end of the specified range.
Touch.force - Web APIs
WebAPITouchforce
the touch.force read-only property returns the amount of pressure the user is applying to the touch surface for a touch point.
... syntax touchitem.force; return value a float that represents the amount of pressure the user is applying to the touch surface.
...a value of 0.0 is returned if no value is known (for example the touch device does not support this property).
Touch.radiusX - Web APIs
WebAPITouchradiusX
summary returns the x radius of the ellipse that most closely circumscribes the area of contact with the touch surface.
... syntax var xradius = touchitem.radiusx; return 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
WebAPITouchListitem
the item() method returns the touch object at the specified index in the touchlist.
... return value touchpoint the requested touch object from the touchlist.
... returns 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 return.
... returns a trackdefault object.
... errors no specific errors are returned, but if the supplied index is great than or equal to trackdefaultlist.length, the operation will return undefined.
TransformStream - Web APIs
constructor transformstream() creates and returns 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() {return _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() {return _jstds_wm.get(this).decoder.encoding} get fatal() {return _jstds_wm.get(this).decoder.fatal} get ignorebom() {return _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 returns the found child.
...if no such child exists, returns 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) { return nodefilter.filter_accept; } }, false ); var node = treewalker.firstchild(); // returns 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 returns the found child.
...if no such child exists, returns 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) { return nodefilter.filter_accept; } }, false ); var node = treewalker.lastchild(); // returns 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 returns the found node.
...if no such node exists, returns 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) { return nodefilter.filter_accept; } }, false ); var node = treewalker.nextnode(); // returns 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 returns the found sibling.
... if there is no such node, return 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) { return nodefilter.filter_accept; } }, false ); treewalker.firstchild(); var node = treewalker.nextsibling(); // returns 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 returns the found node.
... if no such node exists, or if it is above the treewalker's root node, returns 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) { return nodefilter.filter_accept; } }, false ); var node = treewalker.parentnode(); // returns 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 returns the found node.
...if no such node exists,or if it is before that the root node defined at the object construction, returns 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) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previousnode(); // returns 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 returns the found sibling.
... if there is no such node, return 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) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previoussibling(); // returns null as there is no previous sibiling specifications specification status comment domthe definition of 'treewalker.previoussibling' in that specification.
TypeInfo - Web APIs
WebAPITypeInfo
properties typeinfo.typename read only returns a domstring indicating the type's name.
... typeinfo.typenamespace read only returns a domstring indicating the type's namespace within the schema.
... methods typeinfo.isderivedfrom() returns a boolean.
URL.toJSON() - Web APIs
WebAPIURLtoJSON
the tojson() method of the url interface returns 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() return value a usvstring.
... examples const url = new url("/docs/web/api/url/tostring"); url.tojson(); // should return the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification.
URL.toString() - Web APIs
WebAPIURLtoString
the url.tostring() stringifier method returns a usvstring containing the whole url.
... syntax const href = url.tostring() return value a usvstring.
... examples const url = new url("/docs/web/api/url/tostring"); url.tostring(); // should return 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 returns all the values associated with a given search parameter as an array.
... syntax urlsearchparams.getall(name) parameters name the name of the parameter to return.
... return value an array of usvstrings.
USBConfiguration - Web APIs
properties usbconfiguration.configurationvalueread only returns the configuration value of this configuration.
... usbconfiguration.configurationnameread only returns the name provided by the device to describe this configuration.
... usbconfiguration.interfacesread only returns an array containing instances of the usbinterface describing each interface supported by this configuration.
getTrackById - Web APIs
the videotracklist method gettrackbyid() returns the first videotrack object from the track list whose id matches the specified string.
... return 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 returns null.
WebGL2RenderingContext.getInternalformatParameter() - Web APIs
the webgl2renderingcontext.getinternalformatparameter() method of the webgl 2 api returns information about implementation-dependent support for internal formats.
...possible values: gl.samples: returns a int32array containing sample counts supported for internalformat in descending order.
... return value depends on the requested information (as specified with pname).
WebGLRenderingContext.getActiveAttrib() - Web APIs
the webglrenderingcontext.getactiveattrib() method of the webgl api returns a webglactiveinfo object containing size, type, and name of a vertex attribute.
...this value is an index 0 to n - 1 as returned by gl.getprogramparameter(program, gl.active_attributes).
... return value a webglactiveinfo object.
WebGLRenderingContext.getAttribLocation() - Web APIs
the webglrenderingcontext.getattriblocation() method of the webgl api returns the location of an attribute variable in a given webglprogram.
... return value a glint number indicating the location of the variable name if found.
... returns -1 otherwise.
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
the webglrenderingcontext.getframebufferattachmentparameter() method of the webgl api returns information about a framebuffer's attachment.
... return value depends on the requested information (as specified with pname).
... pname parameter return value gl.framebuffer_attachment_object_type a glenum indicating the type of the texture.
WebGLRenderingContext.scissor() - Web APIs
return 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 returns 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 returns the initialized context.
... in case of error, it displays an error message and returns 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."; return 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); return 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."; return; } 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())) return; 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; return; } 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."; return 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); return 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())) return; 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; return; } 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."; return 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); return 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())) return; 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() { return [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."; return 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); return 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())) return; 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() { return [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."; return 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); return 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())) return; 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; return; } 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."; return 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); return 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; } } return 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); return 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; return texture; } function ispowerof2(value) { return (value & (value - 1)) == 0; ...
...without performing the above configuration, webgl requires all samples of npot textures to fail by returning transparent black: rgba(0,0,0,0).
... return { 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 returns an array of strings, one for each supported extension.
...for example: var float_texture_ext = gl.getextension('oes_texture_float'); the return 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 returned 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 returned 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
saturn'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 saturn'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 returns 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 returned 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 returned 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 returns, 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 return, 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() returns an array of animation objects currently in effect on elements in the document.
...it returns the created animation object instance.
... element.getanimations() returns 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 return a storage object; calling sessionstorage on a document will return 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); return true; } catch(e) { return 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 returns the data value.
Window.innerWidth - Web APIs
WebAPIWindowinnerWidth
the read-only window property innerwidth returns the interior width of the window in pixels.
... more precisely, innerwidth returns the width of the window's layout viewport.
... example // this will return the width of the viewport var intframewidth = window.innerwidth; // this will return the width of the frame viewport within a frameset var intframewidth = self.innerwidth; // this will return the width of the viewport of the closest frameset var intframesetwidth = parent.innerwidth; // this will return the width of the viewport of the outermost frameset var intouterframesetwidth = top.innerwid...
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
the window interface's matchmedia() method returns 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.
... return value a new mediaquerylist object for the media query.
... usage notes you can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query.
Window.pkcs11 - Web APIs
WebAPIWindowpkcs11
summary returns the pkcs11 object, which is used to install drivers and other software associated with the pkcs11 protocol.
... if pkcs11 isn't supported, this property returns null.
... note: this property has been returned 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") return; // ...
... if (event.origin !== "http://example.com") return; // event.source is popup // event.data is "hi there yourself!
... if (event.origin !== "http://example.com:8080") return; // 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 returns a promise that resolves to the existing windowclient.
... return 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) return client.focus(); } if (clients.openwindow) return 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.returnvalue 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 returnvalue to be set e.returnvalue = ''; }); guarantee the browser unload by removing the returnvalue property of the event window.addeventlistener('beforeunload', function (e) { // the absence of a returnvalue property on the event will guarantee the browser unload happens delete e['returnvalue']; }); 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 return visit and update the content as desired.
WindowOrWorkerGlobalScope.btoa() - Web APIs
return 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); } return 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); } return 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, returning a promise which is fulfilled once the response is available.
... return value a promise that resolves to a response object.
...status: ${response.status}`); } return 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 returning 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 returned to the browser's event loop.
... return value undefined.
WorkerGlobalScope.location - Web APIs
the location read-only property of the workerglobalscope interface returns 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 return 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 return strange results, but this should be fixed soon.
WorkerLocation - Web APIs
urlutilsreadonly.href read only is a stringifier that returns a domstring containing the whole url of the script executed in the worker.
... urlutilsreadonly.origin read only returns a domstring containing the canonical form of the origin of the specific location.
... urlutilsreadonly.tostring() returns a domstring containing the whole url of the script executed in the worker.
HTML in XMLHttpRequest - Web APIs
function htmlinxhr() { if (!window.xmlhttprequest) return false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'document'; } catch(e) { return true; } return false; } view on jsfiddle this method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of...
...this test file is small and is not well-formed xml: <title>&amp;&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(callback) { if (!window.xmlhttprequest) { window.settimeout(function() { callback(false); }, 0); return; } 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); return aexec ?
XMLHttpRequest.send() - Web APIs
if the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.
... if the request is synchronous, this method doesn't return until the response has arrived.
... return value undefined.
XPathResult.iterateNext() - Web APIs
the iteratenext() method of the xpathresult interface iterates over a node set result and returns the next node from it or null if there are no more nodes.
... syntax var node = result.iteratenext(); return value the next node within the node set of the xpathresult.
... invalid_state_err if the document is mutated since the result was returned, 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 returned.
... methods xpathresult.iteratenext() if the result is a node set, this method iterates over it and returns the next node from it or null if there are no more nodes.
... xpathresult.snapshotitem() returns 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 returns a javascript iterator which can then be used to iterate over the keys used to reference each item in the array of input sources.
... return value a javascript iterator that can be used to walk through the keys for each entry in the list of input sources.
... the values returned 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() returns a javascript iterator that can walk over the list of xrinputsource objects contained in the array, from first to last.
... return 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 returned value.
XRPermissionDescriptor.optionalFeatures - Web APIs
the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace.
... the "interface" column in the table below indicates which of the two types is returned 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 returned object.
XRReferenceSpaceType - Web APIs
values the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace.
... the "interface" column in the table below indicates which of the two types is returned 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 returned object.
XRRigidTransform() - Web APIs
the xrrigidtransform() constructor creates and returns a new xrrigidtransform object, representing the position and orientation of a point or object.
... return 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 returned 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 returns 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 returning to its previous pose.
... in other words, its position and orientation both return to their prior configurations.
XRRigidTransform.matrix - Web APIs
the read-only xrrigidtransform property matrix returns the transform matrix represented by the object.
... the returned 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 returned 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 returns the transform matrix in the form of a 16-member float32array.
... xrrigidtransform.inverse read only returns 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 return the original object.
XRSystem: isSessionSupported() - Web APIs
the xrsystem method issessionsupported() returns a promise which resolves to true if the specified webxr session mode is supported by the user's webxr device.
... return 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 returned 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 returns a promise which resolves to an xrsession object through which you can manage the requested type of webxr session.
... return 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 returned 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 returns 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 returned, 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() returns 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 returned 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 returned, 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() returns 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 returns 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() returns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution.
... return 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
return value type: hresult.
... if this method succeeds, it returns s_ok.
... otherwise, it returns 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 return 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(); return true; } else { return 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(); return true; } else { return 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();return true;" type="text" maxlength=6 id="y1" value="0.33" class='field'> <label for="x2">x2 = </label><input onchange="updatecanvas();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updatecanvas();return 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) { return x * scaling + rulers; } function reversex(x) { return (x - rulers) / scaling; } function lx(x) { //used when drawing vertical lines to prevent subpixel blur var result = cx(x); return math.round(result) == result ?
... result + 0.5 : result; } function cy(y) { return (1 - y) * scaling + margin; } function reversey(y) { return (margin - y) / scaling + 1; } function ly(y) { // used when drawing horizontal lines to prevent subpixel blur var result = cy(y); return 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
WebCSStransform
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.5turn); 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() returns a string that indicates the type of the specified object.
... syntax exsl:object-type(object) parameters object the object whose type is to be returned.
... returns 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
WebEXSLTmathhighest
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:highest() returns 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 returned.
... returns a result tree fragment consisting of copies of the nodes returned by math:max().
math:lowest() - EXSLT
WebEXSLTmathlowest
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:lowest() returns 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 returned.
... returns a result tree fragment consisting of copies of the nodes returned by math:min().
math:max() - EXSLT
WebEXSLTmathmax
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:max() returns the maximum value of a node-set.
... syntax math:max(nodeset) parameters nodeset the node-set whose highest value is to be returned.
... returns a result tree fragment representing the highest valued node's numeric value as a string.
math:min() - EXSLT
WebEXSLTmathmin
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:min() returns the minimum value of a node-set.
... note: syntax math:min(nodeset) parameters nodeset the node-set whose lowest value is to be returned.
... returns 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() returns the intersection of two node-sets.
... in other words, it returns a node-set containing all the nodes that exits in both nodeset1 and nodeset2.
... returns a node-set containing the nodes that existed in both nodeset1 and in nodeset2.
set:leading() - EXSLT
WebEXSLTsetleading
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:leading() returns the nodes in one node-set that come before the first node in the other node-set.
... returns 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 returned.
set:trailing() - EXSLT
WebEXSLTsettrailing
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:trailing() returns the nodes in one node-set that come after the first node in the other node-set.
... returns 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 returned.
Sets (set) - EXSLT
WebEXSLTset
set:difference()set:difference() returns the difference between two node-sets.
... in other words, it returns a node-set whose nodes are in one node-set but not in the other.set:distinct()set:distinct() returns a subset of the nodes in the specified node-set, returning 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() returns the intersection of two node-sets.
... in other words, it returns a node-set containing all the nodes that exits in both nodeset1 and nodeset2.set:leading()set:leading() returns the nodes in one node-set that come before the first node in the other node-set.set:trailing()set:trailing() returns the nodes in one node-set that come after the first node in the other node-set.
str:concat() - EXSLT
WebEXSLTstrconcat
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes str:concat() returns a string containing all the string values in a node-set concatenated together.
... returns a string whose value is all the string values of the nodes in nodeset concatenated together.
... if nodeset is empty, an empty string is returned.
str:split() - EXSLT
WebEXSLTstrsplit
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, returning a node-set containing the resulting strings.
... returns a node-set of token elements, each containing one token from the string.
... example str:split('book, phone, computer, chair', ', ') returns a node set like: <token>book</token> <token>phone</token> <token>computer</token> <token>chair</token> specifications exslt - str:split ...
str:tokenize() - EXSLT
WebEXSLTstrtokenize
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, returning a node-set containing the resulting strings.
... returns a node-set of token elements, each containing one token from the string.
... example: str:tokenize('2007-09-14-03t11:40:23', '-t:') returns 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 returns a final result with no significant recognition.
... result speechrecognitionevent web speech api the speech recognition service returns 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 returned 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 return 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 return value from the handler determines if the event is canceled.
... the specific handling of the return 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 returns 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"); return; } } // 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 returned by the validity property of the element types listed above.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
image data from a cors-enabled image returned 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 return 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
WebHTMLElementinputpassword
note: the line feed (u+000a) and carriage return (u+000d) characters are not permitted in a password value.
... when setting the value of a password control, line feed and carriage return characters are stripped out of the value.
...the text must not include carriage returns or line feeds.
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
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-return).
... 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 returns null).
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
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 returned to the invoking web content.
... access-control-allow-origin a returned 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 returned with the resource, the response is ignored by the browser and not returned to web content.
HTTP caching - HTTP
WebHTTPCaching
when a web cache has a requested resource in its store, it intercepts the request and returns its copy instead of re-downloading from the originating server.
...if so, the server returns 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 return 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 returned.
... 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 return 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 return 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 return.
... string.match() won't return groups if the /.../g flag is set.
... (?<name>x) named capturing group: matches "x" and stores it on the groups property of the returned 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) { return 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 return '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 returns, 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() { return `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() { return `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() { return 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) { return n * 3; } } class biggertriple extends triple { static triple(n) { return 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() { return 'static method has been called'; } static anotherstaticmethod() { return 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() { return '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 returns an value.
... difference between legacy and es2015 iterator protocols the value was returned directly as a return 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; return { next: function(){ if(nextindex < array.length){ return 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 return 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 return statements.
... var x = function() { return 1; } var obj = { count: function() { return 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() { return 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) { return num * 2; }); // typeerror: obj.map is not a function use an array instead: let numbers = [1, 4, 9]; numbers.map(function(num) { return 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"; return this; } dog.prototype.name = function(name) { this.name = name; return 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 return this; } dog.prototype.name = function(name) { this.dogname = name; return 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) { return objectarray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return 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 return; // 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) return; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion this recursive function is missing a base case.
... get name(){ return 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(){ return 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 () { return 'hello world'; } // syntaxerror: function statement requires a name you can use a function expression (assignment) instead: var greet = function() { return '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 () { return "moin"; } } // syntaxerror: function statement requires a name this would work, for example: function greeter() { german: function g() { return "moin"; } } object methods if you intended to create a method of an object, you will need to create an object.
... var greeter = { german: function () { return "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 returned: function multiply(multiplier, ...theargs) { return theargs.map(element => { return 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() return sortedargs } console.l...
...og(sortrestargs(5, 3, 7, 1)) // 1, 3, 5, 7 function sortarguments() { let sortedargs = arguments.sort() return 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() return 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]() return value the initial value given by the values() iterator.
... by default, using arr[symbol.iterator] will return 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...'); return; } 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 returns it without modifying its length.
... return value the modified array.
... return 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
return 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) { return 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 return 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]]) { // return 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.
... return value a new array with each element being the result of the callback function and flattened to a depth of 1.
...simply return 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, returning true or false as appropriate.
... return 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 returned.
Array.prototype.splice() - JavaScript
return value an array containing the deleted elements.
... if only one element is removed, an array of one element is returned.
... if no elements are removed, an empty array is returned.
ArrayBuffer - JavaScript
static methods arraybuffer.isview(arg) returns true if arg is one of the arraybuffer views, such as typed array objects or a dataview.
... returns false otherwise.
... instance methods arraybuffer.prototype.slice() returns 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 returns the old value at that position.
... return 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); // returns 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 returns the old value at that position.
... return 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); // returns 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 returns the old value at that position whether it was equal to the expected value or not.
... return 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); // returns 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 returns the old value at that position.
... return 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); // returns 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 returns the old value at that position.
... return 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); // returns 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 returns the old value at that position.
... return 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); // returns 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 returns a string which is either "ok", "not-equal", or "timed-out".
... return 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 return 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 returns the old value at that position.
... return 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); // returns 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 returns a string representing the source code of the object.
... syntax booleanobj.tosource() boolean.tosource() return value a string representing the source code of the object.
... examples native function for the built-in boolean object, tosource returns the following string indicating that the source code is not available: function boolean() { [native code] } specifications not part of any standard.
DataView - JavaScript
return 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'); return 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 return return littleendian ?
Date.prototype.getUTCFullYear() - JavaScript
the getutcfullyear() method returns the year in the specified date according to universal time.
... syntax dateobj.getutcfullyear() return value a number representing the year in the given date according to universal time.
... description the value returned by getutcfullyear() is an absolute number that is compliant with year-2000, for example, 1995.
Date.now() - JavaScript
the static date.now() method returns the number of milliseconds elapsed since january 1, 1970 00:00:00 utc.
... syntax var timeinms = date.now(); return 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() { return 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
returns new timestamp.
... return 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 returned 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 returns the number of milliseconds since january 1, 1970 00:00:00 utc until the time represented by the updated date instance.
... return 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 returned 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 returns the number of milliseconds since january 1, 1970 00:00:00 utc until the time represented by the updated date instance.
... return 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 returned from the getutcminutes(), getutcseconds(), and getutcmilliseconds() methods are used.
Date.prototype.toDateString() - JavaScript
the todatestring() method returns 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() return value a string representing the date portion of the given date object in human readable form in english.
...calling tostring() will return the date formatted in a human readable form in english.
Date.prototype.toGMTString() - JavaScript
the exact format of the value returned by togmtstring() varies according to the platform and browser, in general it should represent a human readable date string.
... syntax dateobj.togmtstring() return 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 returns a string value that is similar to the following form.
Date.prototype.toJSON() - JavaScript
the tojson() method returns a string representation of the date object.
... syntax dateobj.tojson() return value a string representation of the given date.
...calling tojson() returns a string (using toisostring()) representing the date object's value.
Date.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object.
... syntax dateobj.tosource() date.tosource() return value a string representing the source code of the given date object.
... examples native function for the built-in date object, tosource() returns 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 returns the time portion of a date object in human readable form in american english.
... syntax dateobj.totimestring() return value a string representing the time portion of the given date in human readable form in american english.
...calling tostring() will return the date formatted in a human readable form in american english.
Date.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a date object.
... syntax dateobj.valueof() return value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date.
... description the valueof() method returns 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 returns code that could eval to the same error.
... syntax e.tosource() return value a string containing the source code of the error.
... examples using tosource calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error.
Error.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified error object.
... syntax e.tostring() return value a string representing the specified error object.
...'' : string(msg); if (name === '') { return msg; } if (msg === '') { return name; } return 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 returns a string representing the source code of the object.
... syntax function.tosource(); return value a string representing the source code of the object.
... examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string.
Function - JavaScript
this can be seen with the code (function(){}).constructor === function, which returns true.
... function.prototype.tostring() returns a string representing the source code of the function.
... var x = 10; function createfunction1() { var x = 20; return new function('return x;'); // this |x| refers global |x| } function createfunction2() { var x = 20; function f() { return x; // this |x| refers local |x| above } return 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 returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.
...instead, a generator instance can be returned from a generator function: function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "generator { }" instance methods generator.prototype.next() returns a value yielded by the yield expression.
... generator.prototype.return() returns the given value and finishes the generator.
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.datetimeformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this datetimeformat object.
... syntax datetimeformat.resolvedoptions() return 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 returned, as future versions may return a string value identifying the runtime’s default time zone instead.
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
the intl.displaynames.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current displaynames object.
... syntax displaynames.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object.
... description the object returned 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() returns 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 returns a string based on the locale and options provided when instantiating intl.displaynames.
... intl.displaynames.prototype.resolvedoptions() returns 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 returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
... return value an array of components which contains the formatted parts from the list.
... description whereas intl.listformat.prototype.format() returns a string being the formated version of the list (according to the given locale and style options), formattoparts() returns an array of the different components of the formated string.
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
the intl.listformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current listformat object.
... syntax listformat.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object.
... description the object returned 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() returns the locale's full locale identifier string.
... syntax locale.tostring() return value the locale's unicode locale identifier string.
...calling the tostring method on a locale object will return 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" return the order-of-magnitude for formatted number.
... "engineering" return 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 returned.
Intl.PluralRules - JavaScript
static methods intl.pluralrules.supportedlocalesof() returns 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() returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
... intl.pluralrules.prototype.select() returns a string indicating which plural rule to use for locale-aware formatting.
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
the intl.relativetimeformat.prototype.formattoparts() method returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
... return 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 returns 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 return (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 return the value.
... json.stringify(value[, replacer[, space]]) return 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
return 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'); // returns true.
...mymap.has('bar'); // returns false.
Map.prototype.has() - JavaScript
the has() method returns a boolean indicating whether an element with the specified key exists or not.
... return 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') // returns true mymap.has('baz') // returns false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.has' in that specification.
Math.acosh() - JavaScript
the math.acosh() function returns 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.
... return 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) { return 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() returns nan.
Math.asinh() - JavaScript
the math.asinh() function returns 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.
... return 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 return 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))) return x > 0 ?
Math.atan() - JavaScript
the math.atan() function returns 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.
... return value the arctangent (in radians) of the given number.
... description the math.atan() method returns a numeric value between -π2-\frac{\pi}{2} and π2\frac{\pi}{2} radians.
Math.atan2() - JavaScript
the math.atan2() function returns 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 return 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 returns a numeric value between -π and π representing the angle theta of an (x, y) point.
Math.atanh() - JavaScript
the math.atanh() function returns 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.
... return 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) { return 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 returned.
Math.cbrt() - JavaScript
the math.cbrt() function returns 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.
... return 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) { return function cbrt(x){ // ensure negative numbers remain negative: return x < 0 ?
Math.cosh() - JavaScript
the math.cosh() function returns 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.
... return 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) { return (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); return (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 returns ex - 1, where x is the argument, and e the base of the natural logarithms.
... return 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) { return 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 returns the sine of a number.
... return value the sine of the given number.
... description the math.sin() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians.
Math.sinh() - JavaScript
the math.sinh() function returns 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.
... return 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) { return (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); return (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 returns 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.
... return 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); return a == infinity ?
Number.isFinite() - JavaScript
return 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, return true.
... polyfill if (number.isfinite === undefined) number.isfinite = function(value) { return 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 returns a floating point number.
... if a number cannot be parsed from the argument, it returns nan.
... return value a floating point number parsed from the given string.
Number.parseInt() - JavaScript
the number.parseint() method parses a string argument and returns an integer of the specified radix or base.
... return 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 returned.
Number.prototype.toPrecision() - JavaScript
the toprecision() method returns a string representing the number object to the specified precision.
... return 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 returned 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 returns a string representing the source code of the object.
... syntax numobj.tosource() number.tosource() return value a string representing the source code of the object.
... examples native function for the built-in number object, tosource() returns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() returns a string representing the source code.
Object() constructor - JavaScript
if the value is null or undefined, it will create and return an empty object.
... otherwise, it will return an object of a type that corresponds to the given value.
... if the value is an object already, it will return the value.
Object.fromEntries() - JavaScript
return 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 returns 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 returns 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
return value a boolean indicating whether or not the given object is frozen.
...var accessor = { get food() { return '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 return true.
Object.preventExtensions() - JavaScript
return value the object being made non-extensible.
... examples using object.preventextensions // object.preventextensions returns 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 return it.
Object.seal() - JavaScript
return value the object being sealed.
...object.defineproperty(obj, 'foo', { get: function() { return '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 returning it.
Object.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns a string representing the object.
... syntax obj.tolocalestring() return value a string representing the object.
... description object's tolocalestring returns the result of calling tostring().
Promise.reject() - JavaScript
the promise.reject() method returns a promise object that is rejected with a given reason.
... return value a promise that is rejected with the given reason.
... description the static promise.reject function returns a promise that is rejected.
handler.defineProperty() - JavaScript
return value the defineproperty() method must return a boolean indicating whether or not the property has been successfully defined.
... in strict mode, a false return value from the defineproperty() handler will throw a typeerror exception.
... const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return 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); return reflect.defineproperty(target, prop, descriptor); } }); object.
handler.get() - JavaScript
return value the get() method can return any value.
... const p = new proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 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) { return 20; } }); p.a; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[get]]' in that specification.
handler.has() - JavaScript
return value the has() method must return a boolean value.
... const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return 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) { return false; } }); 'a' in p; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[hasproperty]]' in that specification.
handler.ownKeys() - JavaScript
return value the ownkeys() method must return an enumerable object.
... const p = new proxy({}, { ownkeys: function(target) { console.log('called'); return ['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) { return [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(object.getownpropertynames(p)); // typeerror: proxy [[ownpropertykeys]] must return an array // with only string and symbol elements specifications specification ecmascript (ecma-262)the definition of '[[ownpropertykeys]]' in that specification.
Reflect.deleteProperty() - JavaScript
return value a boolean indicating whether or not the property was successfully deleted.
...it returns 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] // returns true if no such property exists reflect.deleteproperty({}, 'foo') // true // returns 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 returns a property descriptor of the given property if it exists on the object, undefined otherwise.
... return value a property descriptor object if the property exists in target object; otherwise, undefined.
... description the reflect.getownpropertydescriptor method returns a property descriptor of the given property if it exists in the target object, undefined otherwise.
RegExp.prototype[@@match]() - JavaScript
return 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 return same result.
... class myregexp extends regexp { [symbol.match](str) { let result = regexp.prototype[symbol.match].call(this, str); if (!result) return null; return { group(n) { return 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
return value an array containing substrings as its elements.
...for example, the following two examples return the same result.
... class myregexp extends regexp { [symbol.split](str, limit) { let result = regexp.prototype[symbol.split].call(this, str, limit); return 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 returns 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 returns an empty string for empty regular expressions.
... instead, the string "(?:)" is returned.
RegExp.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object.
... syntax regexobj.tosource() return value a string representing the source code of the given regexp object.
... examples native function for the built-in regexp object, tosource() returns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() returns a string representing the source code.
Set.prototype.entries() - JavaScript
the entries() method returns 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 returned.
... syntax myset.entries() return 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 returns a boolean indicating whether an element with the specified value exists in a set object or not.
... return value returns 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'); // returns true myset.has('bar'); // returns false var set1 = new set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); // returns 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 returns 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 returns values of set elements.
... syntax myset.values(); return 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, returning true or false as appropriate.
... return 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; } return 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 returns 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 returned 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 return [...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 () { return 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 returned as-is.
... return 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) { return 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
return 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 returns 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)) // returns 4, which is the index of the first capital letter "j" console.log(str.search(redot)) // returns -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, returning true or false as appropriate.
... return value true if the given characters are found at the beginning of the string; otherwise, false.
...rawpos|0 : 0; return 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 returns the calling string value converted to lower case, according to any locale-specific case mappings.
... return value a new string representing the calling string converted to lower case, according to any locale-specific case mappings.
... description the tolocalelowercase() method returns the value of the string converted to lower case according to any locale-specific case mappings.
String.prototype.toLowerCase() - JavaScript
the tolowercase() method returns the calling string value converted to lower case.
... syntax str.tolowercase() return value a new string representing the calling string converted to lower case.
... description the tolowercase() method returns the value of the string converted to lower case.
String.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object.
... syntax string.tosource() str.tosource() return value a string representing the source code of the calling object.
... examples native function for the built-in string object, tosource() returns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() returns a string representing the source code.
String.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified object.
... syntax str.tostring() return value a string representing the calling object.
...for string objects, the tostring() method returns a string representation of the object and is the same as the string.prototype.valueof() method.
String.prototype.trim() - JavaScript
syntax str.trim() return value a new string representing the str stripped of whitespace from both ends.
... description the trim() method returns the string stripped of whitespace from both ends.
... if (!string.prototype.trim) { string.prototype.trim = function () { return 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(); return value a new string representing the calling string stripped of whitespace from its beginning (left end).
... description the trimstart() / trimleft() methods return 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(){ return 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(){ return this.replace(r,'') } } })(proto,'trimstart'); })(window); */ examples usi...
String.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a string object.
... syntax str.valueof() return value a string representing the primitive value of a given string object.
... description the valueof() method of string returns 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 returns it if found.
... return value an existing symbol with the given key if found; otherwise, a new symbol is created and returned.
...in that case, that symbol is returned.
Symbol.species - JavaScript
property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to return array objects in your derived array class myarray.
... for example, when using methods such as map() that return the default constructor, you want these methods to return 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]() { return 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 returns a string representing the source code of the object.
... syntax symbol.tosource() var sym = symbol() sym.tosource() return value a string representing the source code of the object.
... examples native function for the built-in symbol object, tosource returns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource returns a string representing the source code.
Symbol.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified symbol object.
... syntax symbol().tostring() return value a string representing the specified symbol object.
...for symbol objects, the tostring method returns a string representation of the object.
Symbol.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a symbol object.
... syntax symbol().valueof() return value the primitive value of the specified symbol object.
... description the valueof method of symbol returns the primitive value of a symbol object as a symbol data type.
TypedArray.from() - JavaScript
return 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) { return elem; }; if (typeof func !== 'function') { throw new typeerror('specified argument is not a function'); } obj = object(obj); if (!obj['length']) { return 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]; } return 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 returns 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 returned, which means the typed array will not be searched.
... return value the first index of the element in the array; -1 if not found.
TypedArray.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns 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 returned, i.e.
... return value the last index of the element in the array; -1 if not found.
TypedArray.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns 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 returned are entirely implementation dependent.
... return value a string representing the elements of the typed array.
TypedArray.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements.
... syntax typedarray.tostring() return value a string representing the elements of the typed array.
...for typedarray objects, the tostring method joins the array and returns one string containing each typed array element separated by commas.
WeakMap.prototype.delete() - JavaScript
return 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); // returns true.
... wm.has(window); // returns false.
WeakMap.prototype.has() - JavaScript
the has() method returns a boolean indicating whether an element with the specified key exists in the weakmap object or not.
... return value boolean returns 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); // returns true wm.has('baz'); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification.
WeakSet.prototype.has() - JavaScript
the has() method returns a boolean indicating whether an object exists in a weakset or not.
... return value boolean returns 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); // returns true myset.has(obj); // returns 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)) return; 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 return false afterwards.
... weakset.prototype.has(value) returns a boolean asserting whether value is present in the weakset object or not.
WebAssembly.CompileError - JavaScript
instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error.
... webassembly.compileerror.prototype.tostring() returns 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); // returns 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 returns the function that created this object's instance.
... instance methods global.prototype.valueof() old-style method that returns 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 returns the new value).
WebAssembly.LinkError - JavaScript
instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error.
... webassembly.linkerror.prototype.tostring() returns 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); // returns 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 returns the buffer contained in the memory.
...its buffer property will return 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 return a sharedarraybuffer.
WebAssembly.Module.customSections() - JavaScript
the webassembly.customsections() function returns a copy of the contents of all custom sections in the given module with the given string name.
... return 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 returned.
WebAssembly.Module.exports() - JavaScript
the webassembly.module.exports() function returns an array containing descriptions of all the declared exports of the given module.
... return 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 return 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, returns a copy of the contents of all custom sections in the module with the given string name.
... webassembly.module.exports() given a module, returns an array containing descriptions of all the declared exports.
... webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports.
WebAssembly.RuntimeError - JavaScript
instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error.
... webassembly.runtimeerror.prototype.tostring() returns 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); // returns 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, returning both a module and its first instance.
... webassembly.instantiatestreaming() compiles and instantiates a webassembly module directly from a streamed underlying source, returning both a module and its first instance.
... webassembly.validate() validates a given typed array of webassembly binary code, returning whether the bytes are valid webassembly code (true) or not (false).
globalThis - JavaScript
you can also use function('return 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('return 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') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new error('unable to locate global object'); }; var globals = getglobal(); if (typeof globals.settimeout !== 'function') { // no settimeout in this environment!
uneval() - JavaScript
return value a string representing the source code of object.
... note: this will not return a json representation of object.
... examples using uneval var a = 1; uneval(a); // returns a string containing 1 var b = '1'; uneval(b); // returns a string containing "1" uneval(function foo() {}); // returns "(function foo(){})" var a = uneval(function foo() { return 'hi'; }); var foo = eval(a); foo(); // returns "hi" specifications not part of any standard.
Decrement (--) - JavaScript
the decrement operator (--) decrements (subtracts one from) its operand and returns a value.
... syntax operator: x-- or --x description if used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.
... if used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing.
Increment (++) - JavaScript
the increment operator (++) increments (adds one to) its operand and returns a value.
... syntax operator: x++ or ++x description if used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
... if used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.
Logical OR assignment (||=) - JavaScript
syntax expr1 ||= expr2 description short-circuit evaluation the logical or operator works like this: x || y; // returns x when x is truthy // returns 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 returned by the api you're checking against.
... if an empty string is returned (a falsy value), ||= must be used, otherwise you want to use the ??= operator (for null or undefined return values).
class expression - JavaScript
'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "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() { return '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() { return 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 returns the value 3 * x.
... function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return 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; } return 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]() { return { i: 0, next() { if (this.i < 3) { return promise.resolve({ value: this.i++, done: false }); } return promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asynciterable) { console.log(num); } })(); // 0 // 1 // 2 iterating over async generators since the return values of async generators con...
... async function* streamasynciterable(stream) { const reader = stream.getreader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaselock(); } } // fetches data from url and calculates response size using the async generator.
... responsesize += chunk.length; } console.log(`response size: ${responsesize} bytes`); // expected output: "response size: 1071472" return 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) { return 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() { return this.value }; this.tostring = function() { return 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() { return 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) { return zipcode_invalid; } else { return zipcode_unknown_error; } } return z; } a = verifyzipcode(95060); // returns 95060 b = verifyzipcode(9560); // returns -1 c = verifyzipcode('a'); // returns -1 d = verifyzipcode('95060'); // returns 95060 e = verifyzipcode('95060 1234'); // returns 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 returns true or false.
... returns returns 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 return false.
key - XPath
WebXPathFunctionskey
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the key function returns a node-set of nodes that have the given value for the given key.
... value the returned node-set will contain every node that has this value for the given key.
... returns a node set.
lang - XPath
WebXPathFunctionslang
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the lang function determines whether the context node matches the given language and returns boolean true or false.
... returns 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 return false.
local-name - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the local-name function returns 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 returned.
... returns a string.
name - XPath
WebXPathFunctionsname
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the name function returns 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 returned.
... returns a string representing the qname of a node.
not - XPath
WebXPathFunctionsnot
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the not function evaluates a boolean expression and returns the opposite value.
... returns 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 returns the opposite value.
substring - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the substring function returns a part of a given string.
...if omitted, the returned string will contain every character from thestart position to the end ofstring.
... returns a string.
sum - XPath
WebXPathFunctionssum
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the sum function returns 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 returned.
... returns 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 returns a notification object that can be used to display the specified message with an optional url.
... return 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 returned by require.
... so a if you import a module using require, you can't change the properties of the object returned: 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"); returns 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"); returns string : the decoded string ...
private-browsing - Archive of obsolete content
it returns 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 returns 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 returned by the server in the response's content-type header.
...it is returned by the get(), head(), post(), put() or delete() method of a request object.
widget - Archive of obsolete content
returns 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) return; // update widget displayed text: view.content = tab.url.match(/^https/) ?
windows - Archive of obsolete content
} }); returns 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.
... returns browserwindow : properties browserwindows browserwindows provides access to all the currently open browser windows as browserwindow objects.
event/core - Archive of obsolete content
count() returns a number of event listeners registered for the given event type on the given event target.
... returns number : number of listeners ...
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 returned by that function.
... error : function|regexp either a constructor function returning 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 returns a promise that resolves upon the predicate returning a truthy value, which is called every interval milliseconds.
... returns promise : waituntil returns a promise that becomes resolved once the predicate returns a truthy value.
util/collection - Archive of obsolete content
returns collection : the collection.
... returns collection : the collection.
Modifying the Page Hosted by a Tab - Archive of obsolete content
in the add-on script, tab.attach() returns 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 returned 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) return; // 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 returns 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") return; // only documents // if (win != win.top) return; //only top window.
... // if (win.frameelement) return; // 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() returns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond.
... date.now() date.now() returns the number of milliseconds elapsed since 1 january 1970 00:00:00 utc.
Windows - Archive of obsolete content
however, window.open() returns 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(); return; } 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) { return false; } if (thisitem.getattributens) { return thisitem.getattributens(ns, nsatt); } else if (ns === null) { return 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 return 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' return attrs[j].nodevalue; } } thisitem = thisitem.parentnode; } } } return ''; // if not found (some implementations return '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 returns 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 returns.
Extension Versioning, Update and Compatibility - Archive of obsolete content
the information returned 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 return 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 return the object itself.
... for instance, calling jquery.noconflict(true) will remove the window.jquery and window.$ variables, and return 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 return 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 returns.
... function module(uri) { if (!/^[a-z-]+:/.exec(uri)) uri = /([^ ]+\/)[^\/]+$/.exec(components.stack.caller.filename)[1] + uri + ".jsm"; let obj = {}; components.utils.import(uri, obj); return 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="return 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[ return this.getattribute('name'); ]]></getter> <setter><![cdata[ this.setattribute('name', val); ]]></setter> </property> p...
...you can also have a return value using the return 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 return value, which has well-defined possible values.
... } return 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 returns a reference to our root directory and creates it if necessary.
... localdir.create(ci.nsifile.directory_type, 0774); } return 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) return; // 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") return; 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
returns 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.
... returns false if the battery is discharging.
chargingtimechange - Archive of obsolete content
returns 0 if the battery is fully charged.
... returns positive infinity, if the battery is discharging or if the implementation is unable to report the remaining charging time.
levelchange - Archive of obsolete content
returns 0 if the battery is empty and the system is about to suspend.
... returns 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); return; // ...
... var frequency = 0, currentsoundsample; var samplerate = 44100; function requestsounddata(sounddata) { if (!frequency) { return; // 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 return 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 return 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: returns true if a class is marked with the "final" attribute.
... */ function isfinal(c) { if (!c.attributes) return false; for each (let a in c.attributes) if (a.name == 'user' && a.value == 'final') return true; return 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 return 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"); return 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(); return [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 return 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 returns no results.
generateCRMFRequest() - Archive of obsolete content
the method generatecrmfrequest() will return 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 returned object to get the result of the crmf generation.
importUserCertificates - Archive of obsolete content
if the import operation succeeds, an empty string will be returned.
... if it fails, one of the following error strings will be returned: 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 return apply to both.
...to mitigate this effect, only return 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 return 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 return value of <tt>uname -s</tt> on the platform, plus the file suffix <tt>.mk</tt>.
... if the return 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 returned to the blockreflowstate instance after the new one has been destroyed.
... the blockbanddata then walks the collection of trapezoids that were returned 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 return the intersection of two abstract values.
... it is also acceptable for meet to return 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); return; } /* 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); return (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.
Binding Implementations - Archive of obsolete content
<method name="scrolltoindex"> <parameter name="index"/> <body> <![cdata[ if (index < 0) return; ...
... a getter contains script whose return value is handed back when the property is requested.
Example Sticky Notes - Archive of obsolete content
--> <getter><![cdata[ var st = this.innerhtml || ''; if (st != '') { var re = /<\/?[^>]+>/gi; return st.replace(re,''); } else { return ''; } ]]></getter> <setter><![cdata[ // "val" in setter contains the assignment value.
... // here we simply echoing it back: return val; ]]></setter> </property> <method name="setborder"> <!-- new method for the bound element.
copy - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
dirCreate - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
dirRemove - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
dirRename - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
diskSpaceAvailable - Archive of obsolete content
diskspaceavailable returns the amount of disk space available in bytes on the local disk.
... returns a double number representing the amount of space, in bytes, on the queried drive.
execute - Archive of obsolete content
(ignored on mac os) returns an integer error code.
... for a list of possible values, see return codes.
exists - Archive of obsolete content
exists returns a value indicating whether the specified file or directory exists.
... returns a boolean value specifying whether the file or directory does indeed exist or does not.
isDirectory - Archive of obsolete content
summary returns a boolean value indicating whether the specified filespecobject is a directory.
... returns a boolean value indicating whether the object is a directory or not.
isFile - Archive of obsolete content
summary returns a boolean value indicating whether the given filespecobject is a file.
... returns a boolean value indicating whether the filespecobject is a file or not.
macAlias - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
modDate - Archive of obsolete content
summary returns the last modified date of a specified file or directory.
... returns a double number representing the date that the file was last modified.
move - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
remove - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
rename - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
size - Archive of obsolete content
summary return the size of the given file in bytes.
... returns a number representing the size, in bytes, of the queried file.
windowsRegisterServer - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
windowsShortcut - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
addFile - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
deleteRegisteredFile - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
execute - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
gestalt - Archive of obsolete content
returns returns the requested information.
...this method returns null on unix and windows platforms.
getComponentFolder - Archive of obsolete content
getcomponentfolder returns an object representing the directory in which a component is installed.
... returns an object representing the directory in which the component is installed, or null if the component could not be found or if subdirectory refers to a file that already exists.
getFolder - Archive of obsolete content
summary returns an object representing one of the standard directories.
... returns a filespecobject representing one of netscape's standard directories, or null in case of error or if subdirectory refers to a file that already exists.
initInstall - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
logComment - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
createKey - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the creation.
... for a list of possible values, see return codes.
deleteKey - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion.
... for a list of possible values, see return codes.
setValue - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the action.
... for a list of possible values, see return codes.
setValueNumber - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the action.
... for a list of possible values, see return codes.
setValueString - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the action.
... for a list of possible values, see return codes.
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
if the name 'subdirname' refers to a directory, then the returned object will refer to this directory.
... the returned 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 return type: nsiautocompletesession adds a new session object to the autocomplete widget.
...this method returns the object passed in.
appendCustomToolbar - Archive of obsolete content
« xul reference home appendcustomtoolbar( name, currentset ) firefox only return type: element adds a custom toolbar to the toolbox with the given name.
...the method returns the dom element for the created toolbar.
appendItem - Archive of obsolete content
« xul reference home appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
getBrowserIndexForDocument - Archive of obsolete content
« xul reference home getbrowserindexfordocument( document ) return type: integer returns the index of the browser for the specified document in the tabbrowser the method was invoked on.
... the returned 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 ) return type: dom nodelist returns 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 returned by queryselectorall), the nodelist returned by this method is live.
getIcon - Archive of obsolete content
ArchiveMozillaXULMethodgetIcon
« xul reference home geticon( atab ) return type: string returns the url of the specified tab's favicon.
... if atab is null, the current tab's icon is returned.
getNextItem - Archive of obsolete content
« xul reference home getnextitem( startitem, delta ) return type: element this method returns the item a given distance (delta) after the specified startitem, or null if no such item exists.
... this example will return the item two rows after someitem: getnextitem ( someitem, 2 ); ...
getNotificationWithValue - Archive of obsolete content
« xul reference home getnotificationwithvalue( value ) return type: notification element retrieve the notification with a particular value.
...if no matching value is found, returns null.
getPreviousItem - Archive of obsolete content
« xul reference home getpreviousitem( startitem, delta ) return type: element this method returns the item a given distance (delta) before the specified startitem, or null if no such item exists.
... this example will return the item five rows before someitem: getpreviousitem ( someitem, 5 ); ...
getSelectedItem - Archive of obsolete content
« xul reference home getselecteditem( index ) return 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 return the first selected item: getselecteditem(0).
getSession - Archive of obsolete content
« xul reference home getsession( index ) obsolete since gecko 26 return type: nsiautocompletesession returns the session object with the given index.
... this will return an object of type nsiautocompletesession.
getSessionByName - Archive of obsolete content
« xul reference home getsessionbyname( name ) obsolete since gecko 26 return type: nsiautocompletesession returns the session object with the given name.
... this will return an object of type nsiautocompletesession.
getTabModalPromptBox - Archive of obsolete content
« xul reference home gettabmodalpromptbox( browser ) return type: object returns an object that manages tab-modal prompts for the specified browser.
... returns 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 return type: element add an item with the given id to the toolbar.
... the method returns the dom element for the created item.
insertItemAt - Archive of obsolete content
« xul reference home insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
...the new item element is returned.
loadGroup - Archive of obsolete content
« xul reference home loadgroup( group ) not in firefox return type: the first tab loads a group of pages into multiple tabs.
...this function returns a reference to the first tab loaded.
menulist.appendItem - Archive of obsolete content
« xul reference home appenditem( label, value, description ) return type: element creates a new menuitem element and adds it to the end of the menulist.
...the function returns the new item.
replaceGroup - Archive of obsolete content
« xul reference home replacegroup( group ) not in firefox return type: array of session history objects replaces existing tabs with a new set.
...this method returns 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()) return; event.target.setattribute("checked", "true"); } } </script> ...
...the example assumes that the showtoolbar() function might fail so if it returns 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 return key or right arrow key will open the menu.
... if it were a menuitem, then pressing the return key would have launched the command associated with it.
editable - Archive of obsolete content
« xul reference editable type: boolean returns true if the element is editable.
... autocomplete fields are editable so this property always returns true for those.
selectedIndex - Archive of obsolete content
« xul reference selectedindex type: integer returns the index of the currently selected item.
...returns -1 if no items are selected ...
Building Trees - Archive of obsolete content
the builder looks at the label for the corresponding cell, translates any variables or predicates into values, and returns 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 returns it.
Introduction - Archive of obsolete content
for each result returned 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 returned results.
XML Assignments - Archive of obsolete content
however, you cannot use a expression that returns a number in the query, as the query must return dom nodes as results.
... in this case, we use an expression that returns 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 returns 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 returned by getlasterror() are listed in the mozilla source file nsinstall.h.
More Wizards - Archive of obsolete content
remember to return 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(); return 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() returns 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" returned), 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/return).
... 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="return myfunction(event);"/> </window> preference type: id connects the element to a corresponding preference.
... open type: boolean returns true if the popup for a button-type colorpicker is open.
deck - Archive of obsolete content
ArchiveMozillaXULdeck
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 returns the index of the currently selected item.
...returns -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 returns 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 returns the containing menu element, or null if there isn't a containing menu.
menuseparator - Archive of obsolete content
control type: menu element returns 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 returns 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 ) return type: preference element returns 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 returns 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
ArchiveMozillaXULtab
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 returns the enclosing tabs element.
tabbox - Archive of obsolete content
selectedindex type: integer returns the index of the currently selected item.
...returns -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 return type: element add an item with the given id to the toolbar.
... the method returns the dom element for the created item.
window - Archive of obsolete content
if this value turns out to be less than 0, 0 is used.
...note: this has no effect if the tabs on top preference is turned off.
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="return dosave();" buttonlabelcancel="cancel" buttonaccesskeycancel="n" ondialogcancel="return docancel();"> <script> function dosave(){ //dosomething() return true; } function docancel(){ return 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.returnok) { 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 returned.
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)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return 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)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return 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) { return; } > getresponse(xhr); > }; > var headers = { > 'method': 'post', > 'content-type': soapclient.contenttype + '; charset="' + > soapclient.charset + '"', > 'content-length': soapclient.contentlength, > 'soapserver': soapclient.soapserver, > 'soapaction': soapreq.action > }; > for (var h in headers) { xhr.setrequestheader(h, headers[h]); } > xhr.send(cont...
application/http-index-format specification - Archive of obsolete content
all lines must be terminated by a carriage return followed by a line feed.
...quoted tokens are terminated by the next quote but may not contain carrage returns or new lines.
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 returning.
... if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and return immediately; the browser calls npp_print again with the npembedprint substructure of npprint.
NPN_CreateObject - Archive of obsolete content
returns the newly-allocated npobject.
...the newly created npobject's reference count is initialized to 1 before it is returned.
NPN_DestroyStream - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
NPN_GetURL - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
NPN_MemAlloc - Archive of obsolete content
returns if successful, the function returns a pointer to the allocated memory, in bytes.
... if insufficient memory is available, the plug-in returns null.
NPN_SetValue - Archive of obsolete content
returns if successful, the function should return nperr_no_error.
... if unsuccessful, the function should return the most relevant npapi error code.
NPN_SetValueForURL - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns an error code.
NPN_UserAgent - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary returns the browser's user agent field.
... returns a pointer to a buffer that contains the user agent field of the browser.
NPP_DestroyStream - Archive of obsolete content
returns if successful, the plug-in should return nperr_no_error.
... if unsuccessful, the plug-in should return an error code.
NPP_GetValue - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the function returns an error code.
NPP_HandleEvent - Archive of obsolete content
returns if the plug-in handles the event, the function should return true.
... if the plug-in ignores the event, the function returns false.
NPP_NewStream - Archive of obsolete content
returns if successful, the function should return nperr_no_error.
... if unsuccessful, the function should return one of the nperror error codes.
NPP_SetValue - Archive of obsolete content
returns if successful, the function should return nperr_no_error.
... if unsuccessful, the function should return the most relevant npapi error code.
NPP_SetWindow - Archive of obsolete content
returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
NPStream - Archive of obsolete content
can be zero for streams of unknown length, such as streams returned 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 returns it as an output parameter when the plug-in calls npp_newstream.
NP_GetMIMEDescription - Archive of obsolete content
np_getmimedescription returns 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) { return(mime_types_description); } two mime types const char* np_getmimedescription(void) { return "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) returns if successful, the function returns nperr_no_error.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
then the <description> would be: <description>this is &lt;b&gt;bold&lt;/b&gt;.</description> note that the "<" has been turned into "&lt;".
... and the ">" has been turned into "&gt;".
Sunbird Theme Tutorial - Archive of obsolete content
it is usual to turn off compression so that your theme's speed is maximized.
...it is usual to turn off compression so that your theme's speed is maximized.
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 returns 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) return level; for (i = 0; i < features.length; i++) if (typeof(object[features[i].name]) != 'undefined') { features[i].supported = true; ++level; } return 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 returned 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; return 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 return 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 return 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 returned from debug.mstraceasyncoperationstarting.
... }, function (error) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_error); debug.mstraceasynccallbackstarting(opid); }); debug.mstraceasynccallbackcompleted(); } function dosomethingasync() { return winjs.promise.as(true); } asyncwrapperfunction(); requirements supported in the internet explorer 11 standards document mode.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
asyncoperationid must correspond to the operation id previously returned from debug.mstraceasyncoperationstarting.
... }, function (error) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_error); debug.mstraceasynccallbackstarting(opid); }); debug.mstraceasynccallbackcompleted(); } function dosomethingasync() { return winjs.promise.as(true); } asyncwrapperfunction(); requirements supported in the internet explorer 11 standards document mode.
Enumerator - Archive of obsolete content
methods enumerator.atend returns a boolean value indicating if the enumerator is at the end of the collection.
... enumerator.item returns the current item in the collection.
VBArray.dimensions - Archive of obsolete content
the vbarray.dimensions method returns 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 />"; } return(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.
Number.toInteger() - Archive of obsolete content
if the target value is nan, null or undefined, 0 is returned.
... if the target value is false, 0 is returned and if true, 1 is returned.
Object.observe() - Archive of obsolete content
return 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); return {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 returns 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() return 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 returns 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 return 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 returns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes (").
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
it's a well-known maxim that if you stick around long enough, you get a chance to see the tides of history turn.
... getting the image back on top of the heading turned out to be a matter of relatively positioning the floated image, and then giving it a z-index value.
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 returns basic for conformance-level, should return full.
... version will return 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 returns 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 return 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 return 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) { ; } return 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 returns 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 returning 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 return value, not the function definition itself.
... var result = (function () { var name = "barry"; return 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 returned by each request may differ: the first call of a delete will likely return a 200, while successive ones will likely return 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 returned status code may change between requests: delete /idx/delete http/1.1 -> returns 200 if idx exists delete /idx/delete http/1.1 -> returns 404 as it just got deleted delete /idx/delete http/1.1 -> returns 404 learn more general knowledge definition of idempotent in the http specification.
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
a promise is an object that's returned by a function that has not yet completed its work.
... the promise literally represents a promise made by the function that it will eventually return a result through the promise object.
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
a signature can include: parameters and their types a return 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 return 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) // returns "false" // symbols are guaranteed to be unique.
... the method symbol.for(tokenstring) returns a symbol value from the registry, and symbol.keyfor(symbolvalue) returns 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...
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
the compiler could have coerced the 5 into a number and returned a sum of 14, but it did not.
... to return this result, you'd have to explicitly convert the 5 to a number using the number() method: sum = number(value1) + value2; ...
Assessment: Accessibility troubleshooting - Learn web development
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 return 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 return 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 return 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 return 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 returns 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 returns 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 return a version number.
... enter the command to start up the server in that directory: # if python version returned above is 3.x python3 -m http.server # on windows try "python" instead of "python3", or "py -3" # if python version returned 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')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; 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; return 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')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; 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; return 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 ); return; } // 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.
Test your skills: Basic controls - Learn web development
turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once.
... turn the second <fieldset>'s content into a set of checkboxes.
UI pseudo-classes - Learn web development
while it is being clicked on, or when the return/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 return 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
LearnHTMLTablesBasics
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 saturn 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.
...saturn) 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 — return 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 return 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 return 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/return.
... 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 return value.
Measuring performance - Learn web development
webpagetest.org is another example of a tool that automatically tests your site and returns useful metrics.
...for example, the firefox network monitor returns 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 returns the injected scripts to a browser.
... a reflected xss vulnerability occurs when user content that is passed to the server is returned immediately and unmodified for display in the browser.
Ember app structure and componentization - Learn web development
this is useful in such cases where we have an <input> being used with no corresponding html text that could be turned into a label.
...now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app.
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 returning 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 return a string reporting this.
... computed: { listsummary() { const numberfinisheditems = this.todoitems.filter(item =>item.done).length return `${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 returns 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/return to search for linting-related packages.
Deploying our app - Learn web development
if you get the error fatal: not a git repository returned, 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 returned like 2.0.2; if not, it'll return 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 return valid memory buffers, and never return null.
... do not use nscrt::strdup for returning 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 returns 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")) return 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) { return ns_error_out_of_memory; } return 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 returns the outer window.
Listening to events on all tabs
if any registered progress listener returns false from this method then the attempt to refresh will be blocked.
... return value true if the refresh may proceed.
mach
you will see a big mach error message when all that happened was an invoked command returned a non-0 exit code - possibly expectedly so in mozilla!
... the return 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 return a value from its message listener: // chrome script messagemanager.addmessagelistener("my-addon@me.org:my-e10s-extension-message", listener); function listener(message) { return "value from chrome"; } this value is then presented to the frame script in the return value of sendsyncmessage().
... because a single message can be received by more than one listener, the return value of sendsyncmessage() is an array of all the values returned 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, return values from sendsyncmessage() must be json-serializable, so chrome can't return 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); return 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) { return acontentwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidocshell) .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsicontentframemessagemanager); } ...
HTMLIFrameElement.executeScript()
syntax var mydomrequest = instanceofhtmliframeelement.executescript(script, options); return value a domrequest object that returns 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 returned as the request value.
HTMLIFrameElement.getContentDimensions()
note: the values returned are equivalent to document.body.scrollwidth and document.body.scrollheight.
... syntax var instanceofdomrequest = instanceofhtmliframeelement.getcontentdimensions(); returns 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 returns it as json.
... return value a promise that resolves to a json object representation of the loaded app's manifest.
mozbrowsercontextmenu
details the details property returns 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 returns true if the video has metadata and is bigger than 0 x 0, or false if not.
mozbrowsermetachange
details the details property returns an anonymous javascript object with the following properties: name a domstring representing the <meta> name attribute value.
...if not included, the value returned 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 returns it as json.
... htmliframeelement.getmanifest() retrieves the manifest of an app loaded in the browser <iframe> and returns it as json.
IPDL Type Serialization
return 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))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return 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 return 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) return target.value; if (target instanceof components.interfaces.nsirdfliteral) return target.value; return null; don't test the return value of queryinterface, it always returns 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)) return 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 returned 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 return true to remove the download and false to keep it.
Http.jsm
httprequest returns 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 returns.
ISO8601DateUtils.jsm
return value an iso 8601 format date string.
... return 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 returned, and the total number of add-ons that matched the query (in case the returned 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 returned add-ons, then calls the previously mentioned shownotification() routine, passing in as parameters a prompt including the name of the returned 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() return an error representing the fact that a file is closed.
... os.file.error.exists() return 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) return 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 returned by xre_getprocesstype(), so adjust as needed.
... block_analyzer.py will return 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 returns when not using nscomptr.
... double-addref: this happens most often when assigning the result of a function that returns 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 return an error when invoked on windows 3.1.
...nspr functions returning 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 returns 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 return).
PLHashComparator
it returns a nonzero value if the two values are equal, and 0 if the two values are not equal.
... remark the return value of plhashcomparator functions should be of type prbool.
PL_CompareStrings
if the two strings are equal, it returns 1.
... if the two strings are not equal, it returns 0.
PL_HashTableAdd
returns a pointer to the new entry.
... pl_hashtableadd returns null if there is not enough memory to create a new entry.
PL_strdup
returns a pointer to a new memory node in the nspr heap containing a copy of a specified string.
... returns the function returns one of these values: if successful, a pointer to a copy of the specified string.
PL_strlen
returns 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.
... returns if successful, the function returns length of the specified string.
PRDescIdentity
there are three well-known identities: pr_invalid_io_layer, an invalid layer identity, for error return 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 returns a reference to that copy.
PRFileMap
type returned 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 returns 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 return fd->lower->method->close(fd->lower)).
...in cases where this partial implementation occurs, the function returns an error indication with an error code of pr_invalid_method_error.
PRTimeParamFn
this type defines a callback function to calculate and return 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, returns the time zone information (offset from gmt and dst offset) at that time instant.
PR_Accept
returns the function returns 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 returns null with the error code pr_io_timeout_error.
PR_AtomicDecrement
returns the function returns the decremented value (i.e., the result).
...the value returned 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 returned from pr_opensharedmemory.
... returns address where shared memory is mapped, or null if an error occurs.
PR_Available
returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading.
... if the function fails, it returns the value -1.
PR_Available64
returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading.
... if the function fails, it returns the value -1.
PR_Calloc
returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null.
... call pr_geterror() to retrieve the error returned by the libc function malloc().
PR_CWait
if you specify pr_interval_no_timeout, the function returns if and only if the object is notified.
... returns the function returns 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 returned by a pr_queuejob function representing the job to be cancelled.
... returns prstatus ...
PR_Cleanup
syntax #include <prinit.h> prstatus pr_cleanup(void); returns the function returns one of the following values: if nspr has been shut down successfully, pr_success.
...when the primordial thread returns from main, the process immediately and silently exits.
PR_Close
returns one of the following values: if file descriptor is closed successfully, pr_success.
...on successful return, pr_close frees the dynamic memory and other resources identified by the fd parameter.
PR_CloseDir
returns if successful, pr_success.
...note that after a pr_closedir call, any prdirentry object returned 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 returned from a call to pr_opensemaphore.
... returns prstatus ...
PR_CloseSharedMemory
syntax #include <prshm.h> nspr_api( prstatus ) pr_closesharedmemory( prsharedmemory *shm ); parameter the function has these parameter: shm the handle returned from pr_opensharedmemory.
... returns prstatus.
PR_CreateFileMap
returns if successful, a file mapping of type prfilemap.
...the returned 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 returned from pr_opensharedmemory.
... returns 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 returned from pr_opensharedmemory.
... returns prstatus.
PR_DetachThread
returns the function returns nothing.
...the call returns after the nspr thread object is destroyed.
PR_EnterMonitor
description when the calling thread returns, 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 returns.
PR_ExplodeTime
returns nothing; the buffer pointed to by exploded is filled with the exploded time.
...upon return, the location pointed to by the exploded parameter contains the converted time value.
PR_FamilyInet
syntax #include <prnetdb.h> pruint16 pr_familyinet(void); returns the value of the address family for internet protocol.
...the returned 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 returned by a successful call to pr_getaddrinfobyname.
... returns the function returns a const pointer to the canonical hostname stored in the given praddrinfo structure.
PR_GetCurrentThread
returns the current thread object for the currently running code.
... syntax #include <prthread.h> prthread* pr_getcurrentthread(void); returns always returns 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 returned.
... returns the function returns a prdesctype enumeration constant that describes the type of file.
PR_GetError
returns the current thread's last set platform-independent error code.
... syntax #include <prerror.h> prerrorcode pr_geterror(void) returns the value returned is a 32-bit number.
PR_GetErrorTextLength
syntax #include <prerror.h> print32 pr_geterrortextlength(void) returns if a zero is returned, no error text is currently set.
... otherwise, the value returned is sufficient to contain the error text currently available.
PR_GetFileInfo
returns one of the following values: if the file information is successfully obtained, pr_success.
...the file size is returned as an unsigned 32-bit integer.
PR_GetFileInfo64
returns one of the following values: if the file information is successfully obtained, pr_success.
...the file size is returned as an unsigned 64-bit integer.
PR_GetHostByAddr
on output, this structure is filled in by the runtime if the function returns pr_success.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetHostByName
on output, this structure is filled in by the runtime if the function returns pr_success.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetOSError
returns the current thread's last set os-specific error code.
... syntax #include <prerror.h> print32 pr_getoserror(void) returns the value returned is a 32-bit signed number.
PR_GetPeerName
addr on return, the address of the peer connected to the socket.
... returns if successful, pr_success.
PR_GetRandomNoise
returns prsize value equal to the size of the random number actually generated, or zero.
...a return value of zero means that pr_getrandomnoise is not implemented on this platform, or there is no available noise to be returned at the time of the call.
PR_GetSockName
addr on return, the address of the socket.
... returns if successful, pr_success.
PR_GetUniqueIdentity
returns the function returns 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 returns the value pr_invalid_io_layer with the error code pr_out_of_memory_error.
PR_ImplodeTime
returns an absolute time value.
... description this function converts the specified clock/calendar time to an absolute time and returns the converted time value.
PR ImportTCPSocket
returns the function returns 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* returned 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 returned by a pr_queuejob function representing the job to be cancelled.
... returns prstatus ...
PR_Listen
returns the function returns 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
returns the time zone offset information that maps the specified prexplodedtime to local time.
... returns a time parameters structure that expresses the time zone offsets at the specified time.
PR_MALLOC
returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null.
... call pr_geterror() to retrieve the error returned by the libc function malloc().
PR_MemMap
returns the starting address of the memory region to which the section of file is mapped.
... returns null on error.
PR_NEWZAP
returns 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 returned by the libc function.
PR NewProcessAttr
returns 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 returns a pointer to the structure.
PR_NewThreadPrivateIndex
returns 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.
... returns the function returns one of the following values: if successful, pr_success.
PR_Open
if the file already exists, no action and null is returned.
...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 returns the function returns 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
returns pointer to prfilemap or null on error.
... description if the shared memory already exists, a handle is returned 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 returned from a call to pr_opensemaphore.
... returns prstatus ...
PR_PushIOLayer
returns the function returns 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 returns.
PR_Realloc
returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null.
... call pr_geterror() to retrieve the error returned 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 return.
... returns the function returns one of the following values: a positive number indicates the number of bytes actually received.
PR_RmDir
returns if successful, pr_success.
...if the directory is not empty, pr_rmdir fails and pr_geterror returns the error code pr_directory_not_empty_error.
PR_Seek
returns the function returns one of the following values: if the function completes successfully, it returns 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 returns -1.
PR_Seek64
returns the function returns one of the following values: if the function completes successfully, it returns 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 returns -1.
PR_SetThreadPrivate
returns the function returns one of the following values: if successful, pr_success.
...on return, the private data associated with the index is reassigned the new private data's value, even if it is null.
PR_Unmap
returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success.
...the parameter addr is the return 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 returning.
... returns the function returns 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 returns from its root function or the process abnormally terminates.
... pr_getcurrentthread returns 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 returned by nss.
...the data will be processed and either returned directly or sent to a callback function registered in the context.
NSS Memory allocation
after that function returns, 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 return it to the free list.
NSS 3.16 release notes
bug 981170: aeskeywrap_decrypt should not return secsuccess for invalid keys.
... bugs fixed in nss 3.16 this bugzilla query returns 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 returns 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 returns 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 returns 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 returns 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, return the constraints as encoded certificate extensions.
... bugs fixed in nss 3.19 this bugzilla query returns 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 returns 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 returns a seccomparison result.
... bugs fixed in nss 3.30 this bugzilla query returns 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_importandreturnprivatekey 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 return all certificates with public keys matching a particular private key this bugzilla query returns 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 returning 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) return pl_strdup("test"); else return 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 return the required subtemplate.
...the sub field of the template points to a callback function of type sec_asn1templatechooser that returns the subtemplate depending on the component data.
FC_CancelFunction
fc_cancelfunction is a legacy function that simply returns ckr_function_not_parallel.
... return value fc_cancelfunction always returns ckr_function_not_parallel.
FC_DecryptFinal
description fc_decryptfinal returns the last block of data of a multi-part decryption operation.
... return value examples see also fc_decryptinit, nsc_decryptfinal ...
FC_DigestKey
the digest for the entire message is returned by a call to fc_digestfinal.
... return value examples see also fc_digestinit, fc_digestfinal, nsc_digestkey ...
FC_DigestUpdate
the digest for the entire message is returned by a call to fc_digestfinal.
... return value examples see also fc_digestinit, fc_digestfinal, nsc_digestupdate ...
FC_EncryptFinal
description fc_encryptfinal returns the last block of data of a multi-part encryption operation.
... return value examples see also fc_encryptinit, nsc_encryptfinal ...
FC_GenerateKey
the handle of new key is returned.
... return value examples see also nsc_generatekey ...
FC_GenerateKeyPair
the handles of new keys are returned.
... return value examples see also nsc_generatekeypair ...
FC_GetFunctionStatus
description fc_getfunctionstatus is a legacy function that simply returns ckr_function_not_parallel.
... return value fc_getfunctionstatus always returns ckr_function_not_parallel.
FC_Initialize
return value fc_initialize returns the following return codes.
...(note: we probably should return ckr_host_memory instead.) the software integrity test or power-up self-tests failed.
FC_Login
return value fc_login() returns the following return codes.
... the function should return ckr_pin_incorrect in this case.
FC_SignRecover
if psignature is null only the length of the signature is returned in *pussignaturelen.
... return value examples see also nsc_signrecover ...
FC_SignUpdate
the signature for the entire message is returned by a call to fc_signfinal.
... return value examples see also fc_signinit, fc_signfinal, nsc_signupdate ...
FC_UnwrapKey
if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_unwrapkey may be called again with pwrappedkey set to retrieve the wrapped key.
... return value examples see also nsc_unwrapkey ...
FC_Verify
return value ckr_ok is returned on success.
... ckr_signature_invalid is returned for signature mismatch.
FC_VerifyRecover
if psignature is null only the length of the signature is returned in *pussignaturelen.
... return value examples see also nsc_verifyrecover ...
FC_VerifyUpdate
the result for the entire message is returned by a call to fc_verifyfinal.
... return value examples see also fc_verifyfinal, nsc_verifyupdate ...
FC_WrapKey
if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_wrapkey may be called again with pwrappedkey set to retrieve the wrapped key.
... return value examples see also nsc_wrapkey ...
NSC_Login
return value nsc_login() returns the following return codes.
... ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255).the function should return 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 return 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 return 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 return revocation status of a cert bug 412468: modify certutil bug 417092: modify pkix_certselector api to return 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 returns 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 return 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 return 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 returns 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]; return result; } as function sum(a) { var result = 0; for (var i=0; i < a.length; i++) result += a[i]; return 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("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { return 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 return false.
...for example, to test the decompilation of a simple function you could write: var f = (function () { return 1; }); expect = 'function () { return 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) { return 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 - returns jsval-width lins stobj_get_dslot - returns jsval-width lins stobj_set_dslot - stores jsval-width lins stobj_set_fslot - stores jsval-width lins box_jsval - returns 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 returns cx to the script's compartment before returning.
...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 returns true, and i can be cast to jsval by calling int_to_jsval(i).
... otherwise, int_fits_in_jsval returns false.
JS::Add*Root
on success, these functions return true.
... otherwise they report an out of memory error and return false.
JS::Compile
on success, js::compile stores an object representing the newly compiled script into script, and returns true.
... otherwise, it returns 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 returns true.
... otherwise, it returns 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 returns true.
... otherwise it returns 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 return true.
... otherwise, return false with a typeerror pending.
JS::GetSelfHostedFunction
on success, js::getselfhostedfunction returns a pointer to the newly created function.
... otherwise, it reports an out-of-memory error and returns null.
JS::Handle
method description const t *address() const returns a pointer to ptr.
... const t &get() const returns ptr.
JS::MutableHandle
method description const t &get() const returns *ptr.
... operator const t&() const t operator->() const t *address() returns ptr.
JS::NewFunctionFromSpec
on success, js::newfunctionfromspec returns a pointer to newly created function.
... on error, it returns nullptr.
JS::OrdinaryToPrimitive
on success, js::ordinarytoprimitive stores the converted value in *vp and returns true.
... on error or exception, it returns false, and the value left in *vp is undefined.
JS::Rooted
method description t &get() returns ptr.
... const t &get() const operator const t&() const t operator->() const t *address() returns a pointer to ptr.
JS::ToInt32
on success, js::toint32 stores the converted value in *out and returns true.
... on error or exception, it returns false, and the value left in *out is undefined.
JS::ToInt64
on success, js::toint64 stores the converted value in *out and returns true.
... on error or exception, it returns false, and the value left in *out is undefined.
JS::ToNumber
on success, js::tonumber stores the converted value in *out and returns true.
... on error or exception, it returns false, and the value left in *out is undefined.
JS::ToPrimitive
on success, js::toprimitive stores the converted value in *vp and returns true.
... on error or exception, it returns false, and the value left in *vp is undefined.
JS::ToUint16
on success, js::toint16 stores the converted value in *out and returns true.
... on error or exception, it returns false, and the value left in *out is undefined.
JS::ToUint32
on success, js::touint32 stores the converted value in *out and returns true.
... on error or exception, it returns false, and the value left in *out is undefined.
JS::ToUint64
on success, js::toint64 stores the converted value in *out and returns true.
... on error or exception, it returns false, and the value left in *out is undefined.
JSConvertOp
on success it must return a primitive value in *vp.
...(support for the other types may eventually be removed.) the callback returns true to indicate success or false to indicate failure.
JSFunction
the apis js_newfunction, js_definefunction, js_compilefunction, and their unicode equivalents return values of type jsfunction *.
... for native functions and jsapi-compiled functions - that is, functions returned 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 returns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x.
...it returns 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 return js_true.
... on failure, it must return js_false.
JSObjectOps.defaultValue
the jsclass.convert callback should convert obj to the given type, returning js_true with the resulting value in *vp on success, and returning 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 return 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], returning js_false on error or exception, js_true on success.
... if getting or setting, the new value is returned in *vp on success.
JSObjectOps.newObjectMap
return null on error, non-null on success.
...usually, the nrefs parameter to jsobjectops.newobjectmap will be 1, to count the ref returned to the caller on success.
JSObjectPrincipalsFinder
the callback returns 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, return 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 return a held (via jsprincipals_hold), non-null *principalsp out parameter.
... return 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 return the same value (excepting a few internal classes such as function, call, and block).
...implementations of this hook should return 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 return true if the property is resolved, or set *resolvedp to false and return true if the object has no lazy property with the given id; or return false to indicate any other error.
... obsolete since jsapi 36 the callback must return 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)); return (jsflatstring *)str; } name type description str jsstring * string to examine.
... description js_assert_string_is_flat asserts the string is flattened, and returns a pointer to jsflatstring.
JS_AddExternalStringFinalizer
description add a finalizer for external strings created by js_newexternalstring using a type-code returned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str).
... returns a nonnegative type index if there is room for finalizer in the global gc finalizers table, else returns -1.
JS_Add*Root
on success, these functions return js_true.
... otherwise they report an out of memory error and return js_false.
JS_BufferIsCompilableUnit
description given a buffer, return false if the buffer might become a valid javascript statement with the addition of more lines.
... otherwise return true.
JS_CheckAccess
on success, js_checkaccess returns 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 returns 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 return false to allow the exception to propagate to the caller.
...many jsapi functions can simply report an error and return false without building and throwing an exception object.
JS_CompareStrings
on success the function returns js_true.
... on error, it returns 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 return a pointer to the newly compiled function.
... on error or exception, they return null.
JS_CompileFunctionForPrincipals
on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals return a pointer to the newly compiled function.
... on error or exception, they return null.
JS_CompileScript
on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and returns true.
... otherwise, they report an error, stores null to *script, and return false.
JS_CompileScriptForPrincipals
on success, js_compilescriptforprincipals and js_compileucscriptforprincipals return a pointer to the compiled script.
... on error or exception, they return null.
JS_CompileUTF8File
on success, js_compileutf8file returns an object that represents the newly compiled script.
... otherwise it returns null.
JS_CompileUTF8FileHandle
on success, js_compileutf8filehandle reads file to eof and returns an object representing the newly compiled script.
... if an error occurs during compilation, js_compileutf8filehandle stops reading from the file and returns null.
JS_ConcatStrings
description js_concatstrings concatenates two js strings, str1 and str2, and returns the result.
...when the string concatenation fails null is returned.
JS_ConstructObject
on success, js_constructobject returns a pointer to the newly instantiated object.
... otherwise it returns null.
JS_ContextIterator
each call to js_contextiterator returns the next context in the cycle.
... js_contextiterator returns the new value of *iterp.
JS_ConvertArgumentsVA
if js_convertargumentsva successfully converts all arguments, it returns true.
... otherwise it returns false.
JS_ConvertValue
on success, js_convertvalue stores the converted value in *vp and returns true.
... on error or exception, it returns false, and the value left in *vp is undefined.
JS_DecompileFunction
if successful, js_decompilefunction returns a string containing the text of the function.
... otherwise, it returns null.
JS_DefaultValue
on success, js_defaultvalue stores the converted value in *vp and returns true.
... on error or exception, it returns false, and the value left in *vp is undefined.
JS_DefineConstDoubles
on success, js_defineconstdoubles/js_defineconstintegers returns true, indicating it has created all properties listed in the array.
... otherwise it returns false.
JS_DefineElement
on success, js_defineelement returns true.
... otherwise it returns false.
JS_DefineFunction
on success, js_definefunction and js_defineucfunction return a pointer to the new function.
... on error or exception, they return null.
JS_DefineFunctions
on success, js_definefunctions returns true.
... on error or exception, it stops defining functions and returns false.
JS_DefineObject
on success, js_defineobject returns 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 returns null.
JS_DefineProperties
on success, js_defineproperties returns true, indicating it has created all properties listed in the array.
... otherwise it returns false.
JS_DefineProperty
on success, js_defineproperty returns true.
... on error or exception, it returns false.
JS_DefinePropertyWithTinyId
on success, js_definepropertywithtinyid and js_defineucpropertywithtinyid return js_true.
... if the property already exists or cannot be created, they return js_false.
JS_DeleteProperty
if the hook returns false, the error is propagated.
... these functions return true on success, regardless of whether a property was actually deleted, and false on error or exception.
JS_EncodeStringToBuffer
it returns the length of the whole string encoding or (size_t)-1 if the string can't be encoded as bytes.
... if the returned value is greater than the length you specified, the string was truncated.
JS_EnterCrossCompartmentCall
on success, js_entercrosscompartmentcall returns a pointer to a jscrosscompartmentcall object that must be passed to js_leavecrosscompartmentcall.
... otherwise it returns null.
JS_EnterLocalRootScope
for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx.
... js_leavelocalrootscope(cx); return 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 returns js_true.
... otherwise it returns 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 returns js_true.
... otherwise it returns 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 returns true.
... otherwise it returns 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 returns js_true.
... otherwise it returns 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 returns true.
... otherwise it returns 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 return true.
... on an error or exception, these functions return false, and the value left in *vp is undefined.
JS_GetArrayLength
on success, js_getarraylength stores the length in *lengthp and returns true.
... on failure, it reports an error and returns false, and the value left in *lengthp is undefined.
JS_GetArrayPrototype
if an error occurs, it returns null.
... note: this expression might have different values over time if the global array property is modified, but this method returns only the original value.
JS_GetClass
description js_getclass returns a pointer to the jsclass associated with a specified js object, obj.
...if obj has no jsclass, this returns null.
JS_GetDefaultFreeOp
this article covers features introduced in spidermonkey 17 return default jsfreeop for the runtime.
... description js_getdefaultfreeop returns default jsfreeop for the runtime.
JS_GetErrorPrototype
this article covers features introduced in spidermonkey 38 return the original value of error.prototype.
... description js_geterrorprototype returns 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 returns the string closure stored in a jsstring created by calling js_newexternalstringwithclosure.
... str jsstring * the string for which to return the closure.
JS_GetFlatStringChars
syntax const jschar * js_getflatstringchars(jsflatstring *str); name type description str jsflatstring * the flattended string returned by js_flattenstring.
... description jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) return js_false; const jschar *chars = js_getflatstringchars(fstr) js_assert(chars); see also js_flattenstring bug 1037869 ...
JS_GetFunctionCallback
returns 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 returns the current function invocation callback, or null if there isn't one set up.
JS_GetFunctionName
the return 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 returned by this function is valid only as long as the specified function, fun, exists.
JS_GetFunctionPrototype
if an error occurs, it returns null.
... note: this expression might have different values over time if the global function property is modified, but this method returns only the original value.
JS_GetFunctionScript
description js_getfunctionscript returns a pointer to jsscript for the specified function, fun.
... if fun is a native function, it returns null.
JS_GetGCParameter
description js_getgcparameter returns the current parameter of the garbage collection.
... if successful, js_getgcparameter returns the current parameter.
JS_GetGlobalObject
this returns null if cx has no global object.
...the object returned 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 returns a pointer to the interned string.
... js_getinternedstringcharsandlength returns a pointer to the interned string and stores the length of it to *length.
JS_GetObjectPrototype
if an error occurs, it returns null.
... note: this expression might have different values over time if the global object property is modified, but this method returns 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 returns it, but obj.__parent__ === null.
... similarly, if an object's parent is an inner object, js_getparent simply returns it, but obj.__parent__ returns 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 returns true.
... otherwise, it returns false, and the value left in *vp is undefined.
JS_GetPositiveInfinityValue
description js_getpositiveinfinityvalue returns a js::value that represents an ieee floating-point positive infinity.
... js_getnegativeinfinityvalue returns 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 return true.
... on an error or exception, these functions return false, and the value left in *vp is undefined.
JS_GetPrototype
if js_getprototype returns false, that signals an exception, which should be handled as usual.
... otherwise, it stores a pointer to the prototype or null to *protop and returns true.
JS_GetRegExpFlags
description js_getregexpflags returns flags of the specified object, obj.
... if successful, js_getregexpflags returns the flags, otherwise returns false.
JS_GetRegExpSource
description js_getregexpsource returns a source string of the specified object, obj.
... if successful, js_getregexpsource returns a pointer to the source string, otherwise returns null.
JS_GetStringLength
return the length, in 16-bit code units, of a javascript string.
...this is the same as the length of the array returned by js_getstringchars, in char16_ts (not bytes).
JS_GetTypeName
returns a pointer to the string literal description of a specified js data type.
... description js_gettypename returns a pointer to a string literal description of a specified js data type, type.
JS_HasElement
if not, it sets *foundp to false and returns true (to indicate no error occurred).
... if the search fails with an error or exception, js_haselement returns false, and the value left in *foundp is undefined.
JS_IdToProtoKey
on success, js_idtoprotokey returns a jsprotokey.
... otherwise it returns jsproto_null.
JS_IdToValue
on success, js_idtovalue stores the converted value in *vp and returns true.
... otherwise it returns false.
JS_InternJSString
description js_internjsstring converts a string str to interned string (interned atom) and returns the result string as jsstring *.
... on failure, js_internjsstring returns nullptr.
JS_IsArrayObject
on success, returns true and sets isarray indicating whether obj is an array object or a wrapper around one.
... otherwise returns false on failure.
JS_IsBuiltinEvalFunction
this article covers features introduced in spidermonkey 17 return whether the given function is the global eval function.
... description js_isbuiltinevalfunction returns whether the given function is the global eval function.
JS_IsBuiltinFunctionConstructor
this article covers features introduced in spidermonkey 17 return whether the given function is the global function constructor.
... description js::iscallable returns whether the given function is the global function constructor.
JS_IsIdentifier
on successful, js_isidentifier stores the test result to *isidentifier and returns true, otherwise returns false and the value of *isidentifier is undefined.
... js_isidentifier which takes chars and length is infallible, so just returns whether the chars are an identifier.
JS_IsRunning
if a script is executing, js_isrunning returns true.
... otherwise it returns false.
JS_LeaveCompartment
leave a the compartment, returning to the compartment active before the corresponding js_entercompartment.
... oldcompartment jscompartment * value returned by previous call to js_entercompartment.
JS_LeaveCrossCompartmentCall
leave a the compartment, returning to the compartment active before the corresponding js_entercrosscompartmentcall.
... syntax void js_leavecrosscompartmentcall(jscrosscompartmentcall *call); name type description call jscrosscompartmentcall * value returned by previous call to js_entercrosscompartmentcall.
JS_New
on success, js_new returns a pointer to the new object.
... on error, it returns null.
JS_NewCompartmentAndGlobalObject
on success, js_newcompartmentandglobalobject returns a pointer to the new global object.
... otherwise it returns null.
JS_NewContext
on success, it returns a pointer to the new context.
... otherwise it returns 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 returns a pointer to the new string.
... otherwise it returns null.
JS_NewDoubleValue
on success, js_newdoublevalue stores a numeric jsval in *rval and returns js_true.
... otherwise it returns js_false and the value left in *rval is unspecified.
JS_NewFunction
(js_getfunctionid, passed the new function, will return null.) on success, js_newfunction returns a pointer to the newly created function.
... otherwise it reports an out-of-memory error and returns null.
JS_NewNumberValue
on success, js_newnumbervalue stores a numeric jsval in *rval and returns js_true.
... otherwise it returns js_false and the value left in *rval is unspecified.
JS_NewObject
on success, js_newobject returns a pointer to the new object.
... otherwise it returns null.
JS_NewPlainObject
on success, js_newplainobject returns a pointer to the new object.
... otherwise it returns nullptr.
JS_NewPropertyIterator
note also that while for..in includes properties inherited from prototypes, iterator objects do not.) on success, this returns an iterator object that can be passed to js_nextproperty to fetch the property ids.
... on error, it returns null.
JS_NewStringCopyN
on success, js_newstringcopyn and js_newucstringcopyn return a pointer to the new js string.
... otherwise they return null.
JS_ObjectIsFunction
js_objectisfunction returns true if obj is a function and false otherwise.
... if js_objectisfunction returns true, js_valuetofunction will always return non-null.
JS_ObjectIsRegExp
if so, js_objectisregexp returns true.
... otherwise it returns false.
JS_ReportErrorNumber
if errorcallback returns null, (???
...otherwise, if the jserrorformatstring returned 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 returns true.
... if no exception is pending, or if a second error occurs while trying to report the first one, it returns 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 return true.
... return 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) return 1 / v1 === 1 / v2; if (v1 !== v1 && v2 !== v2) return true; return 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, returning 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 returns a jsexceptionstate object holding this state.
...this function returns null if the engine was not built with support for exceptions.
JS_SetArrayLength
on success, js_setarraylength returns true.
... otherwise it returns false.
JS_SetOperationCallback
(in this case, the callback may terminate the script by returning js_false.) js_getoperationcallback returns the currently installed operation callback, or null if none is currently installed.
...obsolete since javascript 1.9.1 js_getoperationlimit returns the current operation limit, or js_max_operation_limit if no operation callback is currently installed.
JS_SetParent
on success, js_setparent returns js_true.
... otherwise, it reports an error or sets an exception and returns js_false.
JS_SetProperty
on success, js_setproperty returns true, and the value in v is left unchanged unless a hook or setter modified it.
... on error or exception, it returns false, and the value left in v is unspecified.
JS_SetPrototype
on success, js_setprototype returns true.
... otherwise it returns false.
JS_StringEqualsAscii
on successful, js_stringequalsascii stores the comparison result into *match and returns true, otherwise returns false.
... js_flatstringequalsascii always succeeds, and returns the comparison result.
JS_StringToVersion
returns a jsversion value representing the version string.
...js_stringtoversion may return 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 return 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 returns its js data type.
... the return 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 returns js_true.
... on error or exception, it returns js_false, and the value left in *bp is undefined.
JS_ValueToECMAInt32
on success, js_valuetoecmaint32 stores the converted value in *ip and returns js_true.
... on error or exception, it returns js_false, and the value left in *ip is undefined.
JS_ValueToId
on success, js_valuetoid stores the converted value in *idp and returns true.
... otherwise it returns false.
JS_ValueToInt32
on success, js_valuetoint32 stores the converted value in *ip and returns js_true.
... on error or exception, it returns 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 returns true.
... otherwise it returns false and the value left in *objp is unspecified.
JS_ValueToSource
on success, js_valuetosource returns a pointer to a string.
... on error or exception, it returns null.
JS_VersionToString
returns a string representation of a jsversion value.
...js_versiontostring may return 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 return new objects.
... js_getmethod obsolete since jsapi 23 js_getmethodbyid obsolete since jsapi 23 a spidermonkey extension allows a native function to return an lvalue—that is, a reference to a property of an object: js_setcallreturnvalue2 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_setcallreturnvalue2 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 returns 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 return 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 returns 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 returned 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 returns 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 returns 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 return 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 return 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 returned 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 return value if does not implement the given interface.
...*/ queryinterface: function(id) { if (id.equals(ci.imyinterface)) return this; throw cr.ns_error_no_interface; } }; ...
Components.utils.cloneInto
it returns 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.
... returns a reference to the cloned object.
Components.utils.createObjectIn
return 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) { return { 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 returncode 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 returns 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 returns.
..."component returned 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 returns.
... sent when the user returns from being idle.
nsDirectoryService
this service returns 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)) return rv; nscomptr<nsiproperties> directory; rv = svcmgr->getservicebycontractid("@mozilla.org/file/directory_service;1", ns_get_iid(nsiproperties), getter_addrefs(directory)); if (ns_failed(rv)) return rv; rv = directory->get(ns_os_temp_dir, ns_get_iid(nsifile), aresult); return rv; } note that ns_os_temp_...
NS_Alloc
return values this function returns 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 returned from ns_getmemorymanager.
NS_Realloc
return values this function returns 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 returned from ns_getmemorymanager.
BeginReading
« xpcom api reference summary the beginreading function returns 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; } return count; } see also length, endreading ...
EndReading
« xpcom api reference summary the endreading function returns 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 returned pointer, unless it is known that the string's internal buffer is null-terminated.
BeginReading
« xpcom api reference summary the beginreading function returns 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; } return count; } see also length ...
EndReading
« xpcom api reference summary the endreading function returns 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 returned pointer, unless it is known that the string's internal buffer is null-terminated.
Alloc
return values this function is infallible, therefore guaranteed to return a pointer to the newly allocated buffer.
... note: prior to gecko 13.0, this function returned nsnull if memory allocation failed.
Clone
return values this function returns nsnull if the memory allocation fails.
... otherwise, it returns a pointer to the newly allocated buffer.
HeapMinimize
return values this function return ns_ok if successful.
... otherwise, it returns an error code.
Realloc
return values this function returns nsnull if the memory allocation fails.
... otherwise, it returns a pointer to the newly allocated buffer.
amIWebInstallListener
return value true if the caller should start the installs.
... return value true if the caller should start the installs.
amIWebInstaller
return value true if the installation was successfully started.
... return value true if installation is enabled.
imgICache
any images from windows in private browsing mode will not be present in the cache returned from a call with a null parameter).
... return 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 returns.
... if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call returns.
jsdIStackFrame
after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface.
...line result return value ...
mozIAsyncFavicons
getfaviconlinkforicon/page will ignore any associated data if the favicon uri is "chrome:" and just return the same chrome uri.
...getfaviconlinkforicon/page will ignore any associated data if the favicon uri is "chrome:" and just return the same chrome uri.
mozIStoragePendingStatement
return value in versions of gecko prior to gecko 1.9.2, this returned 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 return 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() returns the next row from the result set.
...return value a mozistoragerow object containing the next row from the result set, or null if there are no more results.
mozIStorageVacuumParticipant
return value return true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed.
... you may wish to return 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 return value a combination of the flags above corresponding to the appropriate flags for this about uri.
... return value a fully constructed channel that will load the about uri.
GetAccessibleAbove
« nsiaccessible page summary this method returns an accessible node geometrically above this one.
... nsiaccessible getaccessibleabove(); return value returns an accessible node geometrically above this one.
GetAccessibleBelow
« nsiaccessible page summary this method returns an accessible node geometrically below this one.
... nsiaccessible getaccessiblebelow(); return value returns an accessible node geometrically below this one.
GetAccessibleRelated
« nsiaccessible page summary this method returns an accessible related to this one by the given relation type.
... return value returns an accessible which is related to the one provided by the given relation type.
GetAccessibleToLeft
« nsiaccessible page summary this method returns an accessible node geometrically to the left of this one.
... nsiaccessible getaccessibletoleft(); return value returns an accessible node geometrically to the left of this one.
GetAccessibleToRight
« nsiaccessible page summary this method returns an accessible node geometrically to the right of this one.
... nsiaccessible getaccessibletoright(); return value returns an accessible node geometrically to the right of this one.
GetRelation
« nsiaccessible page summary this method returns accessible relation for this accessible object by index.
... return value returns nsiaccessiblerelation object for this accessible.
GetRelations
« nsiaccessible page summary this method returns multiple accessible relations for this accessible object.
... nsiarray getrelations(); return value returns 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() returns the coordinates of the image accessible.
... getimagesize() returns 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 return the number of rows or cols.
... roworcolindex long return 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() returns 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.
... return value the nsiaccessible corresponding to the specified tree cell.
nsIAccessibleValue
methods setcurrentvalue() obsolete since gecko 1.9 (firefox 3) return a success condition of the value getting set.
... return 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 returns 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
return value a string indicating the status of the update upon return: "downloading" the update is being downloaded.
... return 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() returns successfully.
... they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() returns.
nsIBidiKeyboard
(supported on: win32, mac, gtk2) note: prior to gecko 1.9 this method used a parameter 'out prbool aisrtl' to return the value.
...return value true if the current keyboard is right-to-left, false if it is not.
nsICacheVisitor
return value returns true to start visiting all entries for this device, otherwise returns false to advance to the next device.
... return value returns 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 returns false to advance to the next device.
nsICachingChannel
this may return an error if cacheasfile is false.
...return value returns true if this channel's data is being loaded from the cache, otherwise returns false.
nsIChannelEventSink
by calling oldchannel->cancel() there is a certain freedom in implementing this method: if the return-value indicates success, a callback on callback is required.
...if the return 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 returned by requestcharset().
... return value the resolved charset, or an empty string if no charset could be determined.
nsICompositionStringSynthesizer
boolean dispatchevent(); return value if dispatched event's default is prevented, returns true.
... however, this must always return false since all dispatching dom events are not cancelable.
nsIContentFrameMessageManager
returns string: the decoded binary data.
... returns string: the base64-encoded ascii string.
nsIContentSniffer
return 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-") return "application/pdf"; // we detected a pdf file } catch (e) { // try to get information from arequest } ...
nsIController
return value return true if the specified command is currently available to be used; otherwise, it should return false.
... return value true if the specified command is supported; otherwise false.
nsICookieConsent
the policy for the given uri and channel is also returned.
... return value returns nscookiestatus.
nsICookieService
return value returns the resulting cookie string.
... return value returns the resulting cookie string.
nsIDOMClientRect
the type of box is specified by the method that returns such an object.
... it is returned by functions like element.getboundingclientrect.
nsIDOMGlobalPropertyInitializer
return value the initialized global property.
... ensure that you never return any internal xpcom objects to untrusted code.
nsIDOMStorageList
nsidomstorage nameditem( in domstring domain ); parameters domain the name of the domain for whom to return the storage object.
... return 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 returned 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.
... return value an xpath result.
nsIDOMXULSelectControlElement
selectedindex long selecteditem nsidomxulselectcontrolitemelement value domstring methods appenditem() nsidomxulselectcontrolitemelement appenditem( in domstring label, in domstring value ); parameters label value return value getindexofitem() long getindexofitem( in nsidomxulselectcontrolitemelement item ); parameters item return value getitematindex() nsidomxulselectcontrolitemelement getitematindex( in long index ); parameters index return value insertitemat() nsidomxulselectcontrolitemelement insertitemat( in long index, in domstring label, in domstring value ); parameters index label ...
... value return value removeitemat() nsidomxulselectcontrolitemelement removeitemat( in long index ); parameters index return value ...
nsIDialogParamBlock
return value the previously set integer, or 0 if no integer has been previously set at that index.
... return 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 returns the appropriate nsifile.
... xpcom file system aliases apersistent [out] this output parameter indicates to the caller whether or not the returned location is persistent.
nsIDocumentLoader
return value isbusy() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) boolean isbusy(); parameters none.
... return 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() returns the current nsidragsession.
... return value the current drag session, or null if no drag is in progress.
nsIErrorService
return value the url of the string bundle registered for that module.
... return value the key to use to retrieve the error string from the nsresult's module's string bundle.
nsIFileURL
the getter returns a reference to an immutable object.
... callers must clone before attempting to modify the returned nsifile object.
nsIFrameLoaderOwner
methods getframeloader() returns the frame loader object owned by this object.
...return value the nsiframeloader owned by this object.
nsIFrameMessageListener
if true, the response should be returned in the specified json object.
... json the json object in which to return the response if the message is being handled synchronously.
nsIGlobalHistory3
not all histories have them; this need not be supported (just return ns_error_not_implemented.
... return value the gecko flags for the uri.
nsIINIParserFactory
method overview nsiiniparser createiniparser(in nsilocalfile ainifile); methods createiniparser() creates an ini parser, returning the nsiiniparser object that you can use to parse it.
... return value the nsiiniparser object you can use to parse the ini file.
nsIJSCID
return value getservice() nsisupports getservice(); parameters none.
... return 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 return value of this function is passed back to the jetpack process.
...return value the new handle.
nsIJetpackService
method overview nsijetpack createjetpack(); methods createjetpack() this method creates a new jetpack process and returns an nsijetpack interface that represents it.
...return 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 returns the count of "active" requests (that is requests without the load_background bit set).
... requests nsisimpleenumerator returns the requests contained directly in this group.
nsIMemoryReporter
once that has been done, the reporter will be found by any client accessing the enumerator returned by nsimemoryreportermanager.enumeratereporters().
...the amount returned must never decrease over the lifetime of the application.
nsIMessageBroadcaster
getchildat() return a single subordinate message manager.
... returns nsimessagelistenermanager: the message manager at the given index.
nsIMicrosummary
return value returns true if the microsummaries are equal.
... note: this method returns 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 returned from the nsimicrosummaryservice.
...return 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() returns whether or not this database contains the given key.
...if there are no such messages, null may be returned.
nsIMsgFilterCustomAction
* * @param type the filter type * @param scope the search scope * * @return 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.) * * @return 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
requestreturnreceipt boolean readonly: default request for return receipt option for this identity.
... if this is set, the return receipt menu item on the compose window will be checked.
nsIMsgProtocolInfo
methods getdefaultserverport() returns the default port for a connection to a server of this account type.
... return 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) * @return 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 * @return true if matches */ boolean matchjunkscoreorigin(in string ajunkscoreorigin); matchbody /** * test if the body of the passed in message matches "this" search term.
nsIMsgThread
getchildat() returns the message at an index.
... getroothdr() nsimsgdbhdr getroothdr(out long index); return index changed to the index of the root.
nsINavHistoryFullVisitResultNode
this includes more detailed information than the result_type_visit query (which returns 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 returned 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 return false when the orientation isn't drop_on.
... return value return true if the drop is permitted or false if it isn't.
nsIObserverService
otherwise an error will be returned.
... return value returns an enumeration of all registered listeners.
nsIParentalControlsService
return value true if the block was successfully overridden, otherwise false.
... return value true if the block was successfully overridden, otherwise false.
nsIPipe
recall that a non-blocking stream will return 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 return 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() returns an array of property names.
... return value true if the property exists, false if the property does not exist.
nsIPropertyBag
nsivariant getproperty( in astring name ); parameters name the name to return the matching property.
... return 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 returned from asyncresolve.
...the value returned 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 returns successfully).
... return value true if the request has yet to reach completion.
nsIScriptError
note: nsiconsolemessage.message will return the error formatted with file/line information.
... return value a string representing the error message described by the nsiscripterror object.
nsIScriptableUnescapeHTML
return value an nsidomdocumentfragment of the element with the new text appended.
... return value the result of the plain text conversion.
nsISearchEngine
return value an nsisearchsubmission supportsresponsetype() determines whether the engine can return responses in the given mime type.
... return value returns true if the engine spec has a url with the given responsetype, false otherwise.
nsISmsRequestManager
return value the request id.
... return value the request id.
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 returns an nsisocketprovider representing that socket type.
... return value nsisocketprovider that handles the specified socket type.
nsIStreamListener
note: your implementation of this method must read exactly acount bytes of data before returning.
...you must read all of these bytes before returning to the caller.
nsIStringBundleOverride
return value an enumeration of nsipropertyelement objects for the keys that are overridden in the given string bundle.
... return value the override value.
nsISupportsCString
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsChar
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsDouble
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsFloat
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsID
methods tostring() this method returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsInterfacePointer
methods tostring() returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRBool
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRInt16
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRInt32
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRInt64
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRTime
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRUint16
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRUint32
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRUint64
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsPRUint8
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsISupportsString
methods tostring() this methods returns a string valued representation of the object.
...return value a string valued representation of the object.
nsITaskbarWindowPreview
methods getbutton() returns the specified button from the preview's toolbar.
... return value an nsitaskbarpreviewbutton describing the requested button.
nsIToolkitProfile
note: the unlocker object cannot be returned to javascript as the error causes an exception to be thrown.
... return value an nsiprofilelock object which holds a profile lock as long as you hold a reference to it.
nsIUpdate
return value an nsiupdatepatch object describing the specified patch.
... return value the patch object serialized into an nsidomelement.
nsIUpdateManager
methods getupdateat() returns the update at the specified index into the history list.
... return value the nsiupdate at the specified index into the history list.
nsIVersionComparator
return value if a and b are two version being compared, and the return 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) return a + "==" + b; else if(x > 0) return a + ">" + b; return 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 returns -1, 0, or 1 } see also toolkit version format ...
nsIWebBrowser
return value ns_ok listener was successfully added.
... return value ns_ok listener was successfully added.
nsIWebBrowserChrome3
return value a new link target, if appropriate.
... otherwise returns 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 returns false.
...return value whether an occurrence was found.
nsIWebBrowserPersist
the object that the embbedder supplies may also implement nsiinterfacerequestor and be prepared to return nsiauthprompt or other interfaces that may be required to download data.
... encode_flags_cr_linebreaks 512 output with carriage return line breaks.
nsIWebSocketChannel
the socket listener's methods are called on the thread that calls asyncopen() and are not called until after asyncopen() returns.
... if asyncopen() returns successfully, the protocol implementation promises to call at least onstart and onstop of the listener.
nsIWindowsShellService
the empty string returns the default value of the sub key.
... return 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 returned.
... return value an nsidomdocument.
nsIXULWindow
return value the newly minted window.
... return value the tree item corresponding to the given id, if any.
NS ENSURE SUCCESS
summary macro returns return-value if ns_failed(nsresult) evaluates to true, and shows a warning on stderr in that case.
... syntax ns_ensure_success(nsresult, return-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)) return rv; return ns_ok; } ...
NS_CStringAppendData
return values the ns_cstringappenddata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_CStringContainerInit
return values the ns_cstringcontainerinit function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_CStringCutData
return values the ns_cstringcutdata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_CStringGetData
return values the ns_cstringgetdata function returns the length of adata, measured in storage units (bytes).
...pruint32 countchar(const nsacstring& str, char c) { const char* data; pruint32 len = ns_cstringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ++count; } return count; } history this function was finalized for mozilla 1.7.
NS_CStringInsertData
return values the ns_cstringinsertdata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_CStringSetData
return values the ns_cstringsetdata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_CStringSetDataRange
return values the ns_cstringsetdatarange function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_CStringToUTF16
return values the ns_cstringtoutf16 function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_StringAppendData
return values the ns_stringappenddata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_StringContainerInit
return values the ns_stringcontainerinit function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_StringCutData
return values the ns_stringcutdata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_StringGetData
return values the ns_stringgetdata function returns the length of adata, measured in storage units (bytes).
... example code pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* data; pruint32 len = ns_stringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ++count; } return count; } history this function was frozen for mozilla 1.7.
NS_StringInsertData
return values the ns_stringinsertdata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_StringSetData
return values the ns_stringsetdata function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_StringSetDataRange
return values the ns_stringsetdatarange function returns ns_ok if successful.
... otherwise, it returns an error code.
NS_UTF16ToCString
return values the ns_utf16tocstring function returns ns_ok if successful.
... otherwise, it returns an error code.
XPCOM string functions
this is a low-level api.ns_cstringclonedatathe ns_cstringclonedata function returns 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 returns 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 return 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 returns nothing.
... adata and adatalen are marked as out, meaning that they act as "return values" for this method, and are changed during the method call.
wrappedJSObject
// constructor function helloworld() { }; helloworld.prototype = { hello: function() { return "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihelloworld)) throw components.results.ns_error_no_interface; return this; } }; xpconnect wrapping now let's get a reference to our component.
... the underlying object has a wrappedjsobject property that returns a js object.
XPIDL Syntax
MozillaTechXPIDLSyntax
lexically, tokens are delimited by whitespace (defined here as spaces, tabs, vertical tabs, form feeds, line feeds, and carriage returns, or [ \t\v\f\r\n] in regular expression form).
... libidl only considers a single line feed as a newline, and not carriage returns (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 returns a static xml file with the configuration, as described below.
... server_name autoconfig.*; return 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 return an ns_failed() return 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 *returnfilespec) = 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 returns the type of the server.
... specialfolder-foldertype afolder.flags & nsmsgfolderflags.<name> returns 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() returns 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 returns a c string and you want to modify the contents of this string.
ctypes.open
int add(int a, int b) { return 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, // return 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 ...
Browser Side Plug-in API - Plugins
npn_useragent returns the browser's user agent field.
... npn_version returns version information for the plug-in api.
Scripting plugins - Plugins
a plugin that wishes to be scriptable using this new mechanism needs to return 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 return 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.
Gecko Plugin API Reference - Plugins
npn_useragent returns the browser's user agent field.
... npn_version returns version information for the plug-in api.
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 return value from a function, returning 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) return rootchildren; let parentmap = childmapfor(site.parent); if (parentmap.has(site)) return parentmap.get(site); var m = new map; parentmap.set(site, m); return m; } for (let [site, total] of totals) { childmapfor(site); } // print the allocation count for |site|.
...</div> <script> function makefactory(type) { return function factory(content) { var elt = document.createelement(type); elt.textcontent = content; return 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) { return 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"; return 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); } return 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 return.) 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/return will open up the relevant file at that point in the style editor.
Examine and edit HTML - Firefox Developer Tools
they use white space such as spaces, returns, or tabs between their html elements because it makes markup more readable.
...it is now turned on by default.
Use the Inspector API - Firefox Developer Tools
attributes and functions: .selection - information about the inspector's selection: .isnode() - returns true if selection is node.
... .node - returns 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 return.
... 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 returned 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 return 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 returned 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 returns the current light level or illuminance of the ambient light around the hosting device.
... properties ambientlightsensor.illuminance returns 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 returned from getbytefrequencydata() parameters array the uint8array that the frequency domain data will be copied to.
... return 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 returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to.
... return 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 returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to.
... return value none.
Animation.currentTime - Web APIs
the animation.currenttime property of the web animations api returns 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 return value is null.
Animation.finish() - Web APIs
WebAPIAnimationfinish
return value none.
... elem.getanimations().foreach( function(animation){ return 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 returns 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) { return animation.finished } ) ).then( function() { return 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 returns an effecttiming object containing the timing properties for the animation effect.
... syntax animationtiming = animation.gettiming(); returns an effecttiming object.
AnimationEffect - Web APIs
methods animationeffect.gettiming() returns the effecttiming object associated with the animation containing all the animation's timing values.
... animationeffect.getcomputedtiming() returns the calculated timing properties for this animationeffect.
AnimationEvent() - Web APIs
the animationevent() constructor returns a newly created animationevent, representing an event in relation with an animation.
... return value a new animationevent, initialized per any provided options.
Attr.namespaceURI - Web APIs
WebAPIAttrnamespaceURI
the attr.namespaceuri read-only property returns the namespace uri of the attribute, or null if the element is not in a namespace.
...if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>.
AudioBuffer.getChannelData() - Web APIs
the getchanneldata() method of the audiobuffer interface returns a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel).
... return value a float32array.
AudioContext.close() - Web APIs
the returned promise resolves when all audiocontext-creation-blocking resources have been released.
...}); await audioctx.close(); returns a promise that resolves with void.
AudioContext.getOutputTimestamp() - Web APIs
the getoutputtimestamp() property of the audiocontext interface returns a new audiotimestamp object containing two audio timestamp values relating to the current audio context.
... returns an audiotimestamp object, which has the following properties.
AudioParam.cancelScheduledValues() - Web APIs
returns a reference to this audioparam object.
... in some older implementations this method returns void.
AudioParam.exponentialRampToValueAtTime() - Web APIs
returns a reference to this audioparam object.
... in some browsers older implementations of this interface return void.
AudioParam.linearRampToValueAtTime() - Web APIs
returns a reference to this audioparam object.
... in some browsers older implementations of this interface return void.
AudioParam.setTargetAtTime() - Web APIs
returns a reference to this audioparam object.
... some older browser implementations of this interface return void.
AudioParam.setValueAtTime() - Web APIs
returns a reference to this audioparam object.
... in some browsers older implementations of this interface return void.
AudioParam.setValueCurveAtTime() - Web APIs
return value a reference to this audioparam object.
... some older browser implementations of this interface return undefined.
AudioProcessingEvent - Web APIs
note the the returned audiobuffer is only valid in the scope of the onaudioprocess function.
...note the the returned 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 return 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 returned by audiocontext.currenttime.
AudioTrackList - Web APIs
gettrackbyid() returns the audiotrack found within the audiotracklist whose id matches the specified string.
... if no match is found, null is returned.
AudioWorkletNode.port - Web APIs
the read-only port property of the audioworkletnode interface returns 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) { return 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
return 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) { return 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 returns 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) { return 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 returns an array containing strings describing the different transports which may be used by the authenticator.
... return 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 returned 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 returns an array of strings describing which transport methods (e.g.
BaseAudioContext.createBufferSource() - Web APIs
audiobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track.
... syntax var source = baseaudiocontext.createbuffersource(); returns an audiobuffersourcenode.
BaseAudioContext.createWaveShaper() - Web APIs
syntax baseaudioctx.createwaveshaper(); returns 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) ); } return curve; }; ...
BaseAudioContext.decodeAudioData() - Web APIs
return 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 returns an array buffer as its response that we then store in the audiodata variable .
BatteryManager.chargingTime - Web APIs
even if the time returned 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 return, 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 returned 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 return, 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 return, 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 returned 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 returns "true" and returns "false" otherwise.
...if the browser successfully queues the request for delivery, the method returns "true" and otherwise returns "false".
Blob() - Web APIs
WebAPIBlobBlob
the blob() constructor returns a new blob object.
... return value a new blob object containing the specified data.
Bluetooth.getDevices() - Web APIs
note: this method returns a bluetoothdevice for each device the origin is currently allowed to access, even the ones that are out of range or powered off.
... return value a promise that resolves with an array of bluetoothdevices.
adData - Web APIs
the bluetoothdevice.addata read-only property returns instance of bluetoothadvertisingdata containing the most recent advertising data received for the device.
... syntax var instanceofbluetoothaddata = instanceofbluetoothdevice.addata returns an instance of bluetoothadvertisingdata.
connectGATT() - Web APIs
the bluetoothdevice.connectgatt() method returns a promise that resolves to an instance of bluetoothgattremoteserver.
...}) returns a promise that resolves to an instance of bluetoothgattremoteserver.
deviceClass - Web APIs
the bluetoothdevice.deviceclass read-only property returns a number representing the bluetooth devices "class of device".
... syntax var deviceclass = instanceofbluetoothdevice.deviceclass returns a number.
BluetoothDevice.gatt - Web APIs
the bluetoothdevice.gatt read-only property returns a reference to the device's bluetoothremotegattserver.
... syntax var gattserver = instanceofbluetoothdevice.gatt returns a reference to the device's bluetoothremotegattserver.
gattServer - Web APIs
the bluetoothdevice.gattserver read-only property returns a reference to the device's gatt server or null if the device is disconnected.
... syntax var gattserver = instanceofbluetoothdevice.gattserver returns a reference to the device's gatt server or null if the device is disconnected.
id - Web APIs
the bluetoothdevice.id read-only property returns a domstring that uniquely identifies a device.
... syntax var id = instanceofbluetoothdevice.id returns a domstring.
BluetoothDevice.name - Web APIs
the bluetoothdevice.name read-only property returns a domstring that provides a human-readable name for the device.
... syntax var name = instanceofbluetoothdevice.name returns a domstring.
BluetoothDevice.paired - Web APIs
the bluetoothdevice.paired read-only property returns a boolean value indicating whether the device is paired with the system.
... syntax var paired = instanceofbluetoothdevice.paired returns a boolean.
productID - Web APIs
the bluetoothdevice.productid read-only property returns the 16-bit product id field in the pnp_id characteristic in the device_information service.
... syntax var productid = instanceofbluetoothdevice.productid returns the 16-bit product id field.
productVersion - Web APIs
the bluetoothdevice.productversion read-only property returns the 16-bit product version field in the pnp_id characteristic in the device_information service.
... syntax var productversion = instanceofbluetoothdevice.productversion returns the 16-bit product version field.
vendorID - Web APIs
the bluetoothdevice.vendorid read-only property returns the 16-bit vendor id field in the pnp_id characteristic in the device_information service.
... syntax var vendorid = instanceofbluetoothdevice.vendorid returns the the 16-bit vendor id field.
vendorIDSource - Web APIs
the bluetoothdevice.vendoridsource read-only property returns the vendor id source field in the pnp_id characteristic in the device_information service.
... syntax var vendoridsource = instanceofbluetoothdevice.vendoridsource returns the vendor id source field.
BluetoothRemoteGATTCharacteristic.getDescriptor() - Web APIs
the bluetoothremotegattcharacteristic.getdescriptor() method returns a promise that resolves to the first bluetoothgattdescriptor for a given descriptor uuid.
...}) returns a promise that resolves to the first bluetoothgattdescriptor.
BluetoothRemoteGATTCharacteristic.getDescriptors() - Web APIs
the bluetoothremotegattcharacteristic.getdescriptors() method returns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid.
...}) returns a promise that resolves to an array of bluetoothgattdescriptor objects.
BluetoothRemoteGATTCharacteristic.properties - Web APIs
the bluetoothremotegattcharacteristic.properties read-only property returns a bluetoothcharacteristicproperties instance containing the properties of this characteristic.
... syntax var properties = bluetoothremotegattcharacteristic.properties returns the properties of this characteristic.
BluetoothRemoteGATTCharacteristic.readValue() - Web APIs
the bluetoothremotegattcharacteristic.readvalue() method returns a promise that resolves to a dataview holding a duplicate of the value property if it is available and supported.
...}) returns a promise that resolves to an dataview.
BluetoothRemoteGATTCharacteristic.service - Web APIs
the bluetoothremotegattcharacteristic.service read-only property returns the bluetoothgattservice this characteristic belongs to.
... syntax var bluetoothremotegattserviceinstance = bluetoothremotegattcharacteristic.service returns an instance bluetoothgattservice.
BluetoothRemoteGATTCharacteristic.startNotifications() - Web APIs
the bluetoothremotegattcharacteristic.startnotifications() method returns a promise to the bluetoothremotegattcharacteristic instance when there is an active notification on it.
...}) returns a promise to the bluetoothremotegattcharacteristic instance.
BluetoothRemoteGATTCharacteristic.stopNotifications() - Web APIs
the bluetoothremotegattcharacteristic.stopnotifications() method returns a promise to the bluetoothremotegattcharacteristic instance when there is no longer an active notification on it.
...}) returns a promise.
BluetoothRemoteGATTCharacteristic.uuid - Web APIs
the bluetoothremotegattcharacteristic.uuid read-only property returns 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 returns a domstring.
BluetoothRemoteGATTCharacteristic.value - Web APIs
the bluetoothremotegattcharacteristic.value read-only property returns currently cached characteristic value.
... syntax var value = bluetoothremotegattcharacteristic.value returns the currently cached characteristic value.
BluetoothRemoteGATTCharacteristic.writeValue() - Web APIs
the bluetoothremotegattcharacteristic.writevalue() method sets the value property to the bytes contained in an arraybuffer and returns a promise.
...}) returns a promise.
characteristic - Web APIs
the bluetoothremotegattdescriptor.characteristic read-only property returns the bluetoothremotegattcharacteristic this descriptor belongs to.
... syntax var characteristic = bluetoothremotegattcharacteristic.characteristic returns an instance of bluetoothremotegattcharacteristic.
readValue() - Web APIs
the bluetoothremotegattdescriptor.readvalue() method returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported.
...}) returns a promise that resolves to an arraybuffer.
uuid - Web APIs
the bluetoothremotegattdescriptor.uuid read-only property returns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor.
... syntax var uuid = bluetoothremotegattdescriptor.uuid returns a uuid.
value - Web APIs
the bluetoothremotegattdescriptor.value read-only property returns an arraybuffer containing the currently cached descriptor value.
... syntax var characteristic = bluetoothremotegattdescriptor.characteristic returns an arraybuffer.
writeValue() - Web APIs
the bluetoothremotegattdescriptor.writevalue() method sets the value property to the bytes contained in an arraybuffer and returns a promise.
... returns a promise.
BluetoothRemoteGATTServer.getPrimaryService() - Web APIs
the bluetoothremotegattserver.getprimaryservice() method returns a promise to the primary bluetoothgattservice offered by the bluetooth device for a specified bluetoothserviceuuid.
...}) returns a promise that resolves to a bluetoothgattservice object.
BluetoothRemoteGATTServer.getPrimaryServices() - Web APIs
the bluetoothremotegattserver.getprimaryservices() method returns a promise to a list of primary bluetoothgattservice objects offered by the bluetooth device for a specified bluetoothserviceuuid.
...}) returns a promise that resolves to a list of bluetoothgattservice objects.
device - Web APIs
the bluetoothgattservice.device read-only property returns information about a bluetooth device through an instance of bluetoothdevice.
... syntax var bluetoothdeviceinstance = bluetoothgattservice.device returns an instance of bluetoothdevice.
getCharacteristic() - Web APIs
the bluetoothgattservice.getcharacteristic() method returns a promise to an instance of bluetoothgattcharacteristic for a given universally unique identifier (uuid).
...} ) returns 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 returns a promise to a list of bluetoothgattcharacteristic instances for a given universally unique identifier (uuid).
...} ) returns a promise to an array of bluetoothgattcharacteristic instances.
getIncludedService() - Web APIs
the bluetoothgattservice.getincludedservice() method returns a promise to an instance of bluetoothgattservice for a given universally unique identifier (uuid).
...} ) returns a promise to an instance of bluetoothgattservice.
getIncludedServices() - Web APIs
the bluetoothgattservice.getincludedservices() method returns a promise to an array of bluetoothgattservice instances for an optional universally unique identifier (uuid).
...} ) returns a promise to an instance of bluetoothgattservice.
isPrimary - Web APIs
the bluetoothgattservice.isprimary read-only property returns a boolean that indicates whether this is a primary service.
... syntax var isprimary = bluetoothgattservice.isprimary returns a boolean.
uuid - Web APIs
the bluetoothgattservice.uuid read-only property returns a domstring representing the uuid of this service.
... syntax var uuid = bluetoothgattservice.uuid returns a domstring.
Body.blob() - Web APIs
WebAPIBodyblob
it returns a promise that resolves with a blob.
... return value a promise that resolves with a blob.
Body.body - Web APIs
WebAPIBodybody
const image = document.getelementbyid('target'); // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue(v...
...alue); return 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
WebAPIBodybodyUsed
this returns false before and true afterwards, as at that point the body has been read.
... html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { console.log(response.bodyused); var res = response.blob(); console.log(response.bodyused); return res; }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'bodyused' in that specification.
Body.formData() - Web APIs
WebAPIBodyformData
it returns a promise that resolves with a formdata object.
... return value a promise that resolves with a formdata object.
Body.json() - Web APIs
WebAPIBodyjson
it returns a promise that resolves with the result of parsing the body text as json.
... return value a promise that resolves to a javascript object.
BudgetService.getBudget() - Web APIs
the getbudget() property of the budgetservice interface returns a promise that resolves to an array of budgetstate objects indicating the expected state of the budget at times in the future.
... returns a promise that resolves to an instance of budgetstate.
BudgetService.getCost() - Web APIs
the getcost() property of the budgetservice interface returns a promise that resolves to a double indicating the worst-case background operation cost of the provided background operation.
... returns a promise that resolves to a number.
BudgetService.reserve() - Web APIs
the reserve() property of the budgetservice interface returns a promise that resolves to a boolean indicating whether the requested budget operation can be reserved.
...}); parameters operation desc returns a promise that resolves to a boolean.
BudgetState - Web APIs
properties budgetstate.budgetat returns the anticipated processing budget at a specific time.
... budgetstate.time returns a timestamp at which the budgetat value is valid.
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
the bytelengthqueuingstrategy() constructor creates and returns a bytelengthqueuingstrategy object instance.
... return value an instance of the bytelengthqueuingstrategy object.
ByteLengthQueuingStrategy.size() - Web APIs
the size() method of the bytelengthqueuingstrategy interface returns the given chunk’s bytelength property.
... return 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 return 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
WebAPICSSsupports
the css.supports() method returns a boolean value indicating if the browser supports a given css feature, or not.
... return value true if the browser supports the rule, otherwise false.
CSS - Web APIs
WebAPICSS
css.supports() returns a boolean indicating if the pair property-value, or the condition, given in parameter is supported.
... css factory functions can be used to return 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 return the value of csskeyword.value.
... properties csskeywordvalue.value returns or sets the value of the csskeywordvalue.
CSSMathSum - Web APIs
a cssmathsum is the object type returned when the stylepropertymapreadonly.get() method is used on a css property whosevalue is created with a calc() function.
... properties cssmathsum.values returns 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 return 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 returns sum for the equation and negate for the operator on the second value.
CSSNamespaceRule.namespaceURI - Web APIs
the cssnamespacerule.namespaceuri read-only property returns a domstring containing the text of the uri of the given namespace.
... syntax var namespaceuri = cssnamespacerule.namespaceuri returns a domstring containing a uri.
CSSNumericValue.max() - Web APIs
the max() method of the cssnumericvalue interface returns the highest value from among the values passed.
... return value a cssunitvalue.
CSSNumericValue.min() - Web APIs
the min() method of the cssnumericvalue interface returns the lowest value from among those values passed.
... return value a cssunitvalue.
CSSNumericValue.parse() - Web APIs
return value a cssnumericvalue.
... exceptions syntaxerror tbd examples the following returns 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 returned.
... return value a float value in the specified unit.
CSSPrimitiveValue.getRGBColorValue() - Web APIs
syntax var rgbcolorvalue = cssprimitivevalue.getrgbcolorvalue(); return value an rgbcolor object representing the color value.
... exceptions type description domexception an invalid_access_err is raised if the attached property can't return 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 returned.
... return value void.
CSSPseudoElement - Web APIs
properties csspseudoelement.element read only returns the originating/parent element of the pseudo-element.
... csspseudoelement.type read only returns the pseudo-element selector as a cssomstring.
CSSRule - Web APIs
WebAPICSSRule
cssrule.parentrule read only returns the containing rule, otherwise null.
... cssrule.parentstylesheet read only returns 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 "" return 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; return num; } function randomcolor() { return '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 returns an array of cssstylevalue objects, each containing one of the supplied values.
... return 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 returns the first value as a cssstylevalue object.
... cssstylevalue.parseall() sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of the supplied values.
CSSUnitValue - Web APIs
properties cssunitvalue.value returns a double indicating the number of units.
... cssunitvalue.unit returns a usvstring indicating the type of unit.
CSSUnparsedValue.keys() - Web APIs
the cssunparsedvalue.keys() method returns a new array iterator object that contains the keys for each index in the array.
... return value a new array.
CSSUnparsedValue.values() - Web APIs
the cssunparsedvalue.values() method returns a new array iterator object that contains the values for each index in the cssunparsedvalue object.
... return value a new array.
CSSValueList.item() - Web APIs
WebAPICSSValueListitem
if the index is greater than or equal to the number of values in the list, this method returns null.
... return 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 returns the custom name passed to the constructor.
... cssvariablereferencevalue.fallback read only returns the built-in css value for the custom name.
Using dynamic styling information - Web APIs
however, this property only returns style attributes that have been set in-line (e.g, <td style="background-color: lightblue"> returns 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 returns all styles that have actually been computed for an element.
CSS Painting API - Web APIs
paintsize returns 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() { return ['--boxcolor']; } static get inputarguments() { return ['*','<length>']; } static get contextoptions() { return {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
WebAPICachedelete
the delete() method of the cache interface finds the cache entry whose key is the request, and if found, deletes the cache entry and returns a promise that resolves to true.
... return value a promise that resolves to true if the cache entry is deleted, or false otherwise.
Cache.matchAll() - Web APIs
WebAPICachematchAll
the matchall() method of the cache interface returns a promise that resolves to an array of all matching responses in the cache object.
... return value a promise that resolves to an array of all matching responses in the cache object.
CanvasRenderingContext2D.createLinearGradient() - Web APIs
this method returns a linear canvasgradient.
... return value canvasgradient a linear canvasgradient initialized with the specified line.
CanvasRenderingContext2D.createPattern() - Web APIs
this method returns a canvaspattern.
... return value canvaspattern an opaque object describing a pattern.
CanvasRenderingContext2D.createRadialGradient() - Web APIs
this method returns a canvasgradient.
... return value canvasgradient a radial canvasgradient initialized with the two specified circles.
CanvasRenderingContext2D.getTransform() - Web APIs
return 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 returned 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 returned dommatrix.
CanvasRenderingContext2D.measureText() - Web APIs
the canvasrenderingcontext2d.measuretext() method returns a textmetrics object that contains information about the measured text (such as its width, for example).
... return value a textmetrics object.
Manipulating video using canvas - Web APIs
processor.timercallback = function timercallback() { if (this.video.paused || this.video.ended) { return; } 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 returns 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); return; } 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 returns a node containing the found node at the caret's position.
... caretposition.offset read only returns a long representing the character offset in the caret position node.
Client.url - Web APIs
WebAPIClienturl
the url read-only property of the client interface returns 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) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment service workersthe definition of 'url' in that specification.
CompositionEvent - Web APIs
compositionevent.data read only returns 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 returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime).
console.count() - Web APIs
WebAPIConsolecount
examples for example, given code like this: let user = ""; function greet() { console.count(); return "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); return "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(); return "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); return "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 returns a audioparam object indicating the numeric a-rate value which is always returned 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 returned for every sample by this node.
ContentIndex.add() - Web APIs
WebAPIContentIndexadd
return value returns a promise that resolves with undefined exceptions typeerror if the service worker's registration is not present or the service worker does not contain a fetchevent.
...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) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope.
ContentIndex.delete() - Web APIs
return value returns 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) return; // 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
return value a contentindexevent object configured using the given inputs.
... var removedata = { id : 'unique-content-id' } var cievent = new contentindexevent('contentdelete', removedata); cievent.id; // should return 'unique-content-id' specifications specification status comment unknownthe definition of 'contentindexevent' in that specification.
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
the countqueuingstrategy() constructor creates and returns a countqueuingstrategy object instance.
... return value an instance of the countqueuingstrategy object.
CountQueuingStrategy.size() - Web APIs
the size() method of the countqueuingstrategy interface always returns 1, so that the total queue size is a count of the number of chunks in the queue.
... return value 1.
Credential - Web APIs
properties credential.id read only returns a domstring containing the credential's identifier.
... credential.type read only returns a domstring containing the credential's type.
CredentialsContainer.create() - Web APIs
the create() method of the credentialscontainer interface returns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created.
... returns 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 returns an empty promise.
... returns 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, returning this in a promise.
... returns a promise, resolving to the passed credential instance.
CustomElementRegistry.define() - Web APIs
return 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 return 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 returns a promise that resolves when the named element is defined.
... return value a promise that resolves to undefined when the custom element is defined.
DOMError - Web APIs
WebAPIDOMError
properties domerror.name read only returns a domstring representing one of the error type names (see below).
... domerror.message read only returns a domstring representing a message or description associated with the given error type name.
DOMImplementation.createDocument() - Web APIs
the domimplementation.createdocument() method creates and returns an xmldocument.
... living standard modified the return type of createdocument() from document to xmldocument.
DOMPoint.fromPoint() - Web APIs
the static dompoint method frompoint() creates and returns a new mutable dompoint object given a source point.
... return value a new dompoint object whose coordinate and perspective values are identical to those in the source point.
DOMPointReadOnly() - Web APIs
the dompointreadonly() constructor returns a new dompointreadonly object representing a point in 2d or 3d space, optionally with perspective, whose values cannot be altered by script code.
... return value a new dompointreadonly object representing the specified location in space.
DOMPointReadOnly.fromPoint() - Web APIs
the static dompointreadonly method frompoint() creates and returns a new dompointreadonly object given a source point.
... return value a new dompointreadonly object (which is identical to the source point).
DOMPointReadOnly.toJSON() - Web APIs
the dompointreadonly method tojson() returns a dompointinit object giving the json form of the point object.
... return 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 returns a boolean — true if the underlying list contains the given token, otherwise false.
... return value a boolean, which is true if the calling list contains token, otherwise false.
DOMTokenList.entries() - Web APIs
the domtokenlist.entries() method returns an iterator allowing you to go through all key/value pairs contained in this object.
... syntax tokenlist.entries(); return value returns an iterator.
DOMTokenList.keys() - Web APIs
WebAPIDOMTokenListkeys
the keys() method of the domtokenlist interface returns an iterator allowing to go through all keys contained in this object.
... return value returns an iterator.
DOMTokenList.supports() - Web APIs
the supports() method of the domtokenlist interface returns true if a given token is in the associated attribute's supported tokens.
... returns a boolean indicating whether the token was found.
DOMTokenList.values() - Web APIs
the values() method of the domtokenlist interface returns an iterator allowing developers to go through all values contained in the domtokenlist.
... return value returns an iterator.
DOMUserData - Web APIs
it is returned or used as an argument by node.setuserdata(), node.getuserdata(), used as the third argument to handle() on userdatahandler, and is used or returned by various domconfiguration methods.
... note that although it can be an object, in mozilla, it may be returned 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 returns or sets the drag cursor's state.
... syntax datatransfer.mozcursor; return value a domstring representing one of the values listed above.
DataTransfer.mozItemCount - Web APIs
the datatransfer.mozitemcount property returns the number of items being dragged.
... syntax datatransfer.mozitemcount; return value a number representing the number of items being dragged.
DataTransfer.mozUserCancelled - Web APIs
if the user canceled the event, the property returns true and returns false otherwise.
... syntax datatransfer.mozusercancelled; return value a boolean representing true if the user canceled the drag event and returns false otherwise.
DataTransfer.types - Web APIs
the datatransfer.types read-only property returns an array of the drag data formats (as strings) that were set in the dragstart event.
... syntax datatransfer.types; return value an array of the data formats used in the drag operation.
DataTransfer - Web APIs
constructor datatransfer() creates and returns 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 returned.
DataTransferItem.getAsString() - Web APIs
return value undefined callback the callback parameter is a callback function which accepts one parameter: domstring the drag data item's string data.
... the callback return value is undefined.
DataTransferItem.kind - Web APIs
the read-only datatransferitem.kind property returns a datatransferitem representing the drag data item kind: some text or some file.
... syntax var itemkind = datatransferitem.kind; return value a domstring representing the drag data item's kind.
DataTransferItem.type - Web APIs
the read-only datatransferitem.type property returns the type (format) of the datatransferitem object representing the drag data item.
... syntax dataitem.type; return value a domstring representing the drag data item's type.
DataTransferItem - Web APIs
methods datatransferitem.getasfile() returns the file object associated with the drag data item (or null if the drag item is not a file).
... datatransferitem.webkitgetasentry() returns 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 returns a datatransferitem object for the new item.
... datatransferitemlist.datatransferitem() getter that returns a datatransferitem at the given index.
DedicatedWorkerGlobalScope.name - Web APIs
the name read-only property of the dedicatedworkerglobalscope interface returns 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", returnable 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 return value of its report.body property).
...if the date is not known, this property will return null.
DeviceMotionEvent.rotationRate - Web APIs
returns 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 returns 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 returned 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 returned by getdisplaymedia().
Document.all - Web APIs
WebAPIDocumentall
the document interface's read-only all property returns an htmlallcollection rooted at the document node.
... in other words, it returns all of the document's elements, accessible by order (like an array) and by id (like a regular object).
Document.anchors - Web APIs
WebAPIDocumentanchors
the anchors read-only property of the document interface returns 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 returned set of anchors only contains those anchors created with the name attribute, not those created with the id attribute.
Document.applets - Web APIs
WebAPIDocumentapplets
the applets property of the document interface returns a list of the applets within a document.
...since then, calling document.applets in those browsers always returns an empty htmlcollection.
Document.caretRangeFromPoint() - Web APIs
the caretrangefrompoint() method of the document interface returns a range object for the document fragment under the specified coordinates.
... returns one of the following: a range.
Document.characterSet - Web APIs
the document.characterset read-only property returns the character encoding of the document that it's currently rendered with.
...despite the name of this property, it returns the encoding.
Document.createAttribute() - Web APIs
the document.createattribute() method creates a new attribute node, and returns it.
... return value a attr node.
Document.createProcessingInstruction() - Web APIs
createprocessinginstruction() generates a new processing instruction node and returns 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 returned processinginstruction object more precisely.
Document.createTouch() - Web APIs
the document.createtouch() method creates and returns a new touch object.
... return value touch a touch object configured as described by the input parameters.
Document.createTouchList() - Web APIs
the document.createtouchlist() method creates and returns a new touchlist object.
... return value list a touchlist object containing the touch objects specified by the touches parameter.
Document.fonts - Web APIs
WebAPIDocumentfonts
the fonts property of the document interface returns the fontfaceset interface of the document.
... syntax let fontfaceset = document.fonts; value the returned value is the fontfaceset interface of the document.
Document.forms - Web APIs
WebAPIDocumentforms
the forms read-only property of the document interface returns an htmlcollection listing all the <form> elements contained in the document.
... if the document has no forms, the returned collection is empty, with a length of zero.
Document.getAnimations() - Web APIs
the getanimations() method of the document interface returns an array of all animation objects currently in effect whose target elements are descendants of the document.
... return 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
WebAPIDocumenthasFocus
the hasfocus() method of the document interface returns a boolean value indicating whether the document or any element inside the document has focus.
... syntax var focused = document.hasfocus(); return 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 returns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage.
... return value a promise that resolves with a boolean value indicating whether the document has access to its first-party storage.
Document.images - Web APIs
WebAPIDocumentimages
the images read-only property of the document interface returns 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 returned collection to access the items in the collection.
Document.location - Web APIs
WebAPIDocumentlocation
the document.location read-only property returns 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 returned value is null.
Document.origin - Web APIs
WebAPIDocumentorigin
the document.origin read-only property returns the document's origin.
... syntax var origin = document.origin; examples var origin = document.origin; // on this page, returns:'https://developer.mozilla.org' var origin = document.origin; // on "about:blank", returns:'null' var origin = document.origin; // on "data:text/html,<b>foo</b>", returns:'null' ...
Document.queryCommandSupported() - Web APIs
return value returns a boolean which is true if the command is supported and false if the command isn't.
... notes the 'paste' command return 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
WebAPIDocumentreferrer
the document.referrer property returns the uri of the page that linked to this page.
...because this property returns only a string, it doesn't give you document object model (dom) access to the referring page.
Document.rootElement - Web APIs
document.rootelement returns 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 returns the root element for all documents.
Document.scripts - Web APIs
WebAPIDocumentscripts
the scripts property of the document interface returns a list of the <script> elements in the document.
... the returned object is an htmlcollection.
Document.scrollingElement - Web APIs
the scrollingelement read-only property of the document interface returns a reference to the element that scrolls the document.
... when in quirks mode, the scrollingelement attribute returns the html body element if it exists and is not potentially scrollable, otherwise it returns null.
Document.styleSheetSets - Web APIs
the stylesheetsets read-only property returns a live list of all of the currently-available style sheet sets.
... syntax var sets = document.stylesheetsets; on return, sets is a list of style sheet sets that are available.
Document.title - Web APIs
WebAPIDocumenttitle
the assignment affects the return 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 return an empty string and setting document.title may have no effect.
Document.xmlVersion - Web APIs
returns 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 returned 1.0, and has been removed in dom level 4.
DocumentFragment.querySelectorAll() - Web APIs
the documentfragment.queryselectorall() method returns 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 returns 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 returns the element within the dom or shadow dom tree that currently has focus.
... often activeelement will return 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 returns a caretposition object, containing the dom node, along with the caret and caret's character offset within that node.
... returns a caretposition object.
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
the elementsfrompoint() method of the documentorshadowroot interface returns an array of all elements at the specified coordinates (relative to the viewport).
... return value an array of element objects.
DocumentOrShadowRoot.msElementsFromRect() - Web APIs
the mselementsfromrect method returns 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 returned nodelist is sorted by z-index so that you can tell the relative stacking order of the elements.
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
the nodefrompoint() property of the documentorshadowroot interface returns the topmost node at the specified coordinates (relative to the viewport).
... returns a node object.
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
the nodesfrompoint() property of the documentorshadowroot interface returns an array of all nodes at the specified coordinates (relative to the viewport).
... returns an array of node objects.
DocumentOrShadowRoot.styleSheets - Web APIs
the stylesheets read-only property of the documentorshadowroot interface returns 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) { return sheet; } } } notes the returned list is ordered as follows: stylesheets retrieved from <link> headers are placed first, sorted in header order.
Events and the DOM - Web APIs
the return value is treated in a special way, described in the html specification.
...the return 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 returns a list of the stylesheets that have been loaded on that document.
... getcomputedstyle() returns 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 returns true if the passed object is a webglquery object.
... return value a glboolean indicating whether the given object is a webglquery object (true) or not (false).
EXT_texture_compression_bptc - Web APIs
it only contains rgb data, so the returned alpha value is 1.0.
...it only contains rgb data, so the returned alpha value is 1.0.
EffectTiming.delay - Web APIs
the value of delay corresponds directly to effecttiming.delay in timing objects returned 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) { return 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 returned 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) { return 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.animate() - Web APIs
WebAPIElementanimate
it returns the created animation object instance.
... return value returns an animation.
Element.getElementsByTagNameNS() - Web APIs
the element.getelementsbytagnamens() method returns a live htmlcollection of elements with the given tag name belonging to the given namespace.
... living standard changed the return value from nodelist to htmlcollection.
Element.matches() - Web APIs
WebAPIElementmatches
return 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) {} return 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 returns the namespace uri of the element, or null if the element is not in a namespace.
...if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>.
Element.outerHTML - Web APIs
WebAPIElementouterHTML
syntax var content = element.outerhtml; element.outerhtml = htmlstring; value reading the value of outerhtml returns 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 returned 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&amp;c=d'></a>" specification specification status comment dom parsing and serializationthe definition of 'element.outerhtml' in that specification.
Element.removeAttribute() - Web APIs
if the specified attribute does not exist, removeattribute() returns without generating an error.
... return value undefined.
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 returns 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) { return; } 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, returned 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)); // returns: '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 returned.
Element.setAttributeNodeNS() - Web APIs
syntax replacedattr = element.setattributenodens(attributenode) replacedattr is the replaced attribute node, if any, returned 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) // returns: `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 returned.
Element.toggleAttribute() - Web APIs
return 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) return true; this.removeattribute(name); return false; } if (force === false) return false; this.setattribute(name, ""); return true; }; } specification specification status comment domthe definition of 'element.toggleattribute' in that specification.
ElementCSSInlineStyle.style - Web APIs
when getting, it returns 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 returns a cssstyledeclaration object which is also read-only.
Event.msConvertURL() - Web APIs
return value this method does not return a value.
... if (!filelist) { console.log("filelist is null."); return; } for (var i = 0; i < filelist.length; i++) { var file = filelist[i]; var url = url.createobjecturl(file); if (evt.converturl) { // use standard if available.
EventListener.handleEvent() - Web APIs
return value undefined.
... if you return a value, the browser will ignore it.
EventTarget() - Web APIs
return value an instance of the eventtarget object.
... examples class myeventtarget extends eventtarget { constructor(mysecret) { super(); this._secret = mysecret; } get secret() { return 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
return 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)) { return; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback){ stack.splice(i, 1); return; } } }; eventtarget.prototype.dispatchevent = function(event) { if (!(event.type in this.listeners)) { return true; } var stack = this.listeners[event.type].slice(); for (var i = 0, l = stack.length; i < l; i++) { ...
... stack[i].call(this, event); } return !event.defaultprevented; }; specifications specification status comment domthe definition of 'eventtarget' in that specification.
ExtendableEvent.waitUntil() - Web APIs
return value undefined.
... example using waituntil() within a service worker's install event: addeventlistener('install', event => { const precache = async () => { const cache = await caches.open('static-v1'); return cache.addall([ '/', '/about/', '/static/styles.css' ]); }; event.waituntil(precache()); }); specifications specification status comment service workersthe definition of 'waituntil()' in that specification.
FeaturePolicy.allowsFeature() - Web APIs
it returns 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).
... return 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 returns a list of names of all features supported by the user agent.
... return value a list of strings that represent names of all feature policy directives supported by the user agent.
FeaturePolicy.getAllowlistForFeature() - Web APIs
return value an allow list for the specified feature.
...however, it will also return empty array, inditating that no origin is allowed to use the feature.
FederatedCredential - Web APIs
federatedcredential.provider read only returns a usvstring containing a credential's federated identity provider.
... federatedcredential.protocol read only returns a domstring containing a credential's federated identity protocol.
FetchEvent.isReload - Web APIs
the isreload read-only property of the fetchevent interface returns true if the event was dispatched by the user attempting to reload the page, and false otherwise.
... example self.addeventlistener('fetch', function(event) { event.respondwith( if (event.isreload) { //return something } else { //return something else }; ); ​}); ...
Fetch API - Web APIs
WebAPIFetch API
it returns 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 returned 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) { return 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
WebAPIFilegetAsText
syntax var str = instanceoffile.getastext(encoding); parameters encoding a string indicating the encoding to use for the returned data.
... returns a string containing the file's data interpreted as text in the specified encoding.
File.lastModified - Web APIs
WebAPIFilelastModified
files without a known last modified date return the current date.
... const filewithdate = new file([], 'file.bin', { lastmodified: new date(2017, 1, 1), }); console.log(filewithdate.lastmodified); //returns 1485903600000 const filewithoutdate = new file([], 'file.bin'); console.log(filewithoutdate.lastmodified); //returns 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 returns the last modified date of the file.
... files without a known last modified date returns the current date .
File.type - Web APIs
WebAPIFiletype
returns the media type (mime) of the file represented by a file object.
...uncommon file extensions would return an empty string.
FileReader.error - Web APIs
WebAPIFileReadererror
the filereader error property returns the error that occurred while reading the file.
...in chrome 48+/firefox 58+ this property returns a domexception because domerror has been removed from the dom standard.
FileSystemEntry.getParent() - Web APIs
return value undefined.
...you can, however, create a simple helper function to adapt it, like this: function getparentpromise(entry) { return 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() returns a filesystemdirectoryentry representing the entry's parent directory.
... tourl() creates and returns a url which identifies the entry.
FileSystemFileEntry.createWriter() - Web APIs
the filesystemfileentry interface's method createwriter() returns a filewriter object which can be used to write data into the file represented by the directory entry.
... return value undefined.
FileSystemFileEntry.file() - Web APIs
the filesystemfileentry interface's method file() returns a file object which can be used to read data from the file represented by the directory entry.
... return 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 return a filerequest object.
FontFace.load - Web APIs
WebAPIFontFaceload
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 returns a promise that resolves with the current fontface object.
... return 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
WebAPIFontFaceSetload
syntax result = afontfaceset.load(font); result = afontfaceset.load(font, text); returns a promise of an array of fontface loaded.
... examples // returns 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
WebAPIFontFaceSetready
the ready readonly property of the fontfaceset interface returns a promise that resolves to the given fontfaceset.
...}); returns a promise that resolves to the given fontfaceset.
FormData.entries() - Web APIs
WebAPIFormDataentries
the formdata.entries() method returns an iterator allowing to go through all key/value pairs contained in this object.
... syntax formdata.entries(); return value returns an iterator.
FormData.keys() - Web APIs
WebAPIFormDatakeys
the formdata.keys() method returns an iterator allowing to go through all keys contained in this object.
... syntax formdata.keys(); return value returns an iterator.
FormData.values() - Web APIs
WebAPIFormDatavalues
the formdata.values() method returns an iterator allowing to go through all values contained in this object.
... syntax formdata.values(); return value returns an iterator.
FormDataEntryValue - Web APIs
this type is returned by the formdata.get() and formdata.getall() methods.
... the formdata.get() method returns a single value while formdata.getall() returns an array of formdataentryvalues.
Frame Timing API - Web APIs
this method returns a list of "frame" performanceentry objects.
... each frame object's duration property returns the timestamp of two consecutive frames.
Gamepad.hand - Web APIs
WebAPIGamepadhand
the hand read-only property of the gamepad interface returns an enum defining what hand the controller is being held in, or is most likely to be held in.
... empty string ("") — this value is returned if the other values are not applicable, e.g.
Gamepad.id - Web APIs
WebAPIGamepadid
the gamepad.id property of the gamepad interface returns a string containing some information about the controller.
... for example, a ps2 controller returned 810-3-usb gamepad.
GamepadButton - Web APIs
a gamepadbutton object is returned by querying any value of the array returned 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 return an array of double values when this property is accessed.
GamepadEvent - Web APIs
constructor gamepadevent() returns a new gamepadevent object.
... properties gamepadevent.gamepad read only returns 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 returned by geolocation api functions that obtain and return a geographical position.
... examples in this simple example, we fetch the user's location and display the resulting coordinates once they're returned.
GeolocationPosition.coords - Web APIs
the geolocationposition.coords read-only property returns 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 returned value.
GeolocationPosition - Web APIs
geolocationposition.coords read only secure context returns a geolocationcoordinates object defining the current location.
... geolocationposition.timestamp read only secure context returns 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 returns 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); } return 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 returns a nodelist of the <label> elements associated with the <button> element.
... syntax var labelelements = button.labels; return value a nodelist containing the <label> elements associated with the <button> element.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
return 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() { return function(result) { if (!components.issuccesscode(result)) { alert('failed to create icon'); } else { alert('succesfully made'); } }; } var mfascallback = function(iconname) { return 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() returns a memory-based file object representing the image contained in the canvas.
... return value a file object representing the image contained in the canvas.
HTMLDialogElement.show() - Web APIs
return 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.returnvalue = '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
return 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.returnvalue = '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 returns 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 returned.
HTMLElement.offsetWidth - Web APIs
the htmlelement.offsetwidth read-only property returns 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 returned.
HTMLFieldSetElement - Web APIs
htmlfieldsetelement.checkvalidity() always returns true because <fieldset> objects are never candidates for constraint validation.
... htmlfieldsetelement.reportvalidity() always returns true because <fieldset> objects are never candidates for constraint validation.
HTMLFormControlsCollection - Web APIs
it represents the lists returned by the htmlformelement interface's elements property and the htmlfieldsetelement interface's elements property.
... htmlformcontrolscollection.nameditem() returns 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
returns version information about the document type definition (dtd) of a document.
... while this property is recognized by mozilla, the return value for this property is always an empty string.
HTMLHyperlinkElementUtils.hash - Web APIs
the htmlhyperlinkelementutils.hash property returns 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); // returns '#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 returns 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; // returns: '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 returns 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(); // returns: '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, returns a document (that is, the active document in the inline frame's nested browsing context), else returns 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 returns 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 returns 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 returns 0.
HTMLInputElement.labels - Web APIs
the htmlinputelement.labels read-only property returns a nodelist of the <label> elements associated with the <input> element.
... syntax var labelelements = input.labels; return value a nodelist containing the <label> elements associated with the <input> element.
HTMLInputElement.mozGetFileNameArray() - Web APIs
the htmlinputelement.mozgetfilenamearray() method returns 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 returned array.
HTMLLabelElement.form - Web APIs
the read-only htmllabelelement.form property returns 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 returns null.
HTMLLegendElement - Web APIs
if the legend has a fieldset element as its parent, then this attribute returns the same value as the form attribute on the parent fieldset element.
... otherwise, it returns null.
HTMLMediaElement.audioTracks - Web APIs
the read-only audiotracks property on htmlmediaelement objects returns an audiotracklist object listing all of the audiotrack objects representing the media element's audio tracks.
... the returned 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 returns a mediastream object which is streaming a real-time capture of the content being rendered in the media element.
... return 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
return value undefined.
... the process of aborting any ongoing activities will cause any outstanding promises returned 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 returns a timeranges object that contains the time ranges that the user is able to seek to, if any.
... recommendation specifies a new algorithm for returning 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 returns a promise that resolves to the passed mediakeys, which are those used to decrypt media during playback.
... returns 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 returns a promise.
...}) returns a promise that resolves to undefined.
HTMLMediaElement.videoTracks - Web APIs
the read-only videotracks property on htmlmediaelement objects returns a videotracklist object listing all of the videotrack objects representing the media element's video tracks.
... the returned 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 returns a nodelist of the <label> elements associated with the <meter> element.
... syntax var labelelements = meter.labels; return value a nodelist containing the <label> elements associated with the <meter> element.
HTMLObjectElement.checkValidity - Web APIs
the checkvalidity() method of the htmlobjectelement interface returns a boolean that always is true, because object objects are never candidates for constraint validation.
... return value true exceptions none.
HTMLOrForeignElement.nonce - Web APIs
the nonce property of the htmlorforeignelement interface returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed.
... 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 returned).
HTMLOutputElement.labels - Web APIs
the htmloutputelement.labels read-only property returns a nodelist of the <label> elements associated with the <output> element.
... syntax var labelelements = output.labels; return value a nodelist containing the <label> elements associated with the <output> element.
HTMLOutputElement - Web APIs
htmloutputelement.checkvalidity() checks the validity of the element and returns a boolean holding the check result.
...if there are problems, fires an invalid event at the element, and returns false; if there are no problems, it returns true.
HTMLProgressElement.labels - Web APIs
the htmlprogresselement.labels read-only property returns a nodelist of the <label> elements associated with the <progress> element.
... syntax var labelelements = progress.labels; return value a nodelist containing the <label> elements associated with the <progress> element.
HTMLSelectElement.labels - Web APIs
the htmlselectelement.labels read-only property returns a nodelist of the <label> elements associated with the <select> element.
... syntax var labelelements = select.labels; return value a nodelist containing the <label> elements associated with the <select> element.
HTMLSelectElement.options - Web APIs
the htmlselectelement.options read-only property returns a htmloptionscollection of the <option> elements contained by the <select> element.
... syntax var options = select.options; return 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 returns a reference to the new row.
... return value newrow is an htmltablerowelement that references the new row.
HTMLTableElement.rows - Web APIs
the read-only htmltableelement property rows returns 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 returned 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 returns a reference to the cell.
... return value newcell is an htmltablecellelement that references the new cell.
HTMLTextAreaElement.labels - Web APIs
the htmltextareaelement.labels read-only property returns a nodelist of the <label> elements associated with the <textarea> element.
... syntax var labelelements = textarea.labels; return value a nodelist containing the <label> elements associated with the <textarea> element.
HTMLTrackElement - Web APIs
htmltrackelement.readystate read only returns 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 returns 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
WebAPIHeadersHeaders
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'); // returns '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 return 'image/jpeg' — it inherits it from the first headers object specifications specification status comment fetchthe definition of 'headers()' in that specification.
Headers.delete() - Web APIs
WebAPIHeadersdelete
returns 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'); // returns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // returns null, as it has been deleted specifications specification status comment fetchthe definition of 'delete()' in that specification.
Headers.entries() - Web APIs
WebAPIHeadersentries
the headers.entries() method returns an iterator allowing to go through all key/value pairs contained in this object.
... syntax headers.entries(); return value returns an iterator.
Headers.keys() - Web APIs
WebAPIHeaderskeys
the headers.keys() method returns an iterator allowing to go through all keys contained in this object.
... syntax headers.keys(); return value returns an iterator.
Headers.set() - Web APIs
WebAPIHeadersset
returns 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'); // returns 'gzip' you'd need headers.append to append the new value onto the values, not overwrite it.
Headers.values() - Web APIs
WebAPIHeadersvalues
the headers.values() method returns an iterator allowing to go through all values contained in this object.
... syntax headers.values(); return value returns an iterator.
History.length - Web APIs
WebAPIHistorylength
the history.length read-only property returns 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 returns 1.
IDBCursor.delete() - Web APIs
WebAPIIDBCursordelete
the delete() method of the idbcursor interface returns 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(); returns an idbrequest object on which subsequent events related to this operation are fired.
IDBCursor.source - Web APIs
WebAPIIDBCursorsource
the source read-only property of the idbcursor interface returns the idbobjectstore or idbindex that the cursor is iterating over.
... this function never returns 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
WebAPIIDBCursorupdate
the update() method of the idbcursor interface returns an idbrequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store.
... return value an idbrequest object on which subsequent events related to this operation are fired.
IDBDatabase.createObjectStore() - Web APIs
the createobjectstore() method of the idbdatabase interface creates and returns a new object store or index.
... returns a new idbobjectstore.
IDBDatabase.transaction() - Web APIs
the transaction method of the idbdatabase interface immediately returns 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: return value an idbtransaction object.
databases - Web APIs
the databases method of the idbfactory interface returns a list represening all the available databases, including their names and versions.
... return 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 returns a result indicating which one is greater in value.
... idbfactory.databases a method that returns a list of all available databases, including their names and versions.
IDBIndex.getAll() - Web APIs
WebAPIIDBIndexgetAll
count optional the number records to return.
... return value an idbrequest object on which subsequent events related to this operation are fired.
IDBIndex.getAllKeys() - Web APIs
count optional the number records to return.
... return 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 returns 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 returned records are sorted based on the index, not the primary key.
IDBIndex.locale - Web APIs
WebAPIIDBIndexlocale
the locale read-only property of the idbindex interface returns 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 returns the current locale being used in this index, in other words, it never returns "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 returned records are sorted based on the index, not the primary key.
IDBIndex.name - Web APIs
WebAPIIDBIndexname
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 returned records are sorted based on the index, not the primary key.
... the name of the index is logged to the console: it should be returned as lname.
FileHandle.open() - Web APIs
summary the open method returns a lockedfile object that allows to safely write in the file.
... return a lockedfile object.
IDBMutableFile - Web APIs
methods mutablefile.open() returns a lockedfile object to read or write the associated file safely.
... mutablefile.getfile() returns a domrequest object.
IDBObjectStore.clear() - Web APIs
the clear() method of the idbobjectstore interface creates and immediately returns an idbrequest object, and clears this object store in a separate thread.
... syntax var request = objectstore.clear(); returns 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 returns a new idbindex object in the connected database.
... return value an idbindex object: the newly created index.
IDBObjectStore.delete() - Web APIs
the delete() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, deletes the specified record or records.
... return 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 returns an idbrequest object, and, in a separate thread, returns the object store selected by the specified key.
... return 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 returns an idbrequest object, and, in a separate thread, returns the key selected by the specified query.
... return 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 returns an idbrequest object, and, in a separate thread, returns a new idbcursorwithvalue object.
... return 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 returns an idbrequest object whose result will be set to an idbcursor that can be used to iterate through matching results.
... return 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 returns 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 returned 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 returned.
...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 returned 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 returns 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 returned 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
WebAPIIDBRequestresult
the result read-only property of the idbrequest interface returns 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 returned 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 returns a domstringlist of names of idbobjectstore objects.
... syntax var mydatabase = transactionobj.objectstorenames; returns a domstringlist of names of idbobjectstore objects.
IDBTransaction.error - Web APIs
the idbtransaction.error property of the idbtransaction interface returns one of several types of error when there is an unsuccessful transaction.
...in chrome 48+/firefox 58+ this property returns a domexception because domerror has been removed from the dom standard.
IDBTransaction.mode - Web APIs
the mode read-only property of the idbtransaction interface returns 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>'; }; // return 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() returns an object store that has already been added to the scope of this transaction.
... returns idbobjectstoresync an object for accessing the requested object store.
IDBVersionChangeEvent - Web APIs
idbversionchangeevent.oldversion read only returns the old version of the database.
... idbversionchangeevent.newversion read only returns the new version of the database.
IdleDeadline - Web APIs
methods idledeadline.timeremaining() returns 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 returning.
ImageData() - Web APIs
the imagedata() constructor returns a newly instantiated imagedata object built from the typed array given and having the specified width and height.
... return value a new imagedata object.
IndexedDB API - Web APIs
this method returns an idbrequest object; asynchronous operations communicate to the calling application by firing events on idbrequest objects.
... idbcursorwithvalue iterates over object stores and indexes and returns the cursor's current value.
firesTouchEvents - Web APIs
the inputdevicecapabilities.firestouchevents read-only property returns a boolean that indicates whether the device dispatches touch events.
... syntax var boolean = inputdevicecapabilities.firestouchevents returns 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 returns an array of static ranges that will be affected by a change to the dom if the input event is not canceled.
... return value an array of staticrange objects.
InputEvent.isComposing - Web APIs
the inputevent.iscomposing read-only property returns 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); // return 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 returns the serviceworker that is currently actively controlling the page.
... this will return null if no active worker is already controlling the page.
InstallEvent - Web APIs
installevent.activeworker read only returns the serviceworker that is currently controlling the page.
...resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return 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
returns a boolean value indicating false if the software install feature has been turned off, and true if it's on.
... note that this return value does not indicate anything about the success of the installation.
IntersectionObserver.IntersectionObserver() - Web APIs
the intersectionobserver() constructor creates and returns a new intersectionobserver object.
... return 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() returns 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.
... return 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 returns 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.
... return value a promise that resolves with an instance of keyboardlayoutmap.
Keyboard.lock() - Web APIs
WebAPIKeyboardlock
the lock() method of the keyboard interface returns a promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard.
... return value a promise.
Keyboard.unlock() - Web APIs
WebAPIKeyboardunlock
the unlock() method of the keyboard interface unlocks all keys captured by the keyboard.lock() method and returns synchronously.
... return 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 returns the unicode value of a character key pressed during a keypress event.
... syntax var code = event.charcode; return 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 returns a boolean that indicates if the control key was pressed (true) or not (false) when the event occured.
... syntax var ctrlkeypressed = instanceofkeyboardevent.ctrlkey return 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 returns 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); // return 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 returning a boolean that indicates if the meta key was pressed (true) or not (false) when the event occurred.
... syntax var metakeypressed = instanceofkeyboardevent.metakey return 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 returns a boolean that is true if the given key is being held down such that it is automatically repeating.
... syntax var repeat = event.repeat; return 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 returns the numeric keycode of the key pressed, or the character code (charcode) for an alphanumeric key pressed.
... syntax var keyresult = event.which; return 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 returns a boolean indicating whether the object has an element with the specified key.
... return value a boolean indicating whether the specifed key was found.
Keyboard API - Web APIs
keyboard provides the keyboard.getlayoutmap method, which returns a promise that resolves with a keyboardlayoutmap object that contains members for converting codes to keys.
... navigator.keyboard read only returns a keyboard object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
KeyframeEffect.setKeyframes() - Web APIs
this is the canonical format returned by the getkeyframes() method.
... return value void.
KeyframeEffect.target - Web APIs
syntax var targetelement = document.getelementbyid("elementtoanimate"); var keyframes = new keyframeeffect( targetelement, keyframeblock, timingoptions ); // returns #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' } ); // returns <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
WebAPILinkStyle
linkstyle.sheet read only returns the cssstylesheet object associated with the given element, or null if there is none.
... working draft linkstyle.sheet returns more specialized cssstylesheet instead of stylesheet document object model (dom) level 2 style specificationthe definition of 'linkstyle' in that specification.
LocalFileSystem - Web APIs
returns 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.
... returns 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
returns filesystemsync an object that represents the file system.
... returns entrysync an object that represents entries in the file system.
Location: hash - Web APIs
WebAPILocationhash
the hash property of the location interface returns 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); // returns '#examples' </script> specifications specification status comment html living standardthe definition of 'hash' in that specification.
Location: href - Web APIs
WebAPILocationhref
the href property of the location interface is a stringifier that returns 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; // returns: 'https://developer.mozilla.org/location/href' specifications specification status comment html living standardthe definition of 'href' in that specification.
Location: toString() - Web APIs
WebAPILocationtoString
the tostring() stringifier method of the location interface returns 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(); // returns: 'https://developer.mozilla.org/docs/location/tostring' specifications specification status comment html living standard living standard ...
Locks.mode - Web APIs
WebAPILockmode
the mode read-only property of the lock interface returns the access mode passed to lockmanager.request() when the lock was requested.
...lockmanager is the object returned by navigator.locks.
Locks.name - Web APIs
WebAPILockname
the name read-only property of the lock interface returns the name passed to lockmanager.request selected when the lock was requested.
...lockmanager is the object returned by navigator.locks.
LockManager.query() - Web APIs
WebAPILockManagerquery
the query() method of the lockmanager interface returns a promise which resolves with an object containing information about held and pending locks.
... return 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 returned data.
... return 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 returns information about the work involved in a long task and its associate frame context.
MIDIAccess - Web APIs
properties midiaccess.inputs read only returns an instance of midiinputmap which provides access to any available midi input ports.
... midiaccess.outputs read only returns 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 returns the msgesture object for this gesture event.
MSManipulationEvent - Web APIs
properties property description currentstateread only returns the current state of a manipulation event.
... laststateread only returns the last state after a manipulation change event.
MediaCapabilities.decodingInfo() - Web APIs
the mediacapabilities.decodinginfo() method, part of the media capabilities api, returns 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.
... return 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, returns 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.
... return 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 returns 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 returns 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 returns an object based on the mediatracksupportedconstraints dictionary, whose member fields each specify one of the constrainable properties the user agent understands.
... return value a new object based on the mediatracksupportedconstraints dictionary listing the constraints supported by the user agent.
close() - Web APIs
then, it returns a promise.
...}); return value a promise.
load() - Web APIs
the mediakeysession.load() method returns a promise that resolves to a boolean value after loading data for a specified session object.
... return value a promise that resolves to a boolean indicating whether the load succeeded or failed.
remove() - Web APIs
the mediakeysession.remove() method returns a promise after removing any session data associated with the current object.
... return 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 returns a promise .
... return value a promise.
MediaKeyStatusMap.entries() - Web APIs
the entries() read-only property of the mediakeystatusmap interface returns a new iterator object, containing an array of [key, value] pairs for each element in the status map, in insertion order.
... returns exceptions specifications specification status comment encrypted media extensions recommendation initial definition.
MediaKeyStatusMap.has() - Web APIs
the has property of the mediakeystatusmap interface returns 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 returned returns a boolean.
MediaKeyStatusMap.keys() - Web APIs
the keys property of the mediakeystatusmap interface returns a new iterator object, containing keys for each element in the status map, in insertion order.
... returns a new iterator.
MediaKeyStatusMap.values() - Web APIs
the values property of the mediakeystatusmap interface returns a new iterator object, containing values for each element in the status map, in insertion order.
... returns a new iterator.
MediaKeys - Web APIs
WebAPIMediaKeys
methods mediakeys.createsession() returns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
... mediakeys.setservercertificate() returns 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 returns true if the document currently matches the media query list, or false if not.
... syntax var matches = mediaquerylistevent.matches; value a boolean; returns true if the document currently matches the media query list, false if not.
MediaRecorder.isTypeSupported - Web APIs
the mediarecorder.istypesupported() static method returns a boolean which is true if the mime type specified is one the user agent should be able to successfully record.
... return 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 returns the current state of the current mediarecorder object.
... record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); // will return "recording" console.log("recorder started"); } ...
MediaRecorderErrorEvent.error - Web APIs
example this function creates and returns 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 */ return recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecordererrorevent.error' in that specification.
MediaRecorderErrorEvent - Web APIs
the mediarecordererrorevent interface represents errors returned by the mediastream recording api.
... constructor mediastreamrecorderevent() creates and returns a new mediarecordererrorevent event object with the given parameters.
MediaSession.setActionHandler() - Web APIs
the callback receives no input parameters, and should not return a value.
... return value undefined.
MediaSource.addSourceBuffer() - Web APIs
the new sourcebuffer is also returned.
... return 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 returns a newly-created mediastream, which serves as a collection of media tracks, each represented by a mediastreamtrack object.
... return 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 returns a boolean value which is true if the stream is currently active; otherwise, it returns false.
...when that stream becomes available (that is, when the returned promise is fulfilled, a button on the page is updated based on whether or not the stream is currently active.
MediaStream.ended - Web APIs
WebAPIMediaStreamended
the ended read-only property of the mediastream interface returns 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 returns true if the end of the stream has been reached.
MediaStream.getTracks() - Web APIs
the gettracks() method of the mediastream interface returns a sequence that represents all the mediastreamtrack objects in this stream's track set, regardless of mediastreamtrack.kind.
... return value an array of mediastreamtrack objects.
MediaStreamAudioSourceNode() - Web APIs
the web audio api's mediastreamaudiosourcenode() constructor creates and returns a new mediastreamaudiosourcenode object which uses the first audio track of a given mediastream as its source.
... return 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 returns 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() return 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 returns a new mediastreamtrackaudiosourcenode object whose audio is taken from the mediastreamtrack specified in the given options object.
... return value a new mediastreamtrackaudiosourcenode object representing the audio node whose media is obtained from the specified media track.
MediaStreamTrackEvent() - Web APIs
the mediastreamtrackevent() constructor returns a newly created mediastreamtrackevent object, which represents an event announcing that a mediastreamtrack has been added to or removed from a mediastream.
... return 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 return a value of "recording".
... grabbing and using the blob when recording has stopped, the state property returns 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 returned by a call to mediadevices.getsupportedconstraints().
...that means that a given track will only return 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 returned 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 returned 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 returned by a call to mediadevices.getsupportedconstraints().
...that means that a given track will only return 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 returned 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 returned 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 returned 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 return exactly one value for deviceid.
MessageChannel() - Web APIs
the messagechannel() constructor of the messagechannel interface returns a new messagechannel object with two new messageport objects.
... syntax var channel = new messagechannel(); returns a newly created messagechannel object.
MouseEvent.button - Web APIs
WebAPIMouseEventbutton
syntax var buttonpressed = instanceofmouseevent.button return 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 return value can be negative.
MouseEvent.getModifierState() - Web APIs
the mouseevent.getmodifierstate() method returns 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); returns a boolean parameters keyarg a modifier key value.
MouseEvent.pageX - Web APIs
WebAPIMouseEventpageX
the pagex read-only property of the mouseevent interface returns 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 returned 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 returns null.
... syntax var target = instanceofmouseevent.relatedtarget return value an eventtarget object or null.
MutationObserver.MutationObserver() - Web APIs
the dom mutationobserver() constructor — part of the mutationobserver interface — creates and returns a new observer which invokes a specified callback when dom events occur.
... return value a new mutationobserver object, configured to call the specified callback when dom mutations occur.
MutationObserver.takeRecords() - Web APIs
the mutationobserver method takerecords() returns 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.
... return 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 returns 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 returns them in a new array of mutationrecord objects.
NDEFReader() - Web APIs
the ndefreader() constructor of the web nfc api returns a newly constructed ndefreader object used to read ndef messages from compatiable nfc devices, e.g.
... return value a new ndefreader.
NDEFReader.scan() - Web APIs
WebAPINDEFReaderscan
return 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 returned 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 returns a newly constructed ndefrecord object that represents data that can be read from or written to compatible nfc devices, e.g.
... return 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 returns the result.
... return value a list of ndefrecords.
NDEFWriter() - Web APIs
the ndefwriter() constructor of the web nfc api returns a newly constructed ndefwriter object used to write ndef messages to compatiable nfc devices, e.g.
... return value a new ndefwriter.
NDEFWriter.write() - Web APIs
WebAPINDEFWriterwrite
return 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 returned 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 returned.
... this information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information.
Navigator.battery - Web APIs
WebAPINavigatorbattery
the battery read-only property returns 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 returns a battery promise.
Navigator.buildID - Web APIs
WebAPINavigatorbuildID
returns the build identifier of the browser.
... in modern browsers this property now returns a fixed timestamp as a privacy measure, e.g.
Navigator.canShare() - Web APIs
the navigator.canshare() method of the web share api returns true if a call to navigator.share() would succeed.
... return value a boolean.
Navigator.clipboard - Web APIs
the clipboard api adds to the navigator interface the read-only clipboard property, which returns the clipboard object used to read and write the clipboard's contents.
...this happens because readtext() returns 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 returning version.
... return value undefined.
Navigator.mediaDevices - Web APIs
the navigator.mediadevices read-only property returns 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; return value the mediadevices singleton object.
Navigator.mediaSession - Web APIs
the read-only navigator property mediasession returns 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
return values the sendbeacon() method returns true if the user agent successfully queued the data for transfer.
... otherwise, it returns false.
Navigator.wakeLock - Web APIs
the wakelock read-only property returns 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 returns 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 return 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 returns the number of logical processors which may be available to the user agent.
NavigatorID.appCodeName - Web APIs
note: do not rely on this property to return a real product name.
... all browsers return "mozilla" as the value of this property.
NavigatorID.appName - Web APIs
note: do not rely on this property to return a real browser name.
... all browsers return "netscape" as the value of this property.
NavigatorID.product - Web APIs
note: do not rely on this property to return a real product name.
... all browsers return "gecko" as the value of this property.
NavigatorLanguage.language - Web APIs
the navigatorlanguage.language read-only property returns 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 returned is lowercase: "en-us", "fr-fr" etc.
Online and offline events - Web APIs
you also need to know when your application has returned to an 'online' status again.
...according to the specification: the navigator.online attribute must return 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
returns a mimetypearray object, which contains a list of mimetype objects representing the mime types recognized by the browser.
... example function isjavapresent() { return 'application/x-java-applet' in navigator.mimetypes; } function getjavaplugindescription() { var mimetype = navigator.mimetypes['application/x-java-applet']; if (mimetype === undefined) { // no java plugin present return undefined; } return 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 returns the singleton storagemanager object used to access the overall storage capabilities of the browser for the current site or app.
... the returned 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 returns the storagemanager singleton object which is used to access the storage manager.
... through the returned 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 returns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology.
... syntax var max = networkinformation.downlinkmax return 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 returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.
... syntax rtt = networkinformation.rtt return value a number.
NetworkInformation.type - Web APIs
the networkinformation.type read-only property returns the type of connection a device is using to communicate with the network.
... syntax var type = netinfo.type return 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
WebAPINodeappendChild
return value the returned value is the appended child (achild), except when achild is a documentfragment, in which case the empty documentfragment is returned.
... notes chaining may not work as expected, due to appendchild() returning 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
WebAPINodebaseURI
the baseuri read-only property returns the absolute base url of a node.
...note that obtaining the base url for a document may return different urls over time if the <base> tags or the document's location change.
Node.baseURIObject - Web APIs
the node.baseuriobject property returns the nsiuri representing the node's (typically a document or an element) base url.
... it's similar to node.baseuri, except it returns an nsiuri instead of a string.
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
return value returns the added child (unless newnode is a documentfragment, in which case the empty documentfragment is returned).
... 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 returns 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 returns a boolean with a value of true if the namespace is the default namespace on the given node or false if not.
... return value result is a boolean that holds the return value true or false.
Node.isSupported() - Web APIs
WebAPINodeisSupported
the node.issupported()returns 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 return true.
Node.lastChild - Web APIs
WebAPINodelastChild
the node.lastchild read-only property returns the last child of the node.
...it returns null if there are no child elements.
Node.rootNode - Web APIs
WebAPINoderootNode
the node.rootnode read-only property returns 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 return 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 returns 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) { return 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 returns 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) { return 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 returns 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) { return 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 returned by the nodeiterator.
... example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return 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
WebAPINodeListentries
the nodelist.entries() method returns an iterator allowing to go through all key/value pairs contained in this object.
... syntax list.entries(); return value returns an iterator.
NodeList.keys() - Web APIs
WebAPINodeListkeys
the nodelist.keys() method returns an iterator allowing to go through all keys contained in this object.
... syntax nodelist.keys(); return value returns an iterator.
NodeList.values() - Web APIs
WebAPINodeListvalues
the nodelist.values() method returns an iterator allowing to go through all values contained in this object.
... syntax nodelist.values(); return value returns an iterator.
NonDocumentTypeChildNode - Web APIs
nondocumenttypechildnode.previouselementsibling read only returns 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 returns 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
WebAPINotificationdata
the data read-only property of the notification interface returns 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 return 'i like peas.' specifications specification status comment notifications apithe definition of 'data' in that specification.
Notification.requestPermission() - Web APIs
deprecated in favor of the promise return value.
... returns a promise that resolves to a domstring with the permission picked by the user.
OES_vertex_array_object.isVertexArrayOES() - Web APIs
the oes_vertex_array_object.isvertexarrayoes() method of the webgl api returns true if the passed object is a webglvertexarrayobject object.
... return 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 returns a webglvertexarrayobject object when used in the gl.getparameter() method as the pname parameter.
... ext.isvertexarrayoes() returns true if a given object is a webglvertexarrayobject.
OfflineAudioContext.OfflineAudioContext() - Web APIs
the offlineaudiocontext() constructor—part of the web audio api—creates and returns a new offlineaudiocontext object instance, which can then be used to render audio to an audiobuffer rather than to an audio output device.
... return value a new offlineaudiocontext object whose associated audiobuffer is configured as requested.
OfflineAudioContext.startRendering() - Web APIs
returns void.
... when the startrendering() promise resolves, rendering has completed and the output audiobuffer is returned out of the promise.
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 returns a promise.
... returns 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 returns a promise.
... when the startrendering() promise resolves, rendering has completed and the output audiobuffer is returned out of the promise.
OffscreenCanvas.height - Web APIs
the height property returns and sets the height of an offscreencanvas object.
... syntax var pxl = offscreen.height; offscreen.height = pxl; examples creating a new offscreen canvas and returning 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 returns and sets the width of an offscreencanvas object.
... syntax var pxl = offscreen.width; offscreen.width = pxl; examples creating a new offscreen canvas and returning 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 returned is read-only, the value it represents is not).
... oscillatornode.detune an a-rate audioparam representing detuning of oscillation in cents (though the audioparam returned is read-only, the value it represents is not).
ParentNode.firstElementChild - Web APIs
the parentnode.firstelementchild read-only property returns 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) { return node; } } return null; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.firstelementchild' in that specification.
ParentNode.prepend() - Web APIs
return 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')) { return; } 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 returns a string containing the top-level administrative subdivision of the country in which the address is located.
...in such cases, the browser returns an empty string as the value of region.
PaymentAddress.regionCode - Web APIs
the regioncode read-only attribute of the paymentaddress interface returns 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 returns an empty string.
PaymentAddress.toJSON() - Web APIs
the tojson() property of the paymentaddress interface is a standard serializer that returns a json representation of the paymentaddress object's properties.
... return value a json object.
PaymentRequest.prototype.id - Web APIs
WebAPIPaymentRequestid
the id read-only attribute of the paymentrequest interface returns 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 returned 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, return a paymentdetailsupdate object // with any changes or errors.
... return 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.
PaymentRequestEvent.openWindow() - Web APIs
it returns a promise that resolves with a reference to a windowclient.
... return value a promise that resolves with a reference to a windowclient.
PaymentResponse.methodName - Web APIs
the methodname read-only property of the paymentresponse interface returns 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 returned from paymentrequest.show().
PaymentResponse.shippingOption - Web APIs
the shippingoption read-only property of the paymentrequest interface returns 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 + '\''); return; } 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 return value none this method has no return 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"); return; } // 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"); return; } // getentries should now return zero var p = performance.getentriesbytype("resource"); if (p.length == 0) console.log("...
performance.setResourceTimingBufferSize() - Web APIs
return value none this method has no return value.
... example function setresourcetimingbuffersize(maxsize) { if (performance === undefined) { log("browser does not support web performance"); return; } 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 returns a json representation of the performance object's properties.
... syntax myperf = performance.tojson() arguments none return 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 returned by the performanceentry.entrytype property.
... methods performanceentry.tojson() returns a json representation of the performanceentry object.
PerformanceNavigationTiming.domComplete - Web APIs
the domcomplete read-only property returns 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; return 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 returns a timestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes.
... syntax perfentry.domcontentloadedeventend; return 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 returns 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; return 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 returns 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; return 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 returns a timestamp which is equal to the time when the load event of the current document is completed.
... syntax perfentry.loadeventend; return 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 returns a timestamp representing the time value equal to the time immediately before the load event of the current document is fired.
... syntax perfentry.loadeventstart; return 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 returns a timestamp representing the number of redirects since the last non-redirect navigation under the current browsing context.
... syntax perfentry.redirectcount; return 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 returns a json representation of the performancenavigationtiming object.
... syntax json = resourceperfentry.tojson(); arguments none return 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 returns a string representing the type of navigation.
... syntax perfentry.type; return value a string which is one of the values listed above.
PerformanceNavigationTiming.unloadEventEnd - Web APIs
the unloadeventend read-only property returns 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; return 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 returns the current list of performance entries stored in the performance observer, emptying it out.
... return value a list of performanceentry objects.
PerformanceObserver - Web APIs
constructor performanceobserver() creates and returns a new performanceobserver object.
... performanceobserver.takerecords() returns the current list of performance entries stored in the performance observer, emptying it out.
PerformanceResourceTiming.connectEnd - Web APIs
the connectend read-only property returns the timestamp immediately after the browser finishes establishing the connection to the server to retrieve the resource.
... syntax resource.connectend; return value a domhighrestimestamp representing the time after a connection is established.
PerformanceResourceTiming.connectStart - Web APIs
the connectstart read-only property returns the timestamp immediately before the user agent starts establishing the connection to the server to retrieve the resource.
... syntax resource.connectstart; return 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 returns the timestamp immediately after the browser finishes the domain name lookup for the resource.
... syntax resource.domainlookupend; return 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 returns the timestamp immediately before the browser starts the domain name lookup for the resource.
... syntax resource.domainlookupstart; return 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 return the size of the payload body before removing any applied content-codings.
... syntax resource.encodedbodysize; return value a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings.
PerformanceResourceTiming.fetchStart - Web APIs
if there are http redirects the property returns the time immediately before the user agent starts to fetch the final resource in the redirection.
... syntax resource.fetchstart; return value a domhighrestimestamp immediately before the browser starts to fetch the resource.
PerformanceResourceTiming.responseEnd - Web APIs
the responseend read-only property returns 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; return 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 returns a timestamp immediately after the browser receives the first byte of the response from the server, cache, or local resource.
... syntax resource.responsestart; return 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 returns a json representation of the performanceresourcetiming object.
... syntax json = resourceperfentry.tojson(); arguments none return 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 returns zero.
... syntax resource.transfersize; return 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 returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running.
... if the resource is not intercepted by a service worker the property will always return 0.
PerformanceServerTiming.toJSON - Web APIs
the tojson() method of the performanceservertiming interface returns a domstring that is the json representation of the performanceservertiming object.
... return value a domstring containing json.
PerformanceServerTiming - Web APIs
methods performanceservertiming.tojson() returns 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(''); return 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 returns 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 returns 0.
PerformanceTiming.loadEventStart - Web APIs
the legacy performancetiming.loadeventstart read-only property returns 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 returns 0.
PerformanceTiming.redirectEnd - Web APIs
the legacy performancetiming.redirectend read-only property returns 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 returned is 0.
PerformanceTiming.redirectStart - Web APIs
the legacy performancetiming.redirectstart read-only property returns 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 returned is 0.
PerformanceTiming.secureConnectionStart - Web APIs
the legacy performancetiming.secureconnectionstart read-only property returns 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 returns 0.
PerformanceTiming.unloadEventEnd - Web APIs
the legacy performancetiming.unloadeventend read-only property returns 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 returned is 0.
PerformanceTiming.unloadEventStart - Web APIs
the legacy performancetiming.unloadeventstart read-only property returns 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 returned is 0.
Using the Performance API - Web APIs
the now() method returns 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(); return (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 returns the state of a requested permission.
... this property returns one of 'granted', 'denied', or 'prompt'.
PermissionStatus - Web APIs
properties permissionstatus.state read only returns the state of a requested permission; one of 'granted', 'denied', or 'prompt'.
... permissionstatus.statusread only returns 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 return true for both notifications and push.
... returns 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 returns 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 return a promise that resolves with the permissionstatus for a specific api.
PhotoCapabilities.redEyeReduction - Web APIs
the redeyereduction read-only property of the photocapabilities interface returns 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
WebAPIPlugin
methods plugin.item returns the mime type of a supported content type, given the index number into a list of supported types.
... plugin.nameditem returns the mime type of a supported item.
PointerEvent.getCoalescedEvents() - Web APIs
the getcoalescedevents() method of the pointerevent interface returns a sequence of all pointerevent instances that were coalesced into the dispatched pointermove event.
... returns a sequence of pointerevent instances.
PointerEvent.isPrimary - Web APIs
it returns true if the pointer that caused the event to be fired is the primary device and returns false otherwise.
... syntax var isprimary = pointerevent.isprimary; return value isprimary returns true if the pointer for this event is the primary pointer and returns false otherwise.
PointerEvent - Web APIs
methods pointerevent.getcoalescedevents() returns a sequence of all pointerevent instances that were coalesced into the dispatched pointermove event.
... pointerevent.getpredictedevents() returns 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 return.
...if set to infinity the device must return 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 return a position.
... the default value is infinity, meaning that getcurrentposition() won't return until the position is available.
PromiseRejectionEvent() - Web APIs
the promiserejectionevent() constructor returns a newly created promiserejectionevent, which represents events fired when a javascript promise is rejected.
... return value a new promiserejectionevent configured as specified by the parameters.
PublicKeyCredential.getClientExtensionResults() - Web APIs
getclientextensionresults() is a method of the publickeycredential interface that returns an arraybuffer which contains a map between the extensions identifiers and their results after having being processed by the client.
... return 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 returns a promise which resolves to true if a user-verifying platform authenticator is available.
... return 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 return the results of processing those extensions.
... publickeycredential.isuserverifyingplatformauthenticatoravailable()secure context a static method returning a promise which resolves to true if an authenticator bound to the platform is capable of verifying the user.
PushEvent.data - Web APIs
WebAPIPushEventdata
the data read-only property of the pushevent interface returns a reference to a pushmessagedata object containing data sent to the pushsubscription.
... self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } 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
WebAPIPushEvent
additional properties: pushevent.data read only returns a reference to a pushmessagedata object containing data sent to the pushsubscription.
... self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } 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 returning the result.
... returns 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 returns a json representation of the subscription properties, providing a useful shortcut.
... returns a json object.
PushSubscription.unsubscribe() - Web APIs
the unsubscribe() method of the pushsubscription interface returns a promise that resolves to a boolean when the current subscription is successfully unsubscribed.
... returns 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() returns to the caller.
... return value undefined.
RTCDataChannelEvent - Web APIs
the rtcdatachannelevent() constructor returns 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 returns 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 returns 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; } } }); return results; } note that in this code, the new and connecting states are being treated as a single connectionpending status in the returned object.
RTCIceCandidate.RTCIceCandidate() - Web APIs
the rtcicecandidate() constructor creates and returns a new rtcicecandidate object, which can be configured to represent a single ice candidate.
... return 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:myturn.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 returns 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 return, 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(); return 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 returned 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 returns 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() returns 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 returned 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; } }); } return 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 returns 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 returns 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() returns 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.
... return 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, returning 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: return 0; } return 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, returning 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: return 0; } return 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 returned by retransmittedpacketssent.
...these retransmitted packets are included in the value returned by packetssent.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
the read-only rtcpeerconnection property cantrickleicecandidates returns 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) { return pc.localdescription; } return 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 returning one of the string values specified by the enum rtcpeerconnectionstate.
...these values are returned by the connectionstate property.
RTCPeerConnection.currentLocalDescription - Web APIs
the read-only property rtcpeerconnection.currentlocaldescription returns 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; return 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 returns 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; return 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 returns an rtccertificate, providing access to it.
... return value a reference to an rtccertificate object.
RTCPeerConnection.getIdentityAssertion() - Web APIs
the method returns immediately.
... syntax pc.getidentityassertion(); there is neither parameter nor return value for this method.
RTCPeerConnection.getTransceivers() - Web APIs
the rtcpeerconnection interface's gettransceivers() method returns a list of the rtcrtptransceiver objects being used to send and receive data on the connection.
... return 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 returns 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 returned using the rtcpeerconnection.icegatheringstate property.
RTCPeerConnection.localDescription - Web APIs
the read-only property rtcpeerconnection.localdescription returns an rtcsessiondescription describing the session for the local end of the connection.
... syntax var sessiondescription = peerconnection.localdescription; on a more fundamental level, the returned value is the value of rtcpeerconnection.pendinglocaldescription if that property isn't null; otherwise, the value of rtcpeerconnection.currentlocaldescription is returned.
RTCPeerConnection: negotiationneeded event - Web APIs
pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => return 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 => return 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) { return 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() returns, the offer returned 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.
... return 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; return 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 returned by the the rtcrtpreceiver method getparameters().
... function getrtcpcname(receiver) { let parameters = receiver.getparameters(); return 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 returns an array of rtcrtpcontributingsource instances, each corresponding to one csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... return value an array of rtcrtpcontributingsource instances.
RTCRtpReceiver.getSynchronizationSources() - Web APIs
the getsynchronizationsources() method of the rtcrtpreceiver interface returns an array of rtcrtpcontributingsource instances, each corresponding to one ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... return value an array of rtcrtpsynchronizationsource instances.
RTCRtpSender.dtmf - Web APIs
WebAPIRTCRtpSenderdtmf
the read-only dtmf property on the rtcrtpsender interface returns 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 returned rtcdtmfsender object.
RTCRtpSender.setParameters() - Web APIs
return value a promise that resolves when the rtcrtpsender.track property is updated with the given parameters.
... exceptions if an error occurs, the returned 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, returning 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: return 0; } return 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 returned to the user agent's defaults.
... return 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 return true if the connection is stopped.
... return value undefined exceptions invalidstateerror the rtcpeerconnection of which the transceiver is a member is closed.
RTCSessionDescription - Web APIs
rtcsessiondescription() this constructor returns a new rtcsessiondescription.
... rtcsessiondescription.tojson() returns a json description of the object.
RTCTrackEvent() - Web APIs
the rtctrackevent() constructor creates and returns a new rtctrackevent object, configured to describe the track which has been added to the rtcpeerconnection.
... return 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 returned 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 returned.
RadioNodeList - Web APIs
on retrieving the value property, the value of the currently checked radio button is returned 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 returned.
Range.cloneRange() - Web APIs
WebAPIRangecloneRange
the range.clonerange() method returns a range object with boundary points identical to the cloned range.
... the returned clone is copied by value, not reference, so a change in either range does not affect the other.
Range.collapsed - Web APIs
WebAPIRangecollapsed
the range.collapsed read-only property returns a boolean flag indicating whether the start and end points of the range are at the same position.
... it returns 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 returns 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 returned value.
Range.isPointInRange() - Web APIs
the range.ispointinrange() method returns a boolean indicating whether the given point is in the range.
... it returns true if the point (cursor position) at offset within referencenode is within this range.
ReadableByteStreamController - Web APIs
properties readablebytestreamcontroller.byobrequest read only returns the current byob pull request.
... readablebytestreamcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue.
ReadableStream.locked - Web APIs
the locked read-only property of the readablestream interface returns whether or not the readable stream is locked to a reader.
...}); const reader = stream.getreader(); stream.locked // should return true, as the stream has been locked to a reader specifications specification status comment streamsthe definition of 'locked' in that specification.
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
the readablestreambyobreader() constructor creates and returns a readablestreambyobreader object instance.
... return value an instance of the readablestreambyobreader object.
ReadableStreamBYOBReader.read() - Web APIs
the read() method of the readablestreambyobreader interface returns a promise providing access to the next chunk in the byte stream's internal queue.
... return 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 returned by the reader’s readablestreambyobreader.read() method has not finished.
... return 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 returned by the reader’s readablestreamdefaultreader.read() method has not finished.
... return value undefined.
Report.type - Web APIs
WebAPIReporttype
the type read-only property of the report interface returns the type of report generated, e.g.
... syntax let reporttype = reportinstance.type returns a string representing the type of the report.
Report.url - Web APIs
WebAPIReporturl
the url read-only property of the report interface returns the url of the document that generated the report.
... syntax let reporturl = reportinstance.url returns a string representing the url of the document that generated the report.
ReportingObserver.takeRecords() - Web APIs
the takerecords() method of the reportingobserver interface returns the current list of reports contained in the observer's report queue, and empties the queue.
... syntax reportingobserverinstance.takerecords() return value an array of report objects.
ReportingObserver - Web APIs
reportingobserver.takerecords() returns 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 returns the first generated report and empties the queue.
Request.destination - Web APIs
the destination read-only property of the request interface returns 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; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification.
Request.referrer - Web APIs
WebAPIRequestreferrer
(e.g., client, no-referrer, or a url.) note: if referrer's value is no-referrer, it returns 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; // returns "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 returns 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; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specification.
Response.redirect() - Web APIs
WebAPIResponseredirect
the redirect() method of the response interface returns a response resulting in a redirect to the specified url.
... status optional an optional status code for the response (e.g., 302.) return 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 = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("a...
...wesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specification.
Response.useFinalURL - Web APIs
in other contexts it will return 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; return r; }) } the output will be /page2 and not /test in index.html, since setting the usefinalurl means that the response's url is not set to request's url.
targetElement - Web APIs
if no target element is being animated (for example, because the href attribute specifies an unknown element), the value returned is null.
... editor's draft added null as return value in case that no target element is being animated.
SVGGeometryElement.getPointAtLength() - Web APIs
the svggeometryelement.getpointatlength() method returns the point at a given distance along the path.
... return value a dompoint indicating the point at a given distance along the path.
SVGGeometryElement.getTotalLength() - Web APIs
the svggeometryelement.gettotallength() method returns the user agent's computed value for the total length of the path in user units.
... syntax float someelement.gettotallength(); return value a float indicating the total length of the path in user units.
SVGGeometryElement - Web APIs
svggeometryelement.gettotallength() returns the user agent's computed value for the total length of the path in user units.
... svggeometryelement.getpointatlength() returns 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, returning a promise that resolves once the image data is ready for use.
... return value a promise which resolves once the image data is ready to be used, such as by appending it to the dom, replacing an existing image, and so forth.
SVGImageElement - Web APIs
svgimageelement.decoding returns a domstring representing a hint given to the browser on how it should decode the image.
...returns a promise which resolves once the image data is ready to be used.
SVGPathElement.getPointAtLength() - Web APIs
the svgpathelement.getpointatlength() method returns the point at a given distance along the path.
... return value an svgpoint indicating the point at a given distance along the path.
SVGPathElement.getTotalLength() - Web APIs
the svgpathelement.gettotallength() method returns the user agent's computed value for the total length of the path in user units.
... syntax float someelement.gettotallength(); return value a float indicating the total length of the path in user units.
SVGPoint - Web APIs
WebAPISVGPoint
syntax retobject = svgsvgelement.createsvgpoint() value the returned 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 returned svgpoint object // (which is the variable `s`) s.y = 10; s.x = 10; ...
SVGStylable - Web APIs
methods name & arguments return description getpresentationattribute(in domstring name) cssvalue returns the base (i.e., static) value of a given presentation attribute as an object of type cssvalue.
... the returned 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 returns 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 returns null.
Screen.colorDepth - Web APIs
WebAPIScreencolorDepth
the screen.colordepth read-only property returns the color depth of the screen.
... per the cssom, some implementations return 24 for compatibility reasons.
Screen.height - Web APIs
WebAPIScreenheight
the screen.height read-only property returns the height of the screen in pixels.
...it will only return the real height of the screen if the zoom is set to 100%.
Screen.pixelDepth - Web APIs
WebAPIScreenpixelDepth
returns the bit depth of the screen.
... per the cssom, some implementations return 24 for compatibility reasons.
Screen.width - Web APIs
WebAPIScreenwidth
returns the width of the screen.
...it will only return the real width of the screen if the zoom is set to 100%.
Selection.anchorOffset - Web APIs
the selection.anchoroffset read-only property returns 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 returned.
Selection.containsNode() - Web APIs
partialcontainment optional when true, containsnode() returns true when a part of the node is part of the selection.
... when false, containsnode() only returns true when the entire node is part of the selection.
Selection.focusOffset - Web APIs
the selection.focusoffset read-only property returns 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 returned.
Selection.isCollapsed - Web APIs
the selection.iscollapsed read-only property returns a boolean which indicates whether or not there is currently any text selected.
...in that scenario, calling a selection object's getrangeat() method may return a range object which is collapsed.
Selection.type - Web APIs
WebAPISelectiontype
the type read-only property of the selection interface returns a domstring describing the type of the current selection.
...console.log(selection.type) will return 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 return value — a selection object — in a variable for futher use.
... extensions to other interfaces window.getselection(), document.getselection() returns 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 returns a string representing the current state of the service worker.
...the code listens for any change in the serviceworker.state and returns its value.
ServiceWorkerContainer.controller - Web APIs
the controller read-only property of the serviceworkercontainer interface returns a serviceworker object if its state is activated (the same object returned by serviceworkerregistration.active).
... this property returns null if the request is a force refresh (shift + refresh) or if there is no active worker.
ServiceWorkerContainer.getRegistrations() - Web APIs
the method returns a promise that resolves to an array of serviceworkerregistration.
... return value a promise that resolves to an array of serviceworkerregistration objects.
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) return client.focus(); } if (clients.openwindow) return 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) return client.focus(); } if (clients.openwindow) return 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 => { return fetch("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method.
... when the returned promise is resolved, we receive the new subscription.
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); returns a promise that immediately resolves with undefined.
... self.addeventlistener('install', function(event) { // the promise that skipwaiting() returns can be safely ignored.
ServiceWorkerRegistration.unregister() - Web APIs
the unregister() method of the serviceworkerregistration interface unregisters the service worker registration and returns a promise.
... return value promise resolves with a boolean indicating whether the service worker has unregistered or not.
ShadowRoot.host - Web APIs
WebAPIShadowRoothost
the host read-only property of the shadowroot returns a reference to the dom element the shadowroot is attached to.
... // return 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 returns the applicationcache object for the worker (see using the application cache).
... example if a shared worker has an appcache associated with it, you can return 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 returns 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", returnable by running self.name from inside the shared worker.
SourceBuffer.appendBufferAsync() - Web APIs
it returns a promise which is fulfilled once the buffer has been appended.
... return value a promise which is fulfilled when the buffer has been added successfully to the sourcebuffer, or null if the request could not be initiated.
SourceBuffer.removeAsync() - Web APIs
a promise is returned, which is fulfilled when the buffers in the specified time range have been removed.
... return 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
WebAPISpeechGrammarsrc
the src property of the speechgrammar interface sets and returns 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 return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set in line 4.
SpeechGrammar.weight - Web APIs
the optional weight property of the speechgrammar interface sets and returns 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 return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set in line 4.
SpeechGrammarList.length - Web APIs
the length read-only property of the speechgrammarlist interface returns 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 return 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 return a speechrecognitionresult.
... syntax myspeechrecognition.abort(); returns void.
SpeechRecognition.interimResults - Web APIs
the interimresults property of the speechrecognition interface controls whether interim results should be returned (true) or not (false.) interim results are results that are not yet final (e.g.
...true means interim results are returned, 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 returns 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 returns 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 return a speechrecognitionresult using the audio captured so far.
... syntax myspeechrecognition.stop(); returns void.
SpeechRecognitionError - Web APIs
speechrecognitionerror.error read only returns the type of error raised.
... speechrecognitionerror.message read only returns a message describing the error in more detail.
SpeechRecognitionErrorEvent - Web APIs
speechrecognitionerrorevent.error read only returns the type of error raised.
... speechrecognitionerrorevent.message read only returns a message describing the error in more detail.
SpeechRecognitionEvent.emma - Web APIs
the emma read-only property of the speechrecognitionevent interface returns 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 return null.
SpeechRecognitionEvent.resultIndex - Web APIs
the resultindex read-only property of the speechrecognitionevent interface returns 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); // returns 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 returned 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 return 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 returns 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 return 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 returns 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 return 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 returns 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 return 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 returns 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 returns 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; returned value an a-rate audioparam containing the panning to apply.
... note: though the audioparam returned 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 returns a promise that resolves to true if permission is granted and box mode is persistent, and false otherwise.
... return value a promise that resolves to a boolean.
StorageManager.persisted() - Web APIs
the persisted() method of the storagemanager interface returns a promise that resolves to true if box mode is persistent for your site's storage.
... returns a promise that resolves to a boolean.
StorageQuota.queryInfo - Web APIs
the queryinfo() property of the storagequota interface returns a storageinfo object containting the current data usage and available quota information for the application.
... returns 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 returns a promise to an instance of storageinfo.
... returns a reference to a storageinfo object.
StylePropertyMapReadOnly.entries() - Web APIs
the stylepropertymapreadonly.entries() method returns 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).
... return 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 returns an array of cssstylevalue objects containing the values for the provided property.
... return value an array of cssstylevalue objects.
StylePropertyMapReadOnly.keys() - Web APIs
the stylepropertymapreadonly.keys() method returns a new array iterator containing the keys for each item in stylepropertymapreadonly syntax stylepropertymapreadonly.keys() parameters none.
... return value a new array.
StylePropertyMapReadOnly.values() - Web APIs
the stylepropertymapreadonly.values() method returns a new array iterator containing the values for each index in the stylepropertymapreadonly object.
... return value a new array.
Stylesheet.href - Web APIs
WebAPIStyleSheethref
the href property of the stylesheet interface returns 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> // returns "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 returns the node that associates this style sheet with the document.
... this is usually an html <link> or <style> element, but can also return a processing instruction node in the case of <?xml-stylesheet ?>.
StyleSheet.parentStyleSheet - Web APIs
the parentstylesheet property of the stylesheet interface returns 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 returns 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 returns a new submitevent object, which is used to represent a submit event fired at an html form.
... return value a submitevent object configured using the given inputs.
SyncEvent - Web APIs
WebAPISyncEvent
syncevent.tag read only returns the developer-defined identifier for this syncevent.
... syncevent.lastchance read only returns 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 returns a list of developer-defined identifiers for syncmanager registrations.
...}) returns 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 returns a promise that resolves to a syncregistration instance.
...}) returns a promise that resolves to an instance of syncregistration.
SyncManager - Web APIs
methods syncmanager.register create a new sync registration and return a promise.
... syncmanager.gettags return a list of developer-defined identifiers for syncmanager registration.
Text.replaceWholeText() - Web APIs
this method returns the text node which received the replacement text, or null if the replacement text is an empty string.
... the returned node is the current node unless the current node is read only, in which case the returned 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
WebAPITextsplitText
the newly created node is returned to the caller.
... return value returns a newly created text node that contains the text after the specified offset point.
TextDecoder - Web APIs
constructor textdecoder() returns a newly constructed textdecoder that will generate a code point stream with the decoding method specified in parameters.
... textdecoder.prototype.decode() returns 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 returns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object.
... return value a uint8array object.
TextTrack - Web APIs
WebAPITextTrack
texttrack.inbandmetadatatrackdispatchtype read only returns a domstring which indicates the track's in-band metadata track dispatch type.
... needs details texttrack.kind read only returns a domstring indicating what kind of text track the texttrack describes.
TextTrackList - Web APIs
gettrackbyid() returns the texttrack found within the texttracklist whose id matches the specified string.
... if no match is found, null is returned.
TimeRanges.end() - Web APIs
WebAPITimeRangesend
returns the time offset at which a specified time range ends.
... syntax endtime = timeranges.end(index) parameters index is the range number to return the ending time for.
TimeRanges.start() - Web APIs
WebAPITimeRangesstart
returns the time offset at which a specified time range begins.
... syntax starttime = timeranges.start(index) parameters index is the range number to return the starting time for.
msManipulationViewsEnabled - Web APIs
the msmanipulationviewsenabled read-only property returns true if manipulation features are support available, such as touch panning and zooming using css rules.
... value returns true if manipulation features are support available, such as touch panning and zooming using css rules.
Touch.clientX - Web APIs
WebAPITouchclientX
the touch.clientx read-only property returns the x coordinate of the touch point relative to the viewport, not including any scroll offset.
... syntax touchitem.clientx; return value a long representing the x coordinate of the touch point relative to the viewport, not including any scroll offset.
Touch.clientY - Web APIs
WebAPITouchclientY
the touch.clienty read-only property returns the y coordinate of the touch point relative to the browser's viewport, not including any scroll offset.
... syntax touchitem.clienty; return 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
WebAPITouchidentifier
the touch.identifier returns a value uniquely identifying this point of contact with the touch surface.
... syntax touchitem.identifier; return value a long that represents the unique id of the touch object.
Touch.pageX - Web APIs
WebAPITouchpageX
the touch.pagex read-only property returns the x coordinate of the touch point relative to the viewport, including any scroll offset.
... syntax touchitem.pagex; return value a long representing the x coordinate of the touch point relative to the viewport, including any scroll offset.
Touch.pageY - Web APIs
WebAPITouchpageY
the touch.pagey read-only property returns the y coordinate of the touch point relative to the viewport, including any scroll offset.
... syntax touchitem.pagey; return 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
WebAPITouchradiusY
summary returns the y radius of the ellipse that most closely circumscribes the area of contact with the touch surface.
... syntax var yradius = touchitem.radiusy; return value yradius the y radius of the ellipse that most closely circumscribes the area of contact with the screen.
Touch.rotationAngle - Web APIs
summary returns the rotation angle, in degrees, of the contact area ellipse defined by touch.radiusx and touch.radiusy.
... syntax var angle = touchitem.rotationangle; return 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
WebAPITouchscreenX
summary returns the x coordinate of the touch point relative to the screen, not including any scroll offset.
... syntax var x = touchitem.screenx; return value x the x coordinate of the touch point relative to the screen, not including any scroll offset.
Touch.screenY - Web APIs
WebAPITouchscreenY
summary returns the y coordinate of the touch point relative to the screen, not including any scroll offset.
... syntax var y = touchitem.screeny; return value y the y coordinate of the touch point relative to the screen, not including any scroll offset.
Touch.target - Web APIs
WebAPITouchtarget
summary returns 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; return value el the target element of the touch object.
TouchList.identifiedTouch() - Web APIs
the identifiedtouch() method returns the first touch item in the touchlist that matches the specified identifier.
... return value touchitem a touch object matching the specified id.
TouchList - Web APIs
WebAPITouchList
methods touchlist.identifiedtouch() returns the first touch item in the list whose identifier matches a specified value.
... touchlist.item() returns the touch object at the specified index in the list.
TrackDefaultList - Web APIs
constructor trackdefaultlist() constructs and returns a new trackdefaultlist object.
... trackdefaultlist.length read only returns the number of trackdefault objects in the list.
TrackEvent() - Web APIs
the trackevent() constructor creates and returns a new trackevent object describing an event which occurred on a list of tracks (audiotracklist, videotracklist, or texttracklist).
... return 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 returns 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) { return 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
WebAPITreeWalkerfilter
the treewalker.filter read-only property returns 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) { return 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
WebAPITreeWalkerroot
the treewalker.root read-only property returns 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) { return 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 returns 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) { return 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
WebAPIUIEventisChar
the uievent.ischar read-only property returns a boolean indicating whether the event produced a key character or not.
...when this is the case, ischar returns false.
sourceCapabilities - Web APIs
the uievent.sourcecapabilities read-only property returns 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 returns null.
URL.origin - Web APIs
WebAPIURLorigin
the origin read-only property of the url interface returns 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 returned as "https://mozilla.org".
URLSearchParams() - Web APIs
the urlsearchparams() constructor creates and returns a new urlsearchparams object.
... return value a urlsearchparams object instance.
URLSearchParams.entries() - Web APIs
the entries() method of the urlsearchparams interface returns an iterator allowing iteration through all key/value pairs contained in this object.
... return value returns an iterator.
URLSearchParams.has() - Web APIs
the has() method of the urlsearchparams interface returns a boolean that indicates whether a parameter with the specified name exists.
... return value a boolean.
URLSearchParams.keys() - Web APIs
the keys() method of the urlsearchparams interface returns an iterator allowing iteration through all keys contained in this object.
... return value returns an iterator.
URLSearchParams.set() - Web APIs
return 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) } return 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 returns undefined.
... return value undefined.
URLSearchParams.values() - Web APIs
the values() method of the urlsearchparams interface returns an iterator allowing iteration through all values contained in this object.
... return value returns an iterator.
URLUtilsReadOnly.host - Web APIs
the urlutilsreadonly.host read-only property returns 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; // returns:'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 returns 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; // returns:'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 returns 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; // returns:'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 returns 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; // returns:'/urlutilsreadonly.pathname' specifications specification status comment urlthe definition of 'urlutilsreadonly.pathname' in that specification.
URLUtilsReadOnly.port - Web APIs
the urlutilsreadonly.port read-only property returns 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; // returns:'80' specifications specification status comment urlthe definition of 'urlutilsreadonly.port' in that specification.
URLUtilsReadOnly.protocol - Web APIs
the urlutilsreadonly.protocol read-only property returns 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; // returns:'https:' specifications specification status comment urlthe definition of 'urlutilsreadonly.protocol' in that specification.
URLUtilsReadOnly.search - Web APIs
the urlutilsreadonly.search read-only property returns 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; // returns:'?t=67' specifications specification status comment urlthe definition of 'urlutilsreadonly.search' in that specification.
URLUtilsReadOnly.toString() - Web APIs
the urlutilsreadonly.tostring() stringifier method returns 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(); // returns:'https://developer.mozilla.org/urlutilsreadonly.href' browser compatibility the compatibility table in this page is generated from structured data.
USB.getDevices() - Web APIs
WebAPIUSBgetDevices
the getdevices method of the usb interface returns a promise that resolves with an array of usbdevice objects for paired attached devices.
... return value a promise that resolves with an array of usbdevice objects.
USB.requestDevice() - Web APIs
WebAPIUSBrequestDevice
the requestdevice() method of the usb interface returns 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 return value a promise that resolves with an instance of usbdevice.
USB - Web APIs
WebAPIUSB
methods usb.getdevices() returns a promise that resolves with an array of usbdevice objects for paired attached devices.
... usb.requestdevice() returns 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 returns a promise that resolves when the requested interface is claimed for exclusive access.
... return value a promise.
USBDevice.clearHalt() - Web APIs
the clearhalt() method of the usbdevice interface returns a promise that resolves when a halt condition is cleared.
... return value a promise.
USBDevice.close() - Web APIs
WebAPIUSBDeviceclose
the close() method of the usbdevice interface returns a promise that resolves when all open interfaces are released and the device session has ended.
... return value a promise.
USBDevice.controlTransferIn() - Web APIs
the controltransferin() method of the usbdevice interface returns a promise that resolves with a usbintransferresult when the result of a command or status request has been received from the usb device.
... return value promise that resolves with a usbintransferresult.
USBDevice.controlTransferOut() - Web APIs
the controltransferout() method of the usbdevice interface returns a promise that resolves with a usbouttransferresult when a command or status operation has been transmitted to the usb device.
... return value a promise that resolves with a usbouttransferresult.
USBDevice.isochronousTransferIn() - Web APIs
the isochronoustransferin() method of the usbdevice interface returns a promise that resolves with a usbisochronousintransferresult when time sensitive information has been transmitted received from the usb device.
... return 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 returns a promise that resolves with a usbisochronousouttransferresult when time sensitive information has been transmitted to the usb device.
... return value a promise that resolves with a usbisochronousouttransferresult.
USBDevice.open() - Web APIs
WebAPIUSBDeviceopen
the open() method of the usbdevice interface returns a promise that resolves when a device session has started.
... return value a promise.
USBDevice.releaseInterface() - Web APIs
the releaseinterface() method of the usbdevice interface returns a promise that resolves when a cliamed interface is released from exclusive access.
... return value a promise.
USBDevice.reset() - Web APIs
WebAPIUSBDevicereset
the reset() method of the usbdevice interface returns a promise that resolves when the device is reset and all app operations canceled and their promises rejected.
... return value a promise.
USBDevice.selectAlternateInterface() - Web APIs
the selectalternateinterface() method of the usbdevice interface returns a promise that resolves when the specified alternative endpoint is selected.
... return value a promise.
USBDevice.selectConfiguration() - Web APIs
the selectconfiguration() method of the usbdevice interface returns a promise that resolves when the specified configuration is selected.
... return value a promise.
USBDevice.transferIn() - Web APIs
the transferin() method of the usbdevice interface returns a promise that resolves with a usbtransferinresult when bulk or interrupt data is received from the usb device.
... return value a promise that resolves with a usbtransferinresult.
USBDevice.transferOut() - Web APIs
the transferout() method of the usbdevice interface returns a promise that resolves with a usbtransferoutresult when bulk or interrupt data is sent to the usb device.
... return value a promise that resolves with a usbtransferoutresult.
USBInTransferResult - Web APIs
properties usbintransferresult.dataread only returns a dataview object containing the data received from the usb device, if any.
... usbintransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful.
USBIsochronousInTransferPacket - Web APIs
properties usbisochronousintransferpacket.dataread only read only returns a dataview object containing the data received from the usb device in this packet, if any.
... usbisochronousintransferpacket.statusread only read only returns the status of the transfer request, one of: "ok" - the transfer was successful.
USBIsochronousInTransferResult - Web APIs
properties usbisochronousintransferresult.dataread only returns a dataview object containing the data received from the device.
... usbisochronousintransferresult.packetsread only returns 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 returns the number of bytes from the packet that were sent to the device.
... usbisochronousouttransferpacket.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful.
USBOutTransferResult - Web APIs
properties usbouttransferresult.byteswrittenread only returns the number of bytes from the transfer request that were sent to the device.
... usbouttransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful.
VRStageParameters - Web APIs
vrstageparameters.sizex read only returns the width of the play-area bounds in meters.
... vrstageparameters.sizey read only returns the depth of the play-area bounds in meters.
VTTCue() - Web APIs
WebAPIVTTCueVTTCue
the vttcue() constructor creates and returns a new vttcue object.
... return value a new vttcue object representing a cue which will be presented during the time span given.
VideoTrack - Web APIs
returns 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 returns 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() returns the videotrack found within the videotracklist whose id matches the specified string.
... if no match is found, null is returned.
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
the webgl_compressed_texture_astc.getsupportedprofiles() method returns an array of strings containing the names of the astc profiles supported by the implementation.
... syntax sequence<domstring> ext.getsupportedprofiles(); return value an array of domstring elements indicating which astc profiles are supported by the implementation.
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
return value a string containing the translated shader source.
... an empty string is returned, 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
WebAPIWakeLockrequest
the request() method of the wakelock interface returns a promise that resolves with a wakelocksentinel object, which allows control over screen dimming and locking.
... return value a promise that resolves with a wakelocksentinel object.
WakeLockSentinel.release() - Web APIs
the release() method of the wakelocksentinel interface releases the wakelocksentinel, returning a promise that is resolved once the sentinel has been successfully released.
... return value returns a promise that resolves with undefined exceptions no exceptions are thrown.
WakeLockSentinel.type - Web APIs
the read-only type property of the wakelocksentinel interface returns a string representation of the currently acquired wakelocksentinel type.
... type read only return values are: 'screen': a screen wake lock.
WebGL2RenderingContext.getBufferSubData() - Web APIs
return value none.
... exceptions an invalid_value error is generated if: offset + returneddata.bytelength would extend beyond the end of the buffer returneddata is null offset is less than zero.
WebGL2RenderingContext.getFragDataLocation() - Web APIs
the webgl2renderingcontext.getfragdatalocation() method of the webgl 2 api returns the binding of color numbers to user-defined varying out variables.
... return value a glint indicating the assigned color number binding, or -1 otherwise.
WebGL2RenderingContext.getQuery() - Web APIs
the webgl2renderingcontext.getquery() method of the webgl 2 api returns the currently active webglquery for the target, or null.
... return value a webglquery object.
WebGL2RenderingContext.getTransformFeedbackVarying() - Web APIs
the webgl2renderingcontext.gettransformfeedbackvarying() method of the webgl 2 api returns information about varying variables from webgltransformfeedback buffers.
... return value a webglactiveinfo object.
WebGL2RenderingContext.isQuery() - Web APIs
the webgl2renderingcontext.isquery() method of the webgl 2 api returns true if the passed object is a valid webglquery object.
... return 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 returns true if the passed object is a valid webglsampler object.
... return 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 returns true if the passed object is a valid webglsync object.
... return 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 returns true if the passed object is a valid webgltransformfeedback object.
... return 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 returns true if the passed object is a valid webglvertexarrayobject object.
... return value a glboolean indicating whether the given object is a valid webglvertexarrayobject object (true) or not (false).
WebGL2RenderingContext.renderbufferStorageMultisample() - Web APIs
the webgl2renderingcontext.renderbufferstoragemultisample() method of the webgl 2 api returns creates and initializes a renderbuffer object's data store and allows specifying a number of samples to be used.
... return value none.
WebGL2RenderingContext.waitSync() - Web APIs
the webgl2renderingcontext.waitsync() method of the webgl 2 api returns immediately, but waits on the gl server until the given webglsync object is signaled.
... return value none.
WebGLActiveInfo - Web APIs
the webglactiveinfo interface is part of the webgl api and represents the information returned by calling the webglrenderingcontext.getactiveattrib() and webglrenderingcontext.getactiveuniform() methods.
... examples a webglactiveinfo object is returned by: webglrenderingcontext.getactiveattrib() webglrenderingcontext.getactiveuniform() or webgl2renderingcontext.gettransformfeedbackvarying() webglactiveinfo?
WebGLRenderingContext.activeTexture() - Web APIs
return value none.
... gl.activetexture(gl.texture0); gl.getparameter(gl.active_texture); // returns "33984" (0x84c0, gl.texture0 enum value) specifications specification status comment webgl 1.0the definition of 'activetexture' in that specification.
WebGLRenderingContext.blendColor() - Web APIs
return value none.
... examples to set the blend color, use: gl.blendcolor(0, 0.5, 1, 1); to get the blend color, query the blend_color constant which returns a float32array.
WebGLRenderingContext.blendEquation() - Web APIs
return 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 return 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
return 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 return 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
return 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 return one of the blend function constants.
WebGLRenderingContext.blendFuncSeparate() - Web APIs
return 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 return one of the blend function constants.
WebGLRenderingContext.clearColor() - Web APIs
return value none.
... examples gl.clearcolor(1, 0.5, 0.5, 3); to get the current clear color, query the color_clear_value constant which returns a float32array.
WebGLRenderingContext.colorMask() - Web APIs
return value none.
... examples gl.colormask(true, true, true, false); to get the current color mask, query the color_writemask constant which returns an array.
WebGLRenderingContext.depthMask() - Web APIs
return value none.
... examples gl.depthmask(false); to get the current depth mask, query the depth_writemask constant which returns a boolean.
WebGLRenderingContext.depthRange() - Web APIs
return value none.
... examples gl.depthrange(0.2, 0.6); to check the current depth range, query the depth_range constant which returns 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.disableVertexAttribArray() - Web APIs
the webglrenderingcontext.disablevertexattribarray() method of the webgl api turns the generic vertex attribute array off at a given index position.
... return value none.
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
the webglrenderingcontext method enablevertexattribarray(), part of the webgl api, turns on the generic vertex attribute array at the specified index into the list of attribute arrays.
... return value undefined.
WebGLRenderingContext.getAttachedShaders() - Web APIs
the webglrenderingcontext.getattachedshaders() method of the webgl api returns a list of webglshader objects attached to a webglprogram.
... return value an array of webglshader objects that are attached to the given webglprogram.
WebGLRenderingContext.getProgramInfoLog() - Web APIs
the webglrenderingcontext.getprograminfolog returns the information log for the specified webglprogram object.
... return 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 returns the information log for the specified webglshader object.
... return 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 returns a new webglshaderprecisionformat object describing the range and precision for the specified shader numeric format.
... return value a webglshaderprecisionformat object or null, if an error occurs.
WebGLRenderingContext.getShaderSource() - Web APIs
the webglrenderingcontext.getshadersource() method of the webgl api returns the source code of a webglshader as a domstring.
... return value a domstring containing the source code of the shader.
WebGLRenderingContext.getSupportedExtensions() - Web APIs
the webglrenderingcontext.getsupportedextensions() method returns a list of all the supported webgl extensions.
... syntax gl.getsupportedextensions(); return value an array of strings with all the supported webgl extensions.
WebGLRenderingContext.getUniform() - Web APIs
the webglrenderingcontext.getuniform() method of the webgl api returns the value of a uniform variable at a given location.
... return value the returned type depends on the uniform type: uniform type returned 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.getVertexAttribOffset() - Web APIs
the webglrenderingcontext.getvertexattriboffset() method of the webgl api returns the address of a specified vertex attribute.
... return value a glintptr indicating the address of the vertex attribute.
WebGLRenderingContext.isBuffer() - Web APIs
the webglrenderingcontext.isbuffer() method of the webgl api returns true if the passed webglbuffer is valid and false otherwise.
... return value a glboolean indicating whether or not the buffer is valid.
WebGLRenderingContext.isContextLost() - Web APIs
the webglrenderingcontext.iscontextlost() method returns 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(); return 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 returns true if the passed webglframebuffer is valid and false otherwise.
... return value a glboolean indicating whether or not the frame buffer is valid.
WebGLRenderingContext.isProgram() - Web APIs
the webglrenderingcontext.isprogram() method of the webgl api returns true if the passed webglprogram is valid, false otherwise.
... return value a glboolean indicating whether or not the program is valid.
WebGLRenderingContext.isRenderbuffer() - Web APIs
the webglrenderingcontext.isrenderbuffer() method of the webgl api returns true if the passed webglrenderbuffer is valid and false otherwise.
... return value a glboolean indicating whether or not the renderbuffer is valid.
WebGLRenderingContext.isShader() - Web APIs
the webglrenderingcontext.isshader() method of the webgl api returns true if the passed webglshader is valid, false otherwise.
... return value a glboolean indicating whether or not the shader is valid.
WebGLRenderingContext.isTexture() - Web APIs
the webglrenderingcontext.istexture() method of the webgl api returns true if the passed webgltexture is valid and false otherwise.
... return value a glboolean indicating whether or not the texture is valid.
WebGLRenderingContext.lineWidth() - Web APIs
return value none.
...returns a float32array.
WebGLRenderingContext.viewport() - Web APIs
return value none.
...to get this range, you can use the max_viewport_dims constant, which returns an int32array.
WebGLShaderPrecisionFormat - Web APIs
the webglshaderprecisionformat interface is part of the webgl api and represents the information returned by calling the webglrenderingcontext.getshaderprecisionformat() method.
... examples a webglshaderprecisionformat object is returned 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."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function.
... function getrandomcolor() { return [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."; return; } 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() { return [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."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function.
... function getrandomcolor() { return [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 return an extension object with constants for the added formats and the formats will also be returned 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 return texture; } } ...
Getting started with WebGL - Web APIs
your browser or machine may not support it."); return; } // 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 return null in which case we display a message to the user and exit.
Taking still photos with WebRTC - Web APIs
it returns 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 returned 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 returns.
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() returns an input stream for this socket.
... java.net.socket getoutputstream() returns an output stream for this socket.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
the returned 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 return 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 returns 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)); return 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 returned through the webauthn api as the authenticatorattestationresponse.
... the assertion is returned 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 return null.
Window.back() - Web APIs
WebAPIWindowback
the obsolete and non-standard method back() on the window interface returns the window to the previous item in the history.
... return value undefined.
window.cancelIdleCallback() - Web APIs
syntax window.cancelidlecallback(handle); parameters handle the id value returned by window.requestidlecallback() when the callback was established.
... return value undefined.
Window.confirm() - Web APIs
WebAPIWindowconfirm
return value a boolean indicating whether ok (true) or cancel (false) was selected.
... if a browser is ignoring in-page dialogs, then the returned value is always false.
Window.content - Web APIs
WebAPIWindowcontent
returns a window object for the primary content window.
...in such cases, content returns 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() returns a point which specifies the same position in the page's coordinate system.
... return 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() returns a point object specifying the same location in the coordinate system of the specified dom node.
... return value a point object describing the specified location in the node's coordinate system.
Window.crypto - Web APIs
WebAPIWindowcrypto
the read-only window.crypto property returns the crypto object associated to the global object.
... although window.crypto is available on all windows, the returned crypto object only has one usable feature in insecure contexts: the getrandomvalues() method.
Window.devicePixelRatio - Web APIs
the devicepixelratio of window interface returns the ratio of the resolution in physical pixels to the resolution in css pixels for the current display device.
...other values may be returned 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
WebAPIWindowevent
the read-only window property event returns 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 returned event is not the expected value.
Window.frames - Web APIs
WebAPIWindowframes
returns the window itself, which is an array-like object, listing the direct sub-frames of the current window.
... for more details about the returned value, refer to this thread on mozilla.dev.platform.
Window.innerHeight - Web APIs
the read-only innerheight property of the window interface returns 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 return the height of the frame viewport within the frameset var intframesetheight = parent.innerheight; // will return the height of the viewport of the closest frameset var intouterframesetheight = top.innerheight; // will return 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
WebAPIWindownavigator
the window.navigator read-only property returns 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 return 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 return 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 returns 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 returns 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 returned by performance.now(), indicating the point in time when requestanimationframe() starts to execute callback functions.
... return value a long integer value, the request id, that uniquely identifies the entry in the callback list.
Window.requestFileSystem() - Web APIs
the returned filesystem is then available for use with the other file system apis.
... return 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
WebAPIWindowscreenLeft
the window.screenleft read-only property returns 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 returns 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
WebAPIWindowscreenTop
the window.screentop read-only property returns 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 returns 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
WebAPIWindowscreenX
the window.screenx read-only property returns 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 returns 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
WebAPIWindowscreenY
the window.screeny read-only property returns 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 returns 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
WebAPIWindowsidebar
returns a sidebar object which contains several methods for registering add-ons with the browser.
... methods the sidebar object returned has the following methods: method description (seamonkey) description (firefox) addpanel(title, contenturl, "") adds a sidebar panel.
Window.top - Web APIs
WebAPIWindowtop
returns a reference to the topmost window in the window hierarchy.
... syntax var topwindow = window.top; notes where the window.parent property returns the immediate parent of the current window, window.top returns 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 returns a promise that resolves to the existing windowclient.
... return value a promise that resolves to the existing windowclient.
WindowOrWorkerGlobalScope.caches - Web APIs
the caches read-only property of the windoworworkerglobalscope interface returns the cachestorage object associated with the current context.
... this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); }); specificat...
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
this id was returned by the corresponding call to setinterval().
... return value undefined example see the setinterval() examples.
self.createImageBitmap() - Web APIs
it accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap.
... return 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 returns the origin of the global scope, serialized as a string.
...via file:// url), origin will return the string "null".
WorkerGlobalScope.console - Web APIs
the console read-only property of the workerglobalscope interface returns 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 return a test message out to the browser console.
WorkerGlobalScope.navigator - Web APIs
the navigator read-only property of the workerglobalscope interface returns 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 return more information about the runtime envinronment, as you might do with a normal navigator object.
Worklet.addModule() - Web APIs
WebAPIWorkletaddModule
return value a promise that resolves once the module from the given url has been added.
... the promise doesn't return any value.
WritableStream.locked - Web APIs
the locked read-only property of the writablestream interface returns a boolean indicating whether the writablestream is locked to a writer.
... const writer = writablestream.getwriter(); writablestream.locked // should return true, as the stream has been locked to a writer specifications specification status comment streamsthe definition of 'locked' in that specification.
WritableStreamDefaultController.error() - Web APIs
this method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink’s methods.
... return value undefined.
WritableStreamDefaultWriter.abort() - Web APIs
if not, it returns a rejected promise.
... return value a promise, which fulfills with the value given in the reason parameter.
WritableStreamDefaultWriter.desiredSize - Web APIs
the desiredsize read-only property of the writablestreamdefaultwriter interface returns the desired size required to fill the stream's internal queue.
... // return 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, returning 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) return ''; return 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 returns the serialized url of the response or the empty string if the url is null.
... if the url is returned, any url fragment present in the url will be stripped away.
XMLSerializer - Web APIs
methods serializetostring() returns 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 returns the xml equivalent of the document.
XPathException - Web APIs
properties xpathexception.code read only returns a short that contains one of the error code constants.
... type_err 52 if the expression cannot be converted to return the specified type.
XPathResult.booleanValue - Web APIs
the read-only booleanvalue property of the xpathresult interface returns the boolean value of a result with xpathresult.resulttype being boolean_type.
... syntax var value = result.booleanvalue; return value the return value is the boolean value of the xpathresult returned 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 returned.
... syntax var iteratorstate = result.invaliditeratorstate; return value a boolean value indicating whether the iterator has become invalid.
XPathResult.numberValue - Web APIs
the read-only numbervalue property of the xpathresult interface returns the numeric value of a result with xpathresult.resulttype being number_type.
... syntax var value = result.numbervalue; return value the return value is the numeric value of the xpathresult returned by document.evaluate().
XPathResult.singleNodeValue - Web APIs
the read-only singlenodevalue property of the xpathresult interface returns 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; return value the return value is the node value of the xpathresult returned by document.evaluate().
XPathResult.snapshotItem() - Web APIs
the snapshotitem() method of the xpathresult interface returns 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); return 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 returns the string value of a result with xpathresult.resulttype being string_type.
... syntax var value = result.stringvalue; return value the return value is the string value of the xpathresult returned by document.evaluate().
XRFrame.getPose() - Web APIs
WebAPIXRFramegetPose
the xrframe method getpose() returns the relative position and orientation—the pose—of one xrspace to that of another space.
... return 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, returns a xrviewerpose object which describes the viewer's pose (position and orientation) relative to the specified reference space.
... return value a xrviewerpose describing the viewer's position and orientation relative to the specified reference space.
XRFrame - Web APIs
WebAPIXRFrame
methods getpose() returns an xrpose object representing the spatial relationship between the two specified xrspace objects.
... getviewerpose() returns 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 returned xrframe.
... return value none.
XRInputSource.gripSpace - Web APIs
the read-only xrinputsource property gripspace returns 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 returned, 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 returns a javascript iterator which can then be used to iterate over the key/value pairs in the input source array.
... return 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 returns a new xrinputsourceevent object describing an event (state change) which has occurred on a webxr user input device represented by an xrinputsource.
... return value a new xrinputsourceevent object representing the event described by the given type and eventinitdict.
XRInputSourcesChangeEvent() - Web APIs
the xrinputsourceschangeevent() constructor creates and returns a new xrinputsourceschangeevent object, representing an update to the list of available webxr input devices.
... return value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided.
XRPermissionDescriptor - Web APIs
when the returned promise resolves, we check the returned status.
...and for any other returned 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 returns 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 */ return; } 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 returned by the call to requestanimationframe() that previously scheduled the animation callback.
... return value none.
XRSession.end() - Web APIs
WebAPIXRSessionend
the end() method shuts down the xrsession on which it's called, returning a promise which resolves once the session has fully shut down.
... return 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 returns an xrinputsourcearray object which lists all controllers and input devices which are expressly associated with the xr device and are currently available.
...the returned 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() returns 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") { return; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { return; } 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() returns 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") { return; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { return; } 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() returns 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") { return; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { return; } 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() returns 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") { return; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { return; } switch(event.type) { case "squeezestart": targetobj = mybegintracking(targetraypose.matrix); break; case "squeeze": mydropobject(targetobj, targetraypose.matrix); break; case "squeezeend": mystoptracking(targetobj, targetraypose.m...
XRSession.updateRenderState() - Web APIs
return value none.
...these are true exceptions, since this method does not return a promise.
XRSessionEvent() - Web APIs
the webxr device api's xrsessionevent() constructor creates and returns a new xrsessionevent object.
... return 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 returned xrsession may optionally support.
... requiredfeatures optional an array of values which the returned xrsession must support.
msGetPropertyEnabled - Web APIs
the msgetpropertyenabled returns whether a given property in the style object is enabled.
... return value type: boolean if false, the property is not enabled.
msGetRegionContent - Web APIs
the msgetregioncontent returns an array of range instances corresponding to the content from the region flow that is positioned in the region.
... return value type: boolean returned ranges are sorted by document position and do not overlap.
msPutPropertyEnabled - Web APIs
return value type = hresult: if this method succeeds, it returns s_ok.
... otherwise, it returns an hresult error code.
Alerts - Accessibility
a value of -1 or less is returned if the index of the search term could not be found within the value.
... in both cases, when returning 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.
Web Accessibility: Understanding Colors and Luminance - Accessibility
window.getcomputedstyle() returns values using rgb decimal reference scale.
... for example, calling window.getcomputedstyle() on a div with a background-color: #990000; set returns the computed background color as rgb(153, 0, 0) -- the rgb decimal reference.
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 return light (value: 0), dark (value: 1), or no-preference (value: 2).
... (any other value causes firefox to return 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).
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
for many use cases, turning the block container into a flex item will give you the alignment capability that you are looking for.
... in the example below, a container with a single item inside has been turned into a flex container for the purpose of being able to use the alignment properties.
Using feature queries - CSS: Cascading Style Sheets
the following rule will only return 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 returns a positive response.
CSS Containment - CSS: Cascading Style Sheets
if you turn on contain: size you need to also specify the size of the element you have applied this to.
...using contain: content turns on layout and paint containment.
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 return to our example with items positioned by line number, we can change this to make two items overlap.
CSS values and units - CSS: Cascading Style Sheets
turn turns there is 1 turn in a full circle.
...allows alpha values in rgb() and hsl(), turning rgba() and hsla() into (deprecated) aliases for them.
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 returns the resolved value, which may either be the computed value or the used value, depending on the property.
counter() - CSS: Cascading Style Sheets
WebCSScounter
the counter() css function returns 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 returning developer defined strings (or images).
counters() - CSS: Cascading Style Sheets
WebCSScounters
the counters() css function enables nested counters, returning 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 returning 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
WebCSSdisplay
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.25turn).
... formal definition initial value0degapplies toall elementsinheritedyescomputed valuean <angle>, rounded to the next quarter turn from 0deg and normalized, that is moduloing the value by 1turnanimation typediscrete formal syntax from-image | <angle> | [ <angle>?
Guide to scroll anchoring - CSS: Cascading Style Sheets
how do i turn on scroll anchoring?
...for example, if you opt out for the entire document, you will not be able to set overflow-anchor: auto elsewhere in the document to turn it back on for a subsection.
repeating-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.
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
WebEXSLTexsl
exsl:node-set()exsl:node-set() returns a node-set from a result tree fragment, which is what you get when you look at the xsl:variable instead of its select attribute to fetch a variable's value.
... this lets you process the xml created within a variable to process it in multiple steps.exsl:object-type()exsl:object-type() returns a string that indicates the type of the specified object.
set:distinct() - EXSLT
WebEXSLTsetdistinct
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:distinct() returns a subset of the nodes in the specified node-set, returning only nodes with unique string values.
... returns 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() { return !!(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 returns a timeranges object listing the ranges of times that you can seek to.
... var mediaelement = document.queryselector('#mediaelementid'); mediaelement.seekable.start(0); // returns the starting time (in seconds) mediaelement.seekable.end(0); // returns the ending time (in seconds) mediaelement.currenttime = 122; // seek to 122 seconds mediaelement.played.end(0); // returns 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) { return; } 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); return; } }; 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
WebGuideHTMLHTML5HTML5 Parser
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
WebGuideHTMLHTML5
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 returned 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%);">&nbsp;</td> </tr> <tr> <td><code>hsl(90, 100%, 50%)</code></td> <td style="background-color: hsl(90, 100%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 50%, 75%)</code></td> <td style="background-color: hsl(0.15turn, 50%, 75%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 90%, 75%)</code></td> <td style="background-color: hsl(0.15turn, 90%, 75%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 90%, 50%)</code></td> <td style="background-color: hsl(0.15turn, 90%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(270deg...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
currenttime reading currenttime returns a double-precision floating-point value indicating the current playback position, in seconds, of the audio.
...if no media is present on the element, or the media is not valid, the returned value is nan.
<dialog>: The Dialog element - HTML: Hypertext Markup Language
WebHTMLElementdialog
when such a form is submitted, the dialog closes with its returnvalue 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.returnvalue + " 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
WebHTMLElementinputemail
the text must not include carriage returns 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
WebHTMLElementinputimage
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 returned 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 returns information about places nearby.
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
the text must not include carriage returns 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
WebHTMLElementselect
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 return 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
WebHTMLElement
<br> the html <br> element produces a line break in text (carriage-return).
... <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) { return (""+str).split(camelcaseexpression); }; } else { /*this fallback code is much less performant, but works*/ var splitupstring = function(str){ return 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) { return (""+str).split(new regexp("(?<=[a-z])")); } : function(str) { return 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 return 206: partial content to all byte range requests; otherwise, browsers can't be sure you actually support byte range requests.
... your server must also return 206: partial content for the request range: bytes=0- as well.
Feature Policy - HTTP
some approaches include: return "permission denied" for javascript apis that require user permission grants.
... return 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 return the origin for the specific client making the request.
... note: null should not be used: "it may seem safe to return 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
WebHTTPHeadersIf-Match
if it doesn't match, then a 416 (range not satisfiable) response is returned.
...if the request cannot be fulfilled, the 412 (precondition failed) response is returned.
HTTP headers - HTTP
WebHTTPHeaders
content-location indicates an alternate location for the returned data.
... range indicates the part of a document that the server should return.
A typical HTTP session - HTTP
WebHTTPSession
a client request consists of text directives, separated by crlf (carriage return, 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 returns a response.
204 No Content - HTTP
WebHTTPStatus204
the common use case is to return 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 returned instead.
Introduction - JavaScript
variables, parameters, and function return 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 returned.
Groups and ranges - JavaScript
string.match() won't return groups if the /.../g flag is set.
... (?<name>x) named capturing group: matches "x" and stores it on the groups property of the returned matches under the name specified by <name>.
extends - JavaScript
this.name = 'square'; } get area() { return 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']; return 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) { // return 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) { return 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) { return 'the function was called from the top!'; } else { return '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('returned: ' + 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!'); return 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!'); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { return 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 return 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, returns 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', 'return x + y;'); // syntaxerror (missing a comma) var f = function('x,', 'return x;'); // syntaxerror (extraneous comma) var f = function(37, "alert('ok')"); // syntaxerror (numbers can't be argument names) valid cases var f = function('x, y', 'return x + y;'); // correctly punctuated var f = function('x', 'return x;'); // if you can, avoid using function - this is much faster var f = function(x...
...) { return x; }; ...
SyntaxError: missing } after function body - JavaScript
(function() { if (true) { return false; } ); oftentimes, indenting differently or double checking indentation helps to spot these errors.
... (function() { if (true) { return false; } }); ...
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 returning 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: return new promise.resolve(true); instead, use the promise.resolve() or promise.reject() static methods: // this is legal, but unnecessarily long: return new promise((resolve, reject) => { resolve(true); }) // instead, return the static method: return promise.resolve(true); return 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; return num1 + num2; } console.log(num1); // referenceerror num1 is not defined.
... var num1 = 2, num2 = 3; function numbers() { return 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 returned in that case.
... var name_list2 = array.prototype.reduce.call(names, (acc, name) => { if (acc == "") // initial value return name; return 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'; return 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) { return 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'; return a + b; }; this can be converted to the following expression: var sum = (function() { 'use strict'; return function sum([a, b]) { return 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'; return this.run(args); }; this can be converted to the following expression: var callback = (() => { 'use strict'; return (...args) => { return 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)){ return lowerbound; }else{ return 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)){ return lowerbound; }else{ return upperbound; } } ...
JavaScript error reference - JavaScript
operatorsyntaxerror: missing variable namesyntaxerror: missing } after function bodysyntaxerror: missing } after property listsyntaxerror: redeclaration of formal parameter "x"syntaxerror: return 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 return 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() { return this.a } }; console.log(obj.b()) // "foo" computed property names the shorthand syntax also supports computed property names.
... const bar = { foo0: function() { return 0 }, foo1() { return 1 }, ['foo' + 2]() { return 2 } } console.log(bar.foo0()) // 0 console.log(bar.foo1()) // 1 console.log(bar.foo2()) // 2 // a global function function foo() { return 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 returns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax array.entries() return value a new array iterator object.
Array.prototype.keys() - JavaScript
the keys() method returns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() return value a new array iterator object.
Array.of() - JavaScript
return value a new array instance.
... if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return 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 returns the new length of the array.
... return 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 returns the new length of the array.
... return value the new length property of the object upon which the method was called.
Array.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() return value a new array iterator object.
ArrayBuffer.prototype.slice() - JavaScript
the slice() method returns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin, inclusive, up to end, exclusive.
... return value a new arraybuffer object.
Atomics.isLockFree() - JavaScript
it returns true, if the given size is one of the bytes_per_element property of integer typedarray types.
... return value a boolean indicating whether the operation is lock free.
Atomics.load() - JavaScript
the static atomics.load() method returns a value at a given position in the array.
... return 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 returns that value.
... return value the value that has been stored.
BigInt.prototype.valueOf() - JavaScript
the valueof() method returns the wrapped primitive value of a bigint object.
... syntax bigintobj.valueof() return value a bigint representing the primitive value of the specified bigint object.
Boolean.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a boolean object.
... syntax bool.valueof() return value the primitive value of the given boolean object description the valueof() method of boolean returns the primitive value of a boolean object or literal boolean as a boolean data type.
Boolean - JavaScript
instance methods boolean.prototype.tostring() returns a string of either true or false depending upon the value of the object.
... boolean.prototype.valueof() returns the primitive value of the boolean object.
DataView() constructor - JavaScript
return value a new dataview object representing the specified data buffer.
... (that probably wasn't a very helpful description.) you can think of the returned 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 returned 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() returns 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 returns the day of the month for the specified date according to local time.
... syntax dateobj.getdate() return 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 returns the day of the week for the specified date according to local time, where 0 represents sunday.
... syntax dateobj.getday() return 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 returns the hour for the specified date, according to local time.
... syntax dateobj.gethours() return 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 returns the milliseconds in the specified date according to local time.
... syntax dateobj.getmilliseconds() return 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 returns the minutes in the specified date according to local time.
... syntax dateobj.getminutes() return 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 returns 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() return 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 returns the seconds in the specified date according to local time.
... syntax dateobj.getseconds() return 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 returns the number of milliseconds* since the unix epoch.
... syntax dateobj.gettime() return 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 returns the day (date) of the month in the specified date according to universal time.
... syntax dateobj.getutcdate() return 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 returns the day of the week in the specified date according to universal time, where 0 represents sunday.
... syntax dateobj.getutcday() return 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 returns the hours in the specified date according to universal time.
... syntax dateobj.getutchours() return 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 returns the milliseconds portion of the time object's value.
... syntax dateobj.getutcmilliseconds() return value an integer number, between 0 and 999, representing the milliseconds portion of the given date object.
Date.prototype.getUTCMinutes() - JavaScript
the getutcminutes() method returns the minutes in the specified date according to universal time.
... syntax dateobj.getutcminutes() return 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() returns 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() return 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 returns the seconds in the specified date according to universal time.
... syntax dateobj.getutcseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to universal time.
Date.prototype.setMinutes() - JavaScript
return 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 returned from getseconds() and getmilliseconds() methods are used.
Date.prototype.setSeconds() - JavaScript
return 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 returned from the getmilliseconds() method is used.
Date.prototype.setUTCFullYear() - JavaScript
return 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 returned from the getutcmonth() and getutcdate() methods are used.
Date.prototype.setUTCMinutes() - JavaScript
return 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 returned from getutcseconds() and getutcmilliseconds() methods are used.
Date.prototype.setUTCMonth() - JavaScript
return 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 returned from the getutcdate() method is used.
Date.prototype.setUTCSeconds() - JavaScript
return 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 returned from the getutcmilliseconds() method is used.
Error - JavaScript
instance methods error.prototype.tostring() returns 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); } return 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 returned.
... 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('returned: ' + g.arguments) // output // before: 1 // before: 0 // after: 0 // after: 1 // returned: null specifications not part of any standard.
Function.displayName - JavaScript
the function.displayname property returns 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 returns 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 returns a new object with properties reflecting the locale and collation options computed during initialization of this collator object.
... syntax collator.resolvedoptions() return 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() returns 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() returns 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 returns 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); // return 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 returns a string based on the locale and options provided when instantiating intl.displaynames.
... return value a language-specific formatted string.
Intl​.ListFormat.prototype​.format() - JavaScript
the format() method returns a string with a language-specific representation of the list.
... syntax listformat.format([list]); parameters list an iterable object, such as an array return value a language-specific formatted string representing the elements of the list description the format() method returns 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 returns the type of calendar used in the locale.
... description the calendar property returns 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 returns the language associated with the locale.
...the language property of a locale returns strictly the locale's language subtag.
Intl.Locale.prototype.maximize() - JavaScript
syntax locale.maximize() return value a locale instance whose basename property returns the result of the add likely subtags algorithm executed against locale.basename.
...for instance, given the language id "en", the algorithm would return "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 returns a new object with properties reflecting the locale and number formatting options computed during initialization of this numberformat object.
... syntax numberformat.resolvedoptions() return 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 returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this pluralrules object.
... syntax pluralrule.resolvedoptions() return 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 returns a string indicating which plural rule to use for locale-aware formatting.
... return 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 returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this relativetimeformat object.
... syntax relativetimeformat.resolvedoptions() return 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 returns an array containing the canonical locale names.
... return value an array containing the canonical locale names.
Map.prototype.entries() - JavaScript
the entries() method returns a new iterator object that contains the [key, value] pairs for each element in the map object in insertion order.
... syntax mymap.entries() return value a new map iterator object.
Map.prototype.forEach() - JavaScript
return value undefined.
...it does not return a value.
Map.prototype.keys() - JavaScript
the keys() method returns a new iterator object that contains the keys for each element in the map object in insertion order.
... syntax mymap.keys() return value a new map iterator object.
Map.prototype.set() - JavaScript
return 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 returns 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 returns a new iterator object that contains the values for each element in the map object in insertion order.
... syntax mymap.values() return value a new map iterator object.
Math.exp() - JavaScript
the math.exp() function returns ex, where x is the argument, and e is euler's number (also known as napier's constant), the base of the natural logarithms.
... return value a number representing ex, where e is euler's number and x is the argument.
Math.round() - JavaScript
the math.round() function returns the value of a number rounded to the nearest integer.
... return value the value of the given number rounded to the nearest integer.
NaN - JavaScript
there are five different types of operations that return 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) { return 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 return 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 return 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 returns a finite number in case of success.
... var smallnumber = (-number.max_value) * 2; if (smallnumber === number.negative_infinity) { smallnumber = returnfinite(); } 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 returns a finite number in case of success.
... var bignumber = number.max_value * 2; if (bignumber == number.positive_infinity) { bignumber = returnfinite(); } specifications specification ecmascript (ecma-262)the definition of 'number.positive_infinity' in that specification.
Number.isSafeInteger() - JavaScript
return 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) { return 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 returns a string representing the number object in exponential notation.
... return 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 returns the wrapped primitive value of a number object.
... syntax numobj.valueof() return value a number representing the primitive value of the specified number object.
Object.prototype.__defineGetter__() - JavaScript
return value undefined.
... examples non-standard and deprecated way var o = {}; o.__definegetter__('gimmefive', function() { return 5; }); console.log(o.gimmefive); // 5 standard-compliant ways // using the get operator var o = { get gimmefive() { return 5; } }; console.log(o.gimmefive); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'gimmefive', { get: function() { return 5; } }); console.log(o.gimmefive); // 5 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__definegetter__()' in that specification.
Object.getOwnPropertyDescriptors() - JavaScript
the object.getownpropertydescriptors() method returns all own property descriptors of a given object.
... return value an object containing all own property descriptors of an object.
Object.is() - JavaScript
return 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 return x !== 0 || 1 / x === 1 / y; } else { // step 6.a: nan == nan return 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
return 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 return false.
handler.apply() - JavaScript
return value the apply() method can return any value.
... const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { console.log('called: ' + argumentslist.join(', ')); return 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
return value the deleteproperty() method must return 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) return true } else { console.log('property not found: ' + prop) return 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 returns 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") { return "replaced value"; } return 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
return value a newly created revocable proxy object is returned.
... examples using proxy.revocable var revocable = proxy.revocable({}, { get: function(target, name) { return "[[" + 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
return 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) { return 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) { return 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
return 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 // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has returns 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 returns 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() { return 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); returns ["hi", "hi"] with lastindex equal to 2.
... console.log(re.exec('hi')); console.log(re.lastindex); returns ["", undefined], an empty array whose zeroth element is the match string.
Set.prototype.forEach() - JavaScript
return value undefined.
... foreach() executes the callback function once for each element in the set object; it does not return a value.
SharedArrayBuffer.prototype.slice() - JavaScript
the sharedarraybuffer.prototype.slice() method returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive.
... return value a new sharedarraybuffer containing the extracted elements.
String.prototype[@@iterator]() - JavaScript
the [@@iterator]() method returns a new iterator object that iterates over the code points of a string value, returning each code point as a string value.
... syntax str[symbol.iterator] return value a new iterator object.
String.prototype.matchAll() - JavaScript
the matchall() method returns an iterator of all results matching a string against a regular expression, including capturing groups.
... return value an iterator (which is not a restartable iterable).
String.prototype.normalize() - JavaScript
the normalize() method returns the unicode normalization form of the string.
... return 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 returned as-is.
... return 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(); return value a new string representing the calling string stripped of whitespace from its (right) end.
... description the trimend() / trimright() methods return the string stripped of whitespace from its right end.
Symbol.prototype[@@toPrimitive] - JavaScript
syntax symbol()[symbol.toprimitive](hint) return value the primitive value of the specified symbol object.
... description the [@@toprimitive]() method of symbol returns 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 returned 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 return an iterator object, then it is a non-well-formed iterable.
Symbol.matchAll - JavaScript
the symbol.matchall well-known symbol returns an iterator, that yields matches of the regular expression against a string.
...the following two examples return 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 returns 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) { return 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]() { return '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(); // returns [object htmlbuttonelement] test[symbol.tostringtag]; // returns htmlbuttonelement specifications specification ecmascript (ecma-262)the definition of 'symbol.tostringtag' in that specification.
TypedArray.prototype.entries() - JavaScript
the entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax arr.entries() return value a new array iterator object.
TypedArray.prototype.forEach() - JavaScript
return value undefined.
... foreach() executes the callback function once for each typed array element; unlike every() and some() it, always returns the value undefined.
TypedArray.prototype.includes() - JavaScript
the includes() method determines whether a typed array includes a certain element, returning true or false as appropriate.
... return value a boolean.
TypedArray.prototype.keys() - JavaScript
the keys() method returns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() return value a new array iterator object.
TypedArray.prototype.map() - JavaScript
return value a new typed array.
... const numbers = new uint8array([1, 4, 9]); const doubles = numbers.map(function(num) { return 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.sort() - JavaScript
the sort() method sorts the elements of a typed array numerically in place and returns the typed array.
... return value the sorted typed array.
TypedArray.prototype.subarray() - JavaScript
the subarray() method returns a new typedarray on the same arraybuffer store and with the same element types as for this typedarray object.
... return value a new typedarray object.
TypedArray.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() return value a new array iterator object.
WeakRef.prototype.deref() - JavaScript
the deref method returns the weakref instance's target object, or undefined if the target object has been garbage-collected.
... syntax obj = ref.deref(); return value the target object of the weakref, or undefined if the object has been garbage-collected.
WebAssembly.Memory() constructor - JavaScript
its buffer property will return 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 return a sharedarraybuffer.
WebAssembly.Memory.prototype.grow() - JavaScript
return 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 return value of grow() here is the previous number of webassembly pages.
WebAssembly.Module.imports() - JavaScript
the webassembly.imports() function returns an array containing descriptions of all the declared imports of the given module.
... return value an array containing objects representing the imported functions of the given module.
WebAssembly.Table.prototype.set() - JavaScript
return 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 return null).
WebAssembly.Table - JavaScript
instance properties table.prototype.length returns the length of the table, i.e.
... the table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation).
WebAssembly.instantiateStreaming() - JavaScript
return 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 returned 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, returning whether the bytes form a valid wasm module (true) or not (false).
... return value a boolean that specifies whether buffersource is valid wasm code (true) or not (false).
decodeURIComponent() - JavaScript
return value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component.
... function decodequeryparam(p) { return 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
return 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) { return encodeuri(str).replace(/%5b/g, '[').replace(/%5d/g, ']'); } specifications specification ecmascript (ecma-262)the definition of 'encodeuri' in that specification.
isFinite() - JavaScript
return 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 returns false; otherwise, it returns true.
undefined - JavaScript
a method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.
... a function returns undefined if a value was not returned.
Standard built-in objects - JavaScript
standard objects by category value properties these global properties return a simple value.
... infinity nan undefined globalthis function properties these global functions—functions which are called globally, rather than on an object—directly return their results to the caller.
Conditional (ternary) operator - JavaScript
person.name : `stranger` return `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(…) { return condition1 ?
...value3 : value4; } // equivalent to: function example(…) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } } specifications specification ecmascript (ecma-262)the definition of 'conditional operator' in that specification.
Less than (<) - JavaScript
the less than operator (<) returns true if the left operand is less than the right operand, and false otherwise.
... if either value is nan, the operator returns false.
Object initializer - JavaScript
function havees2015duplicatepropertysemantics() { 'use strict'; try { ({prop: 1, prop: 2}); // no error thrown, duplicate property names allowed in strict mode return true; } catch(e) { // error thrown, duplicates prohibited in strict mode return 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__() { return '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 returns an unsigned 32-bit integer.
...unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
async function expression - JavaScript
examples simple example function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds.
... }); (async function(x) { // async function expression used as an iife let p_a = resolveafter2seconds(20); let p_b = resolveafter2seconds(30); return x + await p_a + await p_b; })(10).then(v => { console.log(v); // prints 60 after 2 seconds.
Function expression - JavaScript
let math = { 'factit': function factorial(n) { console.log(n) if (n <= 1) { return 1; } return 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 returns the square of its argument: var x = function(y) { return 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() { return 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() { return 'i have 4 sides'; } } class square extends rectangle { constructor() {} static logdescription() { return 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 returns false.
... when false is returned, 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) { return 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) { return 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 return the indexes in any particular order.
... the for...in loop statement will return 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 return.
...} iterating over other iterable objects you can also iterate over an object that explicitly implements the iterable protocol: const iterable = { [symbol.iterator]() { return { i: 0, next() { if (this.i < 3) { return { value: this.i++, done: false }; } return { 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 returned object.
...when used this way, it returns 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 returns 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 returns 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 returns 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 return — 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 returning 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 returned.
... disk latency is the time it takes from the moment a computer, usually a server, receives a request, to the time the computer returns 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'); return cache.addall(contenttocache); }) ); }); last of all, the service worker fetches content from the cache if it is available there, providing offline functionality: self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then(functio...
...n(response) { return caches.open(cachename).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return 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 returns 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'); return cache.addall(contenttocache); }) ); }); with that done, we implement the service worker's fetch event handler; its job is to return the contents of the specified file, either from the cache or by loading it over the network (caching it upon doing so): self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service w...
...orker] fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cachename).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return 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
WebSVGAttributerotate
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 returns true or false.
... returns 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 returns the smallest integer greater than or equal to the decimal number.
... returns 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 returns the resulting string.
... returns 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 returns 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 returns true if haystack contains needle.
count - XPath
WebXPathFunctionscount
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the count function counts the number of nodes in a node-set and returns an integer.
... returns an integer representing the number of nodes in a node-set.
false - XPath
WebXPathFunctionsfalse
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the false function returns boolean false.
... syntax false() returns boolean false.
floor - XPath
WebXPathFunctionsfloor
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the floor function evaluates a decimal number and returns the largest integer less than or equal to the decimal number.
... returns 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 returns a string representing the number in a given format.
... returns 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 returns boolean true or false.
... returns 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 returns a string containing that id.
... returns a string containing the generated id.
last - XPath
WebXPathFunctionslast
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the last function returns a number equal to the context size from the expression evaluation context.
... syntax last() returns 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 returns the resulting string.
... returns 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 returns the number.
... returns the resulting number after converting the object.
position - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the position function returns a number equal to the context position from the expression evaluation context.
... syntax position() returns an integer equal to the context position from the expression evaluation context.
round - XPath
WebXPathFunctionsround
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the round function returns a number that is the nearest integer to the given number.
... returns 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 returns true or false.
... returns true if haystack starts with needle.
string-length - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the string-length function returns a number equal to the number of characters in a given string.
... returns 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 returns the translated string.
... returns the translated string.
true - XPath
WebXPathFunctionstrue
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the true function returns a boolean value of true.
... syntax true() returns boolean true.
unparsed-entity-url - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the unparsed-entity-url() function returns the uri of the unparsed entity with the given name.
... returns 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 returns 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 return 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 returns 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 returns 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) { return 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 returns the worker you can use to communicate with the content script(s) you attached.
Contributor's Guide - 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.
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 + "&lt;br&gt;version: " + library.version); }); widgetcontent += htmlcontentpostamble; return widgetcontent; } function updatewidgetview(tab) { var widgetview = widget.getview(tab.window); if (!tab.libraries) { tab.libraries = []; } widgetview.content = buildwidgetviewcontent(tab.libraries); widgetview.width = tab.libraries.length * icon_width; } main.js will use the tabs module to update the widget's content when necessary (for example, when the user switches between tab...
Working with Events - Archive of obsolete content
adding listeners in constructors event emitters may be modules, as is the case for the ready event above, or they may be objects returned by constructors.
clipboard - Archive of obsolete content
the function will return null if the contents of the clipboard do not match the supplied type.
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) return; items.push(result.value.name); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitems(itemlist) { console.log(itemlist); } open("1"); var add = require("sdk/ui/button/action").actionbutton({ id: "add", label: "add", icon: "./add.png", onclick: function() { additem(require("sdk/tabs").activetab.title); } }); var list = require("sdk/...
notifications - Archive of obsolete content
it may be a remote url, a data uri, or a url returned by the self module.
page-mod - Archive of obsolete content
mapping workers to tabs the worker has a tab property which returns the tab associated with this worker.
system - Archive of obsolete content
returns string : the path to the directory.
chrome - Archive of obsolete content
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.
content/symbiont - Archive of obsolete content
var { symbiont } = require('sdk/content/content'); var thing = symbiont.resolve({ constructor: '_init' }).compose({ constructor: function thing(options) { // `getmyframe` returns the host application frame in which // the page is loaded.
content/worker - Archive of obsolete content
tab if this worker is attached to a content document, returns the related tab.
frame/utils - Archive of obsolete content
returns frame : the new browser element.
stylesheet/style - Archive of obsolete content
if no type is provided in constructor's option, it returns the default value, "author".
stylesheet/utils - Archive of obsolete content
returns boolean : true if the type given is valid, otherwise false.
ui/id - Archive of obsolete content
returns string : returns a uuid by default (or domain specific id based on a provided definition).
util/match-pattern - Archive of obsolete content
returns boolean : true if the url matches the pattern and false otherwise.
Low-Level APIs - Archive of obsolete content
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.
Implementing the widget - Archive of obsolete content
main.js now in the lib directory open main.js and add the following code: var widgets = require('sdk/widget'); var data = require('sdk/self').data; var annotatorison = false; function toggleactivation() { annotatorison = !annotatorison; return annotatorison; } exports.main = function() { var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: 'ready', contentscriptfile: data.url('widget/widget.js') }); widget.port.on('left-click', function() { console.log('activate/deactivate'); widget.contenturl = toggleactivation() ?
Storing annotations - Archive of obsolete content
orage.annotations.push(newannotation); } this function calls a constructor for an annotation object, which we also need to supply: function annotation(annotationtext, anchor) { this.annotationtext = annotationtext; this.url = anchor[0]; this.ancestorid = anchor[1]; this.anchortext = anchor[2]; } now we need to link this code to the annotation editor, so that when the user presses the return key in the editor, we create and store the new annotation: var annotationeditor = panels.panel({ width: 220, height: 220, contenturl: data.url('editor/annotation-editor.html'), contentscriptfile: data.url('editor/annotation-editor.js'), onmessage: function(annotationtext) { if (annotationtext) handlenewannotation(annotationtext, this.annotationanchor); annotationeditor.hi...
Chrome Authority - Archive of obsolete content
the object returned by require("chrome"), when unpacked with the destructuring assignment feature available in the mozilla js environment, will provide the usual components.* aliases: cc an alias for components.classes.
Autocomplete - Archive of obsolete content
turning autocomplete on for a xul widget this article is about xul widgets and not about html form inputs.
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"); } } return dl; } } }; window.addeventlistener("load", function(e) { mydownloadmanager.init(); }, false); in your css file, change richdownloaditem (both occurrences) to richdownloaditem[myspecialdownload="true"].
Modules - Archive of obsolete content
some simple code to turn a javascript module into non-mozilla-specific code (e.g., if porting to the browser).
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) return; // 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); } return 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; //returns -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: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,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 return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return;...
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 return 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) return; // 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.
Extension Packaging - Archive of obsolete content
since most http servers are not configured to return this mime type for the .xpi extension by default, you will probably need to configure your http server.
Hiding browser chrome - Archive of obsolete content
var prevfunc = xulbrowserwindow.hidechromeforlocation; xulbrowserwindow.hidechromeforlocation = function(alocation) { return (/* 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 nyep6i4luuyjturnn7yw/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)) return 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() { return 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...
Introduction - Archive of obsolete content
this tutorial is meant to be the stepping stone that will turn you into a professional firefox extension developer in no time.
Mozilla Documentation Roadmap - Archive of obsolete content
there's a great deal of free online documentation available on xul and extension development, but finding it and turning it into useful information can be a daunting task.
Security best practices in extensions - Archive of obsolete content
json has become a popular data format for return formats for web services.
Setting up an extension development environment - Archive of obsolete content
note that since many people have this setting turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension.
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 return to the certificate-database folder.
dischargingtimechange - Archive of obsolete content
returns positive infinity if the battery is charging, if the implementation is unable to report the remaining discharging time, or if there is no battery attached to the system.
Getting the page URL in NPAPI plugin - Archive of obsolete content
this returns an addrefed nsidomelement interface pointer from which you can call .ownerdocument (on nsidomnode), queryinterface that object to nsidom3document, and call .documenturi.
Index of archived content - Archive of obsolete content
file object methods install object methods properties installversion object methods properties return codes winprofile object methods winreg object methods winregvalue xpjs components proposal xre xtech 2005...
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); return; } }, 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)) return 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.
Finding the code to modify - Archive of obsolete content
click the plus sign next to the statusbar node in the dom inspector and select each statusbarpanel node in turn.
Creating a Microsummary - Archive of obsolete content
otherwise, if the url returns plain text content (or html content that can be converted to plain text), firefox uses the content as the microsummary for 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"); } } return file; } public file[] getfiles(string aprop) { file[] files = null; if (aprop.equals("apluginsdl")) { files = new file[1]; files[0] = new file(libxulpath, "plugins"); } return files; } } calling xpcom ui from another thread appstartup.run() enters the main event loop and will stay there until the application exits.
Block and Line Layout Cheat Sheet - Archive of obsolete content
it may be set as a side-effect of calling nsblockframe::shouldapplytopmargin(); once set, shouldapplytopmargin() uses it as a fast-path way to return whether the top margin should apply.
Downloading Nightly or Trunk Builds - Archive of obsolete content
as it turns out there is a platform number for every firefox number, but they are not the same number.
CRMF Request object - Archive of obsolete content
the object returned by generatecrmfrequest() contains one of those.
Enabling Experimental Jetpack Features - Archive of obsolete content
list() arrayreturns an array of the set of potential stringmountpath as used in jetpack.future.import().
Enabling - Archive of obsolete content
list()returns an array of the set of potential stringmountpath as used in jetpack.future.import().
Enabling Experimental Jetpack Features - Archive of obsolete content
ArchiveMozillaJetpackdocsMetaFuture
list() arrayreturns an array of the set of potential stringmountpath as used in jetpack.future.import().
NSC_SetPIN - Archive of obsolete content
return value ckr_ok examples #include <assert.h> see also fc_setpin ...
New Security Model for Web Services - Archive of obsolete content
) return pr_true if access granted else pr_false void invalidatecache(in string atransporturi); invalidate cached entry for the given transport uri.
Configuration - Archive of obsolete content
status turns the status messages on or off for this web app: yes or no location turns the readonly location bar on or off for this web app: yes or no navigation turns the hotkey history navigation (alt+left, alt+right and alt+home) on or off for this web app: yes or no splashscreen filename of an html page to be displayed while the app is loading.
Scripting - Archive of obsolete content
returning false causes the application to terminate.
New Skin Notes - Archive of obsolete content
--nickolay 04:46, 25 aug 2005 (pdt) the sidebar overrides content on diff pages --nickolay turns out this was fixed for 1.5 already.
Remote debugging - Archive of obsolete content
(that is, there's a legitimate reason it happens only on some computers, but that reason just hasn't been discovered.) the crash victim, in turn, trusts the developer with full access to his computer.
SpiderMonkey coding conventions - Archive of obsolete content
linkage dll entry points have their return type expanded within a js_public_api() macro call, to get the right windows secret type qualifiers in the right places for all build variants.
open - Archive of obsolete content
for all file types, carriage returns and linefeeds are treated in a platform-agnostic way.
Supporting per-window private browsing - Archive of obsolete content
} } catch(e) { components.utils.reporterror(e); return; } } obtaining an nsiloadcontext for privacy-sensitive apis some apis (such as nsitransferable and nsiwebbrowserpersist) take nsiloadcontext arguments that are used to determine whether they should be classed as private or not (for example, whether the uri being persisted by saveuri should be added to the permanent download history).
Table Layout Strategy - Archive of obsolete content
the second table has <col width="33%"><col> lets return to the first case but now but with more than 100%: <col width="40%"><col width="80%"><tbody></tbody>foobar <col width="40%"><col><tbody></tbody>foobar <table border width="200px"> <col width="40%"><col width="80%"> <tbody> <tr><td>foo</td><td>bar</td></tr> </tbody> </table> the algorithm tries to satisfy the requirements on a first come first serve base.
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 returnvoid } 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...
Actionscript Acceptance Tests - Archive of obsolete content
# these values correspond to the value returned by time.tzname tuple.
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 returns 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 return 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 return 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 returned 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 returns 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.
The life of an HTML HTTP request - Archive of obsolete content
this streamlistener is returned to the documentloader and connected to the nsichannel of the request.
The new nsString class implementation (1999) - Archive of obsolete content
i'm wondering if this is sufficient, namely, that a string can return it's own (shared) allocator for this purpose.
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 return to the event loop, which allows layout and painting to happen.
Venkman Internals - Archive of obsolete content
try starting up venkman and type "/watch-expr client.scriptmanagers", make sure to turn on "include functions".
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 return control to the debugger when the call returns.
Binding Attachment and Detachment - Archive of obsolete content
scripts that invoke this method should not assume that the binding is installed immediately after this method returns.
Creating XPI Installer Modules - Archive of obsolete content
one way of another, the chrome registry is shown the contents.rdf files; the contents.rdf files in turn point to new resources, and the resources are then registered with mozilla and accessible to the user.
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 returns: " + err); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
File.windowsShortcut - Archive of obsolete content
"1.1.1.1"; initinstall( "windows shortcut", "test", vi, 0); f = getfolder("windows"); g = getfolder("temporary"); addfile( "miscshortcut", "2.2.2.2", xpisrc, f, xpisrc, true); target = getfolder(f, xpisrc); shortcutpath = getfolder("program"); err = file.windowsshortcut( target, shortcutpath, "misc shortcut", g, "", target, 0); logcomment("file.windowsshortcut returns: " + err); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
Trigger Scripts and Install Scripts - Archive of obsolete content
a trigger script may trigger the downloading of a xpi, which in turn will use its own install.js script to manage the complete installation.
toString - Archive of obsolete content
returns the major, minor, revision, and build numbers represented as a single string.
alert - Archive of obsolete content
returns nothing.
loadResources - Archive of obsolete content
returns a javascript object whose property names are the keys from that file and whose values are the strings.
refreshPlugins - Archive of obsolete content
returns nothing.
resetError - Archive of obsolete content
returns nothing.
setPackageFolder - Archive of obsolete content
returns none.
Install Object - Archive of obsolete content
perform installation check that the files have been added successfully (e.g., by checking the error return codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlasterror()) performinstall(); else cancelinstall(); } for complete script examples, see script examples.
writeString - Archive of obsolete content
returns true if successfully scheduled, otherwise, false.
deleteValue - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion.
enumKeys - Archive of obsolete content
returns the name if it succeeded; null if the referenced value does not exist.
enumValueNames - Archive of obsolete content
returns the value of the key as a string if it succeeded; null if the referenced subkey does not exist.
getValue - Archive of obsolete content
returns a winregvalue object representing the value of the named value-name/value pair or null if there is no value or if there is an error.
getValueNumber - Archive of obsolete content
returns number value of the specified key or null if there's an error, the value is not found, or the value is not a string.
getValueString - Archive of obsolete content
returns a string representing the value of the named value-name/value pair or null if there's an error, the value is not found, or the value is not a string.
setRootKey - Archive of obsolete content
returns nothing.
WinRegValue - Archive of obsolete content
returns a new winregvalue object, with the data members type and data set to the values passed to this constructor.
XPInstall API reference - Archive of obsolete content
no properties methods createkey deletekey deletevalue enumkeys enumvaluenames getvalue getvaluenumber getvaluestring iskeywritable keyexists setrootkey setvalue setvaluenumber setvaluestring valueexists winregvalue constructor other information return codes see complete list examples trigger scripts and install scripts code samples file.macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install ...
XPJS Components Proposal - Archive of obsolete content
our friend xpconnect will convert the js object returned from the js module's nsgetfactory function into an xpcom object.
A XUL Bestiary - Archive of obsolete content
locale/ us-en/ navigator.dtd to load chrome information stored in a new package directory like this, you can use the following chrome url, chrome://navigator/skin/mynewskin/newskin.css which in turn loads the graphics in that subdirectory as needed.
accessible - Archive of obsolete content
« xul reference home accessible type: nsiaccessible returns the accessibility object for the element.
chromemargin - Archive of obsolete content
if this value turns out to be less than 0, 0 is used.
disablechrome - Archive of obsolete content
note: this has no effect if the tabs on top preference is turned off.
expr - Archive of obsolete content
ArchiveMozillaXULAttributeexpr
« xul reference home expr type: string for xml queries, an xpath expression which returns results.
menuitem.name - Archive of obsolete content
example <toolbox> <menubar id="planets-menubar"> <menu id="planet-menu" label="planet"> <menupopup> <menuitem id="jupiter" label="jupiter" type="radio" name="planet"/> <menuitem id="saturn" label="saturn" type="radio" name="planet" checked="true"/> <menuitem id="uranus" label="uranus" type="radio" name="planet"/> </menupopup> </menu> </menubar> </toolbox> see also name and menus in the xul tutorial ...
minresultsforpopup - Archive of obsolete content
« xul reference home minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number of results that must be returned for the popup to be displayed.
onbeforeaccept - Archive of obsolete content
returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527).
onchange - 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="return myfunction(event);"/> </window> ...
oncommand - Archive of obsolete content
example 1: in-line code <button label="click me" oncommand="alert('hi')"/> example 2: function with source argument <button label="click me" oncommand="dosomeprocessing(event.target)"/> and here is the definition of the function: function dosomeprocessing(source) { alert("source: " + source); return true; } see also command element ...
onpopupshowing - Archive of obsolete content
returning false from this event handler prevents the popup from appearing.
pending - 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.
showimagecolumn - Archive of obsolete content
there is no default styling of this image, but the class name returned by the results appears in the property list for the column.
textbox.minResultsForPopup - Archive of obsolete content
« xul reference home minresultsforpopup obsolete since gecko 1.9.1 type: integer the minimum number of results that must be returned for the popup to be displayed.
textbox.value - Archive of obsolete content
for number boxes, the default is 0 or the minimum value returned by the min property, whichever is higher.
addTabsProgressListener - Archive of obsolete content
« xul reference home addtabsprogresslistener( listener ) return type: no return value add a progress listener to the browser which will monitor loaded documents in all tabs in the tabbed browser.
onFindAgainCommand - Archive of obsolete content
« xul reference home onfindagaincommand( findprevious ) return type: no return value call this method to handle your application's "find next" and "find previous" commands.
open - Archive of obsolete content
ArchiveMozillaXULMethodOpen
« xul reference home open( mode ) return type: no return value opens the findbar using the specified mode, which should be one of find_normal, find_typeahead, or find_links.
removeTabsProgressListener - Archive of obsolete content
« xul reference home removetabsprogresslistener( listener ) return type: no return value removes a progress listener to the browser which has been monitoring all tabs.
startFind - Archive of obsolete content
« xul reference home startfind( mode ) return type: no return value call this method to handle your application's "find" command.
swapDocShells - Archive of obsolete content
« xul reference home swapdocshells( otherbrowser ) return type: no return value swaps the content, history and current state of this browser with another browser.
toggleHighlight - Archive of obsolete content
« xul reference home togglehighlight( highlight ) return type: no return value turns highlighting of text matching the search term on and off; specify false to disable highlighting or true to enable it.
acceptDialog - Archive of obsolete content
« xul reference home acceptdialog() return type: no return value accepts the dialog and closes it, similar to pressing the ok button.
addItemToSelection - Archive of obsolete content
« xul reference home additemtoselection( item ) return type: no return value selects the given item, without deselecting any other items that are already selected.
addPane - Archive of obsolete content
ArchiveMozillaXULMethodaddPane
« xul reference home addpane( prefpane ) return type: no return value append a prefpane to a list of panes.
addProgressListener - Archive of obsolete content
« xul reference home addprogresslistener( listener ) return type: no return value add a progress listener to the browser which will monitor loaded documents.
addTab - Archive of obsolete content
ArchiveMozillaXULMethodaddTab
}) return type: tab element opens a new tab that loads a page with the specified url.
advance - Archive of obsolete content
ArchiveMozillaXULMethodadvance
« xul reference home advance( pageid ) return type: no return value call this method to go to the next page.
advanceSelectedTab - Archive of obsolete content
« xul reference home advanceselectedtab( dir, wrap ) return type: no return value if the argument dir is set to 1, the currently selected tab changes to the next tab.
appendGroup - Archive of obsolete content
« xul reference home appendgroup( group ) return type: no return value not in firefox add several new tabs to the end of the existing tabs.
blur - Archive of obsolete content
ArchiveMozillaXULMethodblur
« xul reference home blur() return type: no return value if the focus is on the element, it is removed.
cancel - Archive of obsolete content
ArchiveMozillaXULMethodcancel
« xul reference home cancel() return type: no return value call this method to cancel and close the wizard.
cancelDialog - Archive of obsolete content
« xul reference home canceldialog() return type: no return value cancels the dialog and closes it, similar to pressing the cancel button.
centerWindowOnScreen - Archive of obsolete content
« xul reference home centerwindowonscreen() return type: no return value centers the dialog on the screen.
checkAdjacentElement - Archive of obsolete content
« xul reference home checkadjacentelement( dir ) return type: no return value deselects the currently selected radio button in the group and selects the one adjacent to it.
clearResults - Archive of obsolete content
« xul reference home clearresults() return type: ???
clearSelection - Archive of obsolete content
« xul reference home clearselection() return type: no return value deselects all of the items.
click - Archive of obsolete content
ArchiveMozillaXULMethodclick
« xul reference home click() return type: no return value calls the onclick handler for the element.
close - Archive of obsolete content
ArchiveMozillaXULMethodclose
« xul reference home close() return type: no return value closes the notification or findbar and removes it from its enclosing notificationbox or findbar.
collapseToolbar - Archive of obsolete content
« xul reference home collapsetoolbar( toolbar ) not in firefox return type: no return value collapse the given toolbar which should be contained within the toolbox.
contains - Archive of obsolete content
« xul reference home contains( item ) return type: boolean returns true if the menulist contains the specified menuitem as one of its items.
decrease - Archive of obsolete content
« xul reference home method of: scale textbox decrease() return type: no return value decreases the value of the scale or number box by the increment.
decreasePage - Archive of obsolete content
« xul reference home method of: scale decreasepage() return type: no return value decreases the value of the scale by the pageincrement.
doCommand - Archive of obsolete content
« xul reference home docommand() return type: no return value executes the command event for the element.
ensureElementIsVisible - Archive of obsolete content
« xul reference home ensureelementisvisible( element ) return type: no return value if the specified element is not currently visible to the user, the displayed items are scrolled so that it is.
ensureIndexIsVisible - Archive of obsolete content
« xul reference home ensureindexisvisible( index ) return type: no return value if the item at the specified index is not currently visible to the user the displayed items are scrolled so that it is.
ensureSelectedElementIsVisible - Archive of obsolete content
« xul reference home ensureselectedelementisvisible() return type: no return value if the currently selected element in the list box is not currently visible to the user, the list box view is scrolled so that it is.
expandToolbar - Archive of obsolete content
« xul reference home expandtoolbar( toolbar ) not in firefox return type: no return value expand the given toolbar which should be contained in the toolbox.
extra1 - Archive of obsolete content
ArchiveMozillaXULMethodextra1
« xul reference home extra1() return type: no return value call this method to simulate clicking the extra1 button.
extra2 - Archive of obsolete content
ArchiveMozillaXULMethodextra2
« xul reference home extra2() return type: no return value call this method to simulate clicking the extra2 button.
focus - Archive of obsolete content
ArchiveMozillaXULMethodfocus
« xul reference home focus() return type: no return value assigns the focus to the element, if it can accept the focus.
getBrowserAtIndex - Archive of obsolete content
« xul reference home getbrowseratindex( index ) return type: browser element returns a browser at the specified tab index.
getBrowserForDocument - Archive of obsolete content
« xul reference home getbrowserfordocument( document ) return type: browser element returns a browser for the specified document.
getBrowserForTab - Archive of obsolete content
« xul reference home getbrowserfortab( tab ) return type: browser element returns a browser for the specified tab element.
getButton - Archive of obsolete content
« xul reference home getbutton( type ) return type: button element returns the button element in the dialog corresponding to the given type.
getDefaultSession - Archive of obsolete content
« xul reference home getdefaultsession return type: session name returns the name of the first session with available results.
getEditor - Archive of obsolete content
« xul reference home geteditor( window ) return type: nsieditor returns the editing interface for the editor which contains numerous methods for manipulating the document.
getElementsByAttributeNS - Archive of obsolete content
« xul reference home getelementsbyattributens(ns, attrib, value ) return type: dom nodelist returns an array of all the child elements of the element that have the attribute namespace given by the first argument, the attribute name given by the second argument, and the value given by the third argument.
getFormattedString - Archive of obsolete content
« xul reference home getformattedstring( key, strarray ) return type: string looks up the format string for the given key name in the string bundle and returns a formatted copy where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
getHTMLEditor - Archive of obsolete content
« xul reference home gethtmleditor( window ) return type: nsihtmleditor returns the html editing interface for the editor which contains methods for manipulating an html document.
getIndexOfFirstVisibleRow - Archive of obsolete content
« xul reference home getindexoffirstvisiblerow() return type: integer returns the index of the first displayed row.
getIndexOfItem - Archive of obsolete content
« xul reference home getindexofitem( item ) return type: integer returns the zero-based position of the specified item.
getItemAtIndex - Archive of obsolete content
« xul reference home getitematindex( index ) return type: element returns the element that is at the specified index.
getNotificationBox - Archive of obsolete content
« xul reference home getnotificationbox( browser ) return type: notificationbox element returns a notificationbox for the specified browser element.
getNumberOfVisibleRows - Archive of obsolete content
« xul reference home getnumberofvisiblerows() return type: integer returns the number of rows that are currently visible to the user.
getPageById - Archive of obsolete content
« xul reference home getpagebyid( pageid ) return type: wizardpage element returns the wizardpage element corresponding to the specified pageid.
getResultAt - Archive of obsolete content
« xul reference home getresultat( index ) obsolete since gecko 26 return type: nsiautocompleteitem returns the result item at the specified index.
getResultCount - Archive of obsolete content
« xul reference home getresultcount( session ) returns the number of results, holded by the current session.
getResultValueAt - Archive of obsolete content
« xul reference home getresultvalueat( index ) return type: result value returns the result value at the specified index.
getRowCount - Archive of obsolete content
« xul reference home getrowcount() return type: integer returns the total number of rows in the element, regardless of how many rows are displayed.
getSearchAt - Archive of obsolete content
« xul reference home getsearchat( index ) return type: string returns the search component with the given index.
getSessionResultAt - Archive of obsolete content
« xul reference home getsessionresultat( session, index ) obsolete since gecko 26 return type: result item returns the result item at the specified index for the specified session.
getSessionStatusAt - Archive of obsolete content
« xul reference home getsessionstatusat( index ) obsolete since gecko 26 return type: any value listed in nsiautocompletestatus returns the status for the session object with the given index.
getSessionValueAt - Archive of obsolete content
« xul reference home getsessionvalueat( session, index ) return type: result value returns the result value at the specified index for a specific session.
getString - Archive of obsolete content
« xul reference home getstring( key ) return type: string returns the string with the given key name from the string bundle.
getTabForBrowser - Archive of obsolete content
« xul reference home gettabforbrowser( browser ) return type: tab returns the xul tab which contains the specified browser.
goBack - Archive of obsolete content
ArchiveMozillaXULMethodgoBack
« xul reference home goback() return type: no return value go back one page in the history.
goBackGroup - Archive of obsolete content
« xul reference home gobackgroup() not in firefox return type: no return value returns to the previous group of tabs.
goDown - Archive of obsolete content
ArchiveMozillaXULMethodgoDown
« xul reference home godown() return type: no return value move the selection down by one item.
goForward - Archive of obsolete content
« xul reference home goforward() return type: no return value go forward one page in the history.
goForwardGroup - Archive of obsolete content
« xul reference home goforwardgroup() not in firefox return type: no return value go forward to the next group of tabs.
goHome - Archive of obsolete content
ArchiveMozillaXULMethodgoHome
« xul reference home gohome() return type: no return value load the user's home page into the browser.
goTo - Archive of obsolete content
ArchiveMozillaXULMethodgoTo
« xul reference home goto( pageid ) return type: no return value this method is used to change which page is currently displayed, specified by the pageid argument.
goUp - Archive of obsolete content
ArchiveMozillaXULMethodgoUp
« xul reference home goup() return type: no return value move the selection up by one item.
gotoIndex - Archive of obsolete content
« xul reference home gotoindex( index ) return type: no return value navigate to the page in the history with the given index.
hasUserValue - Archive of obsolete content
« xul reference home hasuservalue() return type: boolean returns true if the preference has been changed from its default value.
hidePopup - Archive of obsolete content
« xul reference home method of: popup, menupopup, tooltip hidepopup() return type: no return value closes the popup immediately.
increase - Archive of obsolete content
« xul reference home method of: scale textbox increase() return type: no return value increases the value of the scale or number box by the increment.
increasePage - Archive of obsolete content
« xul reference home method of: scale increasepage() return type: no return value increases the value of the scale by the page increment.
invertSelection - Archive of obsolete content
« xul reference home invertselection() return type: no return value reverses the selected state of all items.
loadOneTab - Archive of obsolete content
}) return type: tab element opens a new tab that loads a page with the specified url.
loadTabs - Archive of obsolete content
« xul reference home loadtabs( uris, loadinbackground, replace ) loadtabs( uris, params ) return type: no return value loads a set of uris, specified by the array uris, into tabs.
loadURI - Archive of obsolete content
ArchiveMozillaXULMethodloadURI
(this one has no post data parameter, see loaduriwithflags for a version that does) loaduri( uri, referrer, charset ) return type: no return 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 ) return type: no return value load a url into the document, with the specified load flags, the given referrer, character set, and post data.
makeEditable - Archive of obsolete content
« xul reference home makeeditable( editortype, waitforload ) return type: no return value this function enables editing for an editor.
menulist.select - Archive of obsolete content
« xul reference home select() return type: no return value select all the text in the menulist's textbox.
moveByOffset - Archive of obsolete content
« xul reference home movebyoffset( offset , isselecting, isselectingrange) return type: no return value if offset is positive, adjusts the focused item forward by that many items.
moveTabTo - Archive of obsolete content
« xul reference home movetabto(tab, index) return type: tab element tries to moves an existing tab to a given index.
moveTo - Archive of obsolete content
ArchiveMozillaXULMethodmoveTo
« xul reference home moveto( x, y ) return type: no return value moves the popup to a new location defined by screen coordinates (and not client coordinates).
moveToAlertPosition - Archive of obsolete content
« xul reference home movetoalertposition() return type: no return value moves and resizes the dialog to a position and size suitable for an alert box.
onSearchComplete - Archive of obsolete content
« xul reference home onsearchcomplete() return type: no return value calls the onsearchcomplete event handler.
onTextEntered - Archive of obsolete content
« xul reference home ontextentered() return type: event result calls the ontextentered event handler.
onTextReverted - Archive of obsolete content
« xul reference home ontextreverted() return type: event result calls the ontextreverted event handler.
openPopup - Archive of obsolete content
« xul reference home openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) return type: no return value opens the popup relative to a specified node at a specific location.
openPopupAtScreen - Archive of obsolete content
« xul reference home openpopupatscreen( x, y, iscontextmenu ) return type: no return value open the popup at a specific screen position specified by x and y.
openSubDialog - Archive of obsolete content
« xul reference home opensubdialog( url, features, params ) return type: window opens a child modal dialog.
openWindow - Archive of obsolete content
« xul reference home openwindow( windowtype, url, features, params ) return type: window open a child window.
pinTab - Archive of obsolete content
ArchiveMozillaXULMethodpinTab
« xul reference home pintab( tabelement ) return type: no return value pins the specified tab element as an app tab.
preferenceForElement - Archive of obsolete content
« xul reference home preferenceforelement( uielement ) return type: preference element returns the preference element to which a user interface element is attached.
reload - Archive of obsolete content
ArchiveMozillaXULMethodreload
« xul reference home reload() return type: no return value reloads the document in the browser element on which you call this method.
reloadAllTabs - Archive of obsolete content
« xul reference home reloadalltabs() return type: no return value reloads the contents of all the tabs.
reloadTab - Archive of obsolete content
« xul reference home reloadtab( tab ) return type: no return value reloads the contents of a specific tab.
reloadWithFlags - Archive of obsolete content
« xul reference home reloadwithflags( flags ) return type: no return value reloads the document in the browser with the given load flags.
removeAllItems - Archive of obsolete content
« xul reference home removeallitems() return type: no return value removes all of the items in the menu.
removeAllNotifications - Archive of obsolete content
« xul reference home removeallnotifications( immediate ) return type: no return value remove all notifications.
removeAllTabsBut - Archive of obsolete content
« xul reference home removealltabsbut( tabelement ) return type: no return value removes all of the tab panels except for the one corresponding to the specified tab.
removeCurrentNotification - Archive of obsolete content
« xul reference home removecurrentnotification() return type: no return value remove the current notification.
removeCurrentTab - Archive of obsolete content
« xul reference home removecurrenttab() return type: tab element removes the currently displayed tab page.
removeItemFromSelection - Archive of obsolete content
« xul reference home removeitemfromselection( item ) return type: no return value deselects the specified item without deselecting other items.
removeNotification - Archive of obsolete content
« xul reference home removenotification( item ) return type: element remove a notification, displaying the next one if the removed item is the current one.
removeProgressListener - Archive of obsolete content
« xul reference home removeprogresslistener( listener ) return type: no return value remove a nsiwebprogresslistener from the browser.
removeSession - Archive of obsolete content
« xul reference home removesession( session ) obsolete since gecko 26 return type: void removes a session object from the autocomplete widget.
removeTab - Archive of obsolete content
« xul reference home removetab( tabelement ) return type: no return value removes a specific tabbed page corresponding to the given tab element.
removeTransientNotifications - Archive of obsolete content
« xul reference home removetransientnotifications( ) return type: no return value remove only those notifications that have a persistence value of zero, and decrements by one the persistence value of those that have a non-zero value.
reset - Archive of obsolete content
ArchiveMozillaXULMethodreset
« xul reference home reset() return type: no return value resets the preference to its default value.
rewind - Archive of obsolete content
ArchiveMozillaXULMethodrewind
« xul reference home rewind() return type: no return value call this method to go back a page.
scrollByIndex - Archive of obsolete content
« xul reference home scrollbyindex( lines ) return type: no return value scrolls the contents of the arrowscrollbox by a certain number of lines.
scrollByPixels - Archive of obsolete content
« xul reference home scrollbypixels( pixels ) return type: no return value scrolls the contents of the arrowscrollbox by a certain number of pixels.
scrollToIndex - Archive of obsolete content
« xul reference home scrolltoindex( index ) return type: no return value scrolls the element to the specified index.
select - Archive of obsolete content
ArchiveMozillaXULMethodselect
« xul reference home select() return type: no return value selects all the text in the textbox.
selectAll - Archive of obsolete content
« xul reference home selectall() return type: no return value selects all of the items.
selectItem - Archive of obsolete content
« xul reference home selectitem( item ) return type: no return value deselects all of the currently selected items and selects the given item.
selectItemRange - Archive of obsolete content
« xul reference home selectitemrange( startitem, enditem ) return type: no return value selects the items between the two items given as arguments, including the start and end items.
selectTabAtIndex - Archive of obsolete content
« xul reference home selecttabatindex( index, event ) return type: no return value selects the tab at the given index.
setIcon - Archive of obsolete content
ArchiveMozillaXULMethodsetIcon
« xul reference home seticon( atab, auri ) return type: no return value sets the specified tab's favicon to the image specified by auri.
setSelectionRange - Archive of obsolete content
« xul reference home setselectionrange( start, end ) return type: no return value sets the selected portion of the textbox, where the start argument is the index of the first character to select and the end argument is the index of the character after the selection.
showOnlyTheseTabs - Archive of obsolete content
« xul reference home showonlythesetabs( atabs ) return type: no return value makes all tabs in the atabs array visible, and all other tabs hidden.
showPane - Archive of obsolete content
« xul reference home showpane( prefpane ) return type: no return value switch to a particular pane.
showPopup - Archive of obsolete content
« xul reference home showpopup( element, x, y, popuptype, anchor, align ) deprecated since gecko 1.9 return type: no return value deprecated in favor of openpopup and openpopupatscreen opens a popup element.
sizeTo - Archive of obsolete content
ArchiveMozillaXULMethodsizeTo
« xul reference home sizeto( width, height ) return type: no return value changes the current size of the popup to the new width and height.
startEditing - Archive of obsolete content
« xul reference home startediting( row, column ) return type: no return value activates user editing of the given cell, which is specified by row index number and the nsitreecolumn in which it is located.
stop - Archive of obsolete content
ArchiveMozillaXULMethodstop
« xul reference home stop() return type: no return value equivalent to pressing the stop button, this method stops the currently loading document.
stopEditing - Archive of obsolete content
« xul reference home stopediting( shouldaccept ) return type: no return value stops editing the cell currently being edited.
syncSessions - Archive of obsolete content
« xul reference home syncsessions( autocompleteelement ) obsolete since gecko 26 return type: void copy the sessions from another autocomplete element.
timedSelect - Archive of obsolete content
« xul reference home timedselect( item, timeout ) return type: no return value selects the item specified by the argument item after the number of milliseconds given by the timeout argument.
toggleItemSelection - Archive of obsolete content
« xul reference home toggleitemselection( item ) return type: no return value if the specified item is selected, it is deselected.
unpinTab - Archive of obsolete content
« xul reference home unpintab( tabelement ) return type: no return value unpins the specified tab element, making it no longer an app tab.
Special per-platform menu considerations - Archive of obsolete content
for example, using document.getelementbyid() for the quit menu item returns the hidden item that still sits in the file menu.
PopupKeys - Archive of obsolete content
enter/return activate the currently highlighted item.
accessible - Archive of obsolete content
« xul reference accessible type: nsiaccessible returns the accessibility object for the element.
appLocale - Archive of obsolete content
« xul reference applocale obsolete since gecko 1.9.1 type: nsilocale returns the xpcom object which holds information about the user's locale.
children - Archive of obsolete content
« xul reference children type: array of elements returns the list of items in the richlistbox.
colorpicker.open - Archive of obsolete content
« xul reference open type: boolean returns true if the popup for a button-type colorpicker is open.
columns - Archive of obsolete content
« xul reference columns type: nsitreecolumns returns the columns for the tree as an nsitreecolumns object.
controller - Archive of obsolete content
« xul reference controller type: nsiautocompletecontroller returns the controller for the auto complete element.
controllers - Archive of obsolete content
example <window id="controller-example" title="controller example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getelementbyid("thelist"); var listcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_delete"); }, iscommandenabled : function(cmd){ if (cmd == "cmd_delete") return (list.selecteditem != null); return false; }, docommand : function(cmd){ list.removeitemat(list.selectedindex); }, onevent : function(evt){ } }; list.controllers.appendcontroller(listcontroller); } </script> <listbox id="thelist"> <listitem label="ocean"/> <l...
currentItem - Archive of obsolete content
« xul reference currentitem type: listitem element returns the currently focused item in the list box, which is only useful in a multiple selection list box.
currentPage - Archive of obsolete content
« xul reference currentpage type: wizardpage element this property returns the wizardpage element that is currently displayed.
database - Archive of obsolete content
« xul reference database type: nsirdfcompositedatasource returns the composite datasource created when all the datasources of an element are combined.
menuitem.control - Archive of obsolete content
« xul reference control type: menu element returns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu.
pageIndex - Archive of obsolete content
« xul reference pageindex type: integer this property returns the index of the currently selected page.
pageStep - Archive of obsolete content
« xul reference pagestep type: integer this property returns 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.
parentContainer - Archive of obsolete content
« xul reference parentcontainer type: menu element read only property that returns the containing menu element, or null if there isn't a containing menu.
radio.control - Archive of obsolete content
« xul reference control type: radiogroup element returns the enclosing radiogroup that the radio element is contained within, which may or may not be its direct parent.
resource - Archive of obsolete content
« xul reference resource type: nsirdfresource returns an rdf resource with the value of the element's ref attribute.
searchCount - Archive of obsolete content
« xul reference searchcount new in thunderbird 15 requires seamonkey 2.12 type: integer returns the number of search components used.
selectedBrowser - Archive of obsolete content
« xul reference selectedbrowser type: browser element this read-only property returns the currently displayed browser element.
selectedCount - Archive of obsolete content
« xul reference selectedcount type: integer returns the number of items that are currently selected.
selectedItems - Archive of obsolete content
« xul reference selecteditems type: array of listitems returns an array of the selected items in the list.
spinButtons - Archive of obsolete content
« xul reference spinbuttons type: element the read-only property returns a reference to the spinbuttons element used by the number box.
stringBundle - Archive of obsolete content
« xul reference stringbundle type: nsistringbundle returns the xpcom string bundle object which implements nsistringbundle.
tab.control - Archive of obsolete content
« xul reference control type: tabs element returns the enclosing tabs element.
tabContainer - Archive of obsolete content
« xul reference tabcontainer type: tabs element returns the tabs element that contains the tabs.
tabbox - Archive of obsolete content
« xul reference tabbox type: tabbox element returns the tabbox element that contains the tabs.
textValue - Archive of obsolete content
« xul reference textvalue new in thunderbird 15 requires seamonkey 2.12 type: string returns the content of the textbox.
uri - Archive of obsolete content
ArchiveMozillaXULPropertyuri
each resource is placed in the variable specified in the uri attribute in turn.
Actions - Archive of obsolete content
here is the [example], and an image of what it looks like: the template builder iterates through the three results, processing the body of the action for each one in turn.
Static Content - Archive of obsolete content
at this point, the menulist will have a menupopup as a child, and the menupopup will in turn have one menuitem child.
Template Logging - Archive of obsolete content
for example, if you spell a value wrong, no data may be returned, 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.
Using Recursive Templates - Archive of obsolete content
however, in most cases, there either aren't any children or the next iteration of the query doesn't return any results, so no output is generated.
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
presss the return or enter key, or the evaluate button.
Adding Event Handlers - Archive of obsolete content
the syntax is as follows: example 3 : source view <button id="okbutton" label="ok"/> <script> function buttonpressed(event){ alert('button was pressed!'); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command', buttonpressed, true); </script> the getelementbyid() function returns the element with a given id, in this case the button.
Advanced Rules - Archive of obsolete content
so the builder will set the 'city' variable to the each child resource in turn.
Anonymous Content - Archive of obsolete content
these elements would in turn be bound to other bindings that use the base xul elements.
Creating a Window - Archive of obsolete content
choose tools – error console, type a line of javascript, and press the evaluate button, or the return or enter key.
Features of a Window - Archive of obsolete content
this function will return a reference to the newly opened window.
Focus and Selection - Archive of obsolete content
you can also set it to ignore to turn off the focus for an element.
Grids - Archive of obsolete content
ArchiveMozillaXULTutorialGrids
the second column contains a box in its second row, which in turn contains two elements, a textbox and a button.
Input Controls - Archive of obsolete content
clicking one will turn off all of the others in the same group.
Keyboard Shortcuts - Archive of obsolete content
vk_cancel vk_back vk_tab vk_clear vk_return vk_enter vk_shift vk_control vk_alt vk_pause vk_caps_lock vk_escape vk_space vk_page_up vk_page_down vk_end vk_home vk_left vk_up vk_right vk_down vk_printscreen vk_insert vk_delete vk_0 vk_1 vk_2 vk_3 vk_4 vk_5 vk_6 vk_7 vk_8 vk_9 vk_semicolon vk_equals ...
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 return 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="saturn" label="saturn" 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...
Progress Meters - Archive of obsolete content
we'll add a script later to turn it on and off.
The Chrome URL - Archive of obsolete content
mozilla will take care of determining where the file is located and return the right data.
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); } } return id; } alert(getappid()); see also mxr: nsixulappinfo.idl ...
Using spell checking in XUL - Archive of obsolete content
this method returns true if the word is correctly spelled, or false if it's not.
XUL Parser in Python/source - Archive of obsolete content
def strip(snip): t = re.sub('http://.*?\s', '', snip) return 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...
XULBrowserWindow - Archive of obsolete content
return value true if chrome should be hidden while displaying the specified location; otherwise false.
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 returns results.
checkbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an element that can be turned on and off.
content - Archive of obsolete content
each resource is placed in the variable specified in the uri attribute in turn.
listitem - Archive of obsolete content
accessible type: nsiaccessible returns the accessibility object for the element.
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() return type: no return value closes the notification or findbar and removes it from its enclosing notificationbox or findbar.
query - Archive of obsolete content
ArchiveMozillaXULquery
attributes expr examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results.
richlistitem - Archive of obsolete content
properties accessible type: nsiaccessible returns the accessibility object for the element.
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 returns 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.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
finally, ben turner and the songbird folks were perhaps the first to write any documentation about building xulrunner apps with the mozilla build system, something i know dave took advantage of.
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 Hall of Fame - Archive of obsolete content
you can add tasks to a pool, turn them on and off, and it will tick off seconds.
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 returned 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; } return 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...
Mozilla.dev.apps.firefox-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-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 returned 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 returned failure code: 0x80570016 (ns_error_xpc_gs_returned_failure) [nsijscid.getservice]" nsresult: "0x80570016 (ns_error_xpc_gs_returned_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.
2006-09-29 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week.
2006-10-06 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week.
2006-10-13 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week.
2006-10-20 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week.
2006-10-27 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week.
2006-11-03 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week discussions none during this week meetings none during this week.
2006-11-10 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week discussions none during this week meetings none during this week.
2006-11-17 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week discussions none during this week meetings none during this week.
2006-11-24 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week discussions none during this week meetings none during this week.
2006-12-01 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week discussions none during this week meetings none during this week.
2006-12-08 - Archive of obsolete content
return to mozilla-dev-extensions announcements none during this week discussions none during this week meetings none during this week.
2006-09-29 - Archive of obsolete content
summary: mozilla.dev.security - september 23, 2006 to september 29, 2006 return to mozilla-dev-security announcements none during this week.
2006-10-06 - Archive of obsolete content
summary: mozilla.dev.security - september 30, 2006 to october 6, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.security - october 7, 2006 to october 13, 2006 return to mozilla-dev-security announcements none during this week.
2006-10-20 - Archive of obsolete content
summary: mozilla.dev.security - october 14, 2006 to october 20, 2006 return to mozilla-dev-security announcements none during this week.
2006-10-27 - Archive of obsolete content
summary: mozilla.dev.security - october 21, 2006 to october 27, 2006 return to mozilla-dev-security announcements none during this week.
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.security - october 28, 2006 to november 3, 2006 return to mozilla-dev-security announcements none during this week.
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.security - november 4, 2006 to november 10, 2006 return to mozilla-dev-security announcements none during this week.
2006-11-17 - Archive of obsolete content
summary: mozilla.dev.security - november 11, 2006 to november 17, 2006 return to mozilla-dev-security announcements none during this week.
2006-11-24 - Archive of obsolete content
summary: mozilla.dev.security - november 18, 2006 to november 24, 2006 return to mozilla-dev-security announcements none during this week.
2006-12-01 - Archive of obsolete content
summary: mozilla.dev.security - november 25, 2006 to december 1, 2006 return to mozilla-dev-security announcements none during this week.
2006-09-29 - Archive of obsolete content
* * the |height| member of the return value may be * ns_unconstrainedsize, but the |width| member must not be.
2006-11-17 - Archive of obsolete content
the possibility of turning the microsummaryresource object into a xpcom component, which accomplishes this task in a "hacky" manner, was also discussed.
2006-12-08 - Archive of obsolete content
however, the c++ call that's supposed to be invoking the method on the javascript object is returning with 0x80004005 (ns_error_failure).
2006-09-22 - Archive of obsolete content
summary: mozilla.dev.tech.xul - sept 22-29, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-09-29 - Archive of obsolete content
summary: mozilla.dev.tech.xul - sept 22-29, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-10-06 - Archive of obsolete content
summary: mozilla.dev.tech.xul - sept 29-oct 06, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.tech.xul - oct 07-oct 13, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-10-20 - Archive of obsolete content
summary: mozilla.dev.tech.xul - oct 14-oct 20, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-10-27 - Archive of obsolete content
summary: mozilla.dev.tech.xul - oct 21-oct 27, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.tech.xul - oct 28-nov 3, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.tech.xul - nov 4-nov 10, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-11-17 - Archive of obsolete content
summary: mozilla.dev.tech.xul - nov 11-nov 17, 2006 return to mozilla-dev-tech-xul announcements processing instructions are now added to xul document's dom on november 12, 2006, nickolay ponomarev announces the results of the recently fixed bug 319654.
2006-11-24 - Archive of obsolete content
summary: mozilla.dev.tech.xul - nov 18-nov 24, 2006 return to mozilla-dev-tech-xul announcements none during this week.
2006-12-01 - Archive of obsolete content
summary: mozilla.dev.tech.xul - nov 25-dec 01, 2006 return to mozilla-dev-tech-xul announcements none during this week.
NPN_Enumerate - Archive of obsolete content
returns true if the names of the properties and methods were successfully retrieved, otherwise false.
NPN_HasMethod - Archive of obsolete content
returns true if the method exists on the specified object, otherwise false.
NPN_HasProperty - Archive of obsolete content
returns true if the property exists on the specified object, otherwise false.
NPN_IdentifierIsString - Archive of obsolete content
returns true if the identifier is a string identifier, or false otherwise.
NPN_ReleaseObject - Archive of obsolete content
returns nothing.
NPN_ReleaseVariantValue - Archive of obsolete content
returns nothing.
NPN_RemoveProperty - Archive of obsolete content
returns true if the property was removed successfully, otherwise false.
NPN_RetainObject - Archive of obsolete content
returns a pointer back to the same object.
NPN_SetException - Archive of obsolete content
returns nothing.
NPN_SetProperty - Archive of obsolete content
returns true if the value was set successfully, otherwise false.
NPP - Archive of obsolete content
the npp_destroy() function informs the plug-in when the npp instance is about to be deleted; after this call returns, the npp pointer is no longer valid.
Writing a plugin for Mac OS X - Archive of obsolete content
xcode will create a "build" directory next to the project file, and if you built it in release mode, that folder in turn contains a "release" directory with the plugin inside it.
SAX - Archive of obsolete content
tespace) { // don't care }, startprefixmapping: function(prefix, uri) { // don't care }, endprefixmapping: function(prefix) { // don't care }, // nsisupports queryinterface: function(iid) { if(!iid.equals(components.interfaces.nsisupports) && !iid.equals(components.interfaces.nsisaxcontenthandler)) throw components.results.ns_error_no_interface; return this; } }; start parsing the xml reader component can parse xml from a string, an nsiinputstream, or asynchronously via the nsistreamlistener interface.
Introduction to Public-Key Cryptography - Archive of obsolete content
otherwise, the issuer's certificate is checked to make sure it contains the appropriate subordinate ca indication in the red hat certificate type extension, and chain verification returns to step 1 to start again, but with this new certificate.
Theme changes in Firefox 3.5 - Archive of obsolete content
if you don't want the shadow, you can turn it off by setting the new -moz-window-shadow css property to none on the affected element.
Scratchpad - Archive of obsolete content
inspect the inspect option executes the code just like the run option; however, after the code returns, an object inspector is opened to let you examine the returned value.
Developing cross-browser and cross-platform pages - Archive of obsolete content
if there is, the code sees if document.getelementbyid(id_attribute_value) returns a reference to an existing element, which it then checks for a style object.
Using workers in extensions - Archive of obsolete content
observe: function(subject, topic, data) { if (topic != "nspref:changed") { return; } 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.
Displaying notifications (deprecated) - Archive of obsolete content
right now!"); this returns a new notification object, but does not actually display the notification.
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) { return i * i }); numbers.map(i => i * i); [for (i of numbers) i * i]; // all are [1, 4, 9] numbers.filter(function (i) { return i < 3 }); numbers.filter(i => i < 3); [for (i of numbers) if (i < 3) i]; // all are [1, 2] array comprehensions with two arrays using two for-of iterations to work with two arrays: var numbers = [1, 2, 3]; var letters = ['a', 'b', 'c']; var cross = [for (i of numbers) for...
Expression closures - Archive of obsolete content
javascript 1.7 and older: function(x) { return x * x; } javascript 1.8: function(x) x * x this syntax allows you to leave off the braces and 'return' statement - making them implicit.
Function.arity - Archive of obsolete content
the arity property used to return the number of arguments expected by the function, however, it no longer exists and has been replaced by the function.prototype.length property.
Function.prototype.isGenerator() - Archive of obsolete content
syntax fun.isgenerator() return value a boolean indicating whether or not the given function is a generator.
ActiveXObject - Archive of obsolete content
the activexobject object enables and returns a reference to an automation object.
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(); } return(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(); } return(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.
Error.description - Archive of obsolete content
the error.description property returns or sets the descriptive string associated with a specific error.
Error.number - Archive of obsolete content
the error.number property returns or sets the numeric value associated with a specific error.
ScriptEngine() - Archive of obsolete content
syntax scriptengine() remarks the scriptengine function returns "jscript", which indicates that javascript is the current scripting engine.
ScriptEngineBuildVersion - Archive of obsolete content
syntax scriptenginebuildversion() remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use.
ScriptEngineMajorVersion - Archive of obsolete content
syntax scriptenginemajorversion() remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use.
ScriptEngineMinorVersion - Archive of obsolete content
syntax scriptengineminorversion() remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use.
VBArray.getItem - Archive of obsolete content
the vbarray.getitem method returns the item at the specified location.
VBArray.toArray - Archive of obsolete content
the vbarray.toarray method returns a standard javascript array converted from a vbarray.
New in JavaScript 1.1 - Archive of obsolete content
isnan() now works on every platform (not only unix anymore) parsefloat() and parseint() now return nan on all platforms, if the first character of the specified string cannot be converted to a number; in previous releases, it returned nan on solaris and irix and zero on all other platforms.
New in JavaScript 1.8 - Archive of obsolete content
however, that made it impossible to destructure the values of an array - that were arrays (i.e., when an iterator returns an array of the current key-value pair).
Object.getNotifier() - Archive of obsolete content
return value the notifier object associated with the object being passed to the function.
Object.unobserve() - Archive of obsolete content
return value the specified object.
Object.prototype.unwatch() - Archive of obsolete content
return value undefined.
JSObject - Archive of obsolete content
returns a jsobject for the window containing the given applet.
LiveConnect Reference - Archive of obsolete content
jsexception the public class jsexception extends runtimeexception, and is thrown when javascript returns an error.
ParallelArray - Archive of obsolete content
methods map reduce scan scatter filter flatten partition get examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { return v + 1; }); ...
forEach - Archive of obsolete content
if (value>1){ return false;//we could have some way to break when we return 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 return upper case in html and lower case in xhtml.
XForms Switch Module - Archive of obsolete content
the switch element contains case elements which in turn contain markup.
Mozilla XForms User Interface - Archive of obsolete content
the switch element contains case elements which in turn contain markup.
Using XForms and PHP - Archive of obsolete content
returning xml data to either serve a page (with xforms in it) or to generate data used as instance data for xforms, the page needs to be served as xml, for example application/xhtml+xml.
Archived open Web documentation - Archive of obsolete content
iterator the iterator function returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object.
Describing microformats in JavaScript - Archive of obsolete content
if a property is plural, it is returned as an array.
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 return null rather than a reference to the opened window.
RDF in Mozilla FAQ - Archive of obsolete content
these methods return an nsirdfcontainer which allows you to do container-like operations without getting your hands too dirty.
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.
XUL Parser in Python - Archive of obsolete content
for example, you could easily adapt this to: return the id values of all the elements take elements on the command line and only spell them out build new chrome subdirectories (i.e.
Common causes of memory leaks in extensions - Extensions
if (reason == app_shutdown) return; // your add-on needs to unload all modules it ships and imported!
Examples - Game development
the wizard a turn-based, dungeon puzzle game.
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) return 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); return 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) { return {x: x - camera.x, y: y - camera.y}; } function screentoworld(x,y) { return {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.
2D maze game with device orientation - Game development
manageaudio turns the audio on and off.
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...
502 - MDN Web Docs Glossary: Definitions of Web-related terms
"502" means that the upstream server has returned an invalid response.
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 returned when available rather than immediately.
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
the cssom, together with the dom, to build the render tree, which is in turn used by the browser to layout and paint the web page.
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
the function could also include a loop, which iterates through all of the fields in the form, checking each one in turn.
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge definition of the doctype in the html specification quirks mode and standards mode technical reference document.doctype, a javascript method that returns the doctype ...
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
effective connection type (ect) refers to the measured network performance, returning 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.
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 returns that object false && "dog" // ↪ false 0 && "dog" // ↪ 0 specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
access global variables var foo = "foobar"; foo === window.foo; // returns: true after defining a global variable foo, we can access its value directly from the window object, by using the variable name foo as a property name of the global object window.foo.
Grid container - MDN Web Docs Glossary: Definitions of Web-related terms
using the value grid or inline-grid on an element turns it into a grid container using css grid layout, and any direct children of this element become grid items.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
for example: console.log(num); // returns undefined, as only declaration was hoisted, no initialization has happened at this stage var num; // declaration num = 6; // initialization the example below only has initialization.
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 ...
Keyword - MDN Web Docs Glossary: Definitions of Web-related terms
when you use a search engine, you use keywords to specify what you are looking for, and the search engine returns relevant webpages.
Long task - MDN Web Docs Glossary: Definitions of Web-related terms
common examples include long running event handlers, expensive reflows and other re-renders, and work the browser does between different turns of the event loop that exceeds 50 ms.
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
fortunately, since the result will be nan and i know my divisor may turn out to be 0, i can set up testing conditions that prevent any such computations in the first place or notify me of where they happen.
Null - MDN Web Docs Glossary: Definitions of Web-related terms
every object is derived from null value, and therefore typeof operator returns object for it: typeof null === 'object' // true ...
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression — for example making a true statement return false.
Parameter - MDN Web Docs Glossary: Definitions of Web-related terms
output/return parameters primarily return 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 ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
the wrapper's valueof() method returns the primitive value.
Random Number Generator - MDN Web Docs Glossary: Definitions of Web-related terms
truly random numbers (say, from a radioactive source) are utterly unpredictable, whereas all algorithms are predictable, and a prng returns the same numbers when passed the same starting parameters or seed.
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
password=' anything 'or'1'='1 ' the password is not 'anything', hence password=anything results in false, but '1'='1' is a true statement and hence returns a true value.
STUN - MDN Web Docs Glossary: Definitions of Web-related terms
stun returns the ip address, port, and connectivity status of a networked computer behind a nat.
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 returns an <li> element with that string as its textcontent.
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
many programming commands are also synchronous — for example when you type in a calculation, the environment will return the result to you instantly, unless you program it not to.
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
the server sends data in tcp packets, the user's client then confirms delivery by returning acknoledgements, or acks.
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
from version 74 onwards, firefox will return a secure connection failed error when connecting to servers using the older tls versions (bug 1606734).
TOFU - MDN Web Docs Glossary: Definitions of Web-related terms
tofu is used in the ssh protocol, in http public key pinning (hpkp) where the browsers will accept the first public key returned by the server, and in strict-transport-security (hsts) where a browser will obey the redirection rule.
Character - MDN Web Docs Glossary: Definitions of Web-related terms
a character is either a symbol (letters, numbers, punctuation) or non-printing "control" (e.g., carriage return or soft hyphen).
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
don't finish your writing with a carriage return.
MDN Web Docs Glossary: Definitions of Web-related terms
t tag tcp tcp handshake tcp slow start telnet texel thread three js time to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls) tree shaking trident truthy ttl turn type type coercion type conversion u udp (user datagram protocol) ui undefined unicode uri url urn usenet user agent utf-8 ux v validator value variable vendor prefix viewport visual view...
Accessible multimedia - Learn web development
note that to turn the subtitles on, you need to press the "cc" button and select an option — english, deutsch, or español.
Test your skills: HTML accessibility - Learn web development
html accessibility 3 in this task you are required to turn all the information links in the paragraph into good, accessible links.
Test your skills: WAI-ARIA - Learn web development
wai-aria 3 for this final wai-aria task, we return to an example we previously saw in the css and javascript skilltest.
Backgrounds and borders - Learn web development
.box { background: linear-gradient(105deg, rgba(255,255,255,.2) 39%, rgba(51,56,57,1) 96%) center center / 400px 200px no-repeat, url(big-star.png) center no-repeat, rebeccapurple; } we'll return to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in css, by looking at the individual background properties.
Organizing your CSS - Learn web development
a pre-processor runs over your raw files and turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it — perhaps to optimize it in order that it will load faster.
CSS values and units - Learn web development
the value used to return an image from a file — url() — is also a function.
Test your skills: Writing Modes and Logical Properties - Learn web development
task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is turned vertically.
Floats - Learn web development
with the advent of flexbox and grid it has now returned to its original purpose, as this article explains.
Multiple-column layout - Learn web development
when you turn your content into a multicol container it is fragmented into columns, and the content breaks to allow this to happen.
Practical positioning examples - Learn web development
the next subject we'll turn to is flexbox.
CSS layout - Learn web development
with the advent of flexbox and grid it has now returned to its original purpose, as this article explains.
Getting started with CSS - Learn web development
to turn all paragraphs green you would use: p { color: green; } you can target multiple selectors at once, by separating the selectors with a comma.
How CSS is structured - Learn web development
<div class="box"></div> .box { margin: 30px; width: 100px; height: 100px; background-color: rebeccapurple; transform: rotate(0.8turn) } the output from the above code looks like this: look up different values of properties listed below.
How CSS works - Learn web development
in this lesson we will take a look at how a browser takes css and html and turns that into a webpage.
How do you make sure your website works properly? - Learn web development
it turns out that we made a typo in our html code: unicorn_pics.png rather than unicorn_pic.png.
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 returns.
What is a URL? - Learn web development
the web server can use those parameters to do extra stuff before returning the resource.
What is accessibility? - Learn web development
make sure all users can operate graphical interfaces (like unfolding menus) solely with a keyboard (e.g., with tab and the return key).
Advanced form styling - Learn web development
now let's turn our attention to the "ugly" controls — the ones that are really hard to thoroughly style.
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')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; 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(): return render_template('form.html') @app.route('/hello', methods=['get', 'post']) def hello(): return 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 ...
Your first form - Learn web development
this turns a basic text field into a kind of "intelligent" field that will perform some validation checks on the data typed by the user.
Add a hitmap on top of an image - Learn web development
try turning images off.
Use JavaScript within a webpage - Learn web development
people may have javascript turned off to improve speed and security, and users often face network issues that prevent loading scripts.
Test your skills: HTML text basics - Learn web development
html text basics 2 in this task we want you to turn the first un-marked up list into an unordered list, and the second one into an ordered list.
Test your skills: Links - Learn web development
the second link should be turned into a link you can click to open up an email in the user's default mail application, with the recipient set as "whales@example.com".
From object to iframe — other embedding technologies - Learn web development
one important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute — in that case, the embedded content could bypass the same-origin policy that stops sites from executing scripts, and use javascript to turn off sandboxing altogether.
HTML table advanced features and accessibility - Learn web development
returning 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...
Test your skills: Conditionals - Learn web development
inside the first, you need to nest an if...else if...else that puts appropriate messages into the response variable depending on what the value of score is — if the machine is turned on.
Test your skills: Loops - Learn web development
isprime() — a function that, when passed a number, returns true if the number is a prime number, and false if not.
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.
JavaScript First Steps - Learn web development
handling text — strings in javascript next we'll turn our attention to strings — this is what pieces of text are called in programming.
Adding features to our bouncing balls demo - Learn web development
inside the if() statements, if the tests return true we don't want to update velx/vely; we want to instead change the value of x/y so the evil circle is bounced back onto the screen slightly.
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; return num; } this function takes two numbers as arguments, and returns a random number in the range between the two.
Test your skills: Object basics - Learn web development
object basics 3 finally for our object basics assessment, we want you to return to the cat object literal from task #1.
JavaScript — Dynamic client-side scripting - Learn web development
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.
Aprender y obtener ayuda - Learn web development
if you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want.
CSS performance optimization - Learn web development
browsers follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the dom and the cssom trees.
What is web performance? - Learn web development
when you request a url and hit enter / return, the browser finds out where the server is that holds that website's files, establishes a connection to it, and requests the files.
The "why" of web performance - Learn web development
slow content has been shown to lead to site abandonment, with some visitors leaving to never return.
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(); return { 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) { return ( <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?
Starting our Svelte Todo list app - Learn web development
if (warning.code === 'a11y-missing-attribute') return; // let rollup handle all other warnings normally handler(warning); } }), ...
Deployment and next steps - Learn web development
if you liked it, you will also enjoy the return of 'write less, do more' presentation, which rich harris gave at jscamp 2019.
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 returned to the "edit" button.
Vue resources - Learn web development
only what you return from this function is available in your <template>s.
Styling Vue components with CSS - Learn web development
in the next article we'll return to adding some more functionlity to our app, namely using a computed property to add a count of completed todo items to our app.
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 returns using curl's -i flag, and print all the location redirects it sends to the terminal, by piping the output of curl into grep (we will ask grep to return all the lines that contain the word "location").
Client-side tooling overview - Learn web development
turning an intermediate language into javascript that a browser can understand.
Accessibility information for UI designers and developers
to help these users, you could offer a setting to turn off animations, or wrap the css in the prefers-reduce-motion media query.
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 return unique pointers and should be treated as opaque by the caller.
Theme concepts
return; } 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 returned.
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); return 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 + ")"); } return 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 returning # 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) returns 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 return the sandbox/directory back to a clean state.
Callgraph
for instance, given the c++ code: int foo() { return good(); } int good() { return evil() ?
Eclipse CDT
finally, you'd click ok twice to return 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.
Multiple Firefox profiles
hit return.
Storage access policy: Block cookies from trackers
return an empty string for calls to document.cookie and ignore requests to set cookies via document.cookie.
Firefox and the "about" protocol
private window about:profiles display and manage firefox profiles about:protections privacy protections report consisting of enhanced tracking protection, firefox monitor and firefox lockwise data about:restartrequired a page users are sent to when firefox requires a restart due to an update about:reader indicates a web page has firefox reader view turned on.
Firefox
firefox profiles if you find yourself using multiple firefox channels—or just multiple configurations—on a regular basis, you should read how to use multiple firefox profiles by turning firefox's profile manager and other profile management tools to your advantage.
HTMLIFrameElement.addNextPaintListener()
syntax instanceofhtmliframeelement.addnextpaintlistener(listener); returns void.
HTMLIFrameElement.clearMatch()
syntax instanceofhtmliframeelement.clearmatch(); returns void.
HTMLIFrameElement.download()
syntax var instanceofdomrequest = instanceofhtmliframeelement.download(url, options); returns a domrequest for handling the download request.
HTMLIFrameElement.findAll()
syntax instanceofhtmliframeelement.findall(searchstring, casesensitivity); returns void.
HTMLIFrameElement.findNext()
syntax instanceofhtmliframeelement.findnext(direction); return value void.
HTMLIFrameElement.getActive()
syntax var amiactive = instanceofhtmliframeelement.getactive(); returns a boolean indicating whether the current browser <iframe> is the currently active frame (true) or not (false.) parameters none.
HTMLIFrameElement.getCanGoBack()
}); returns a promise that resolves with a boolean that equals true if the history can be navigated backward or false if not.
HTMLIFrameElement.getCanGoForward()
}); returns a promise that resolves with a boolean that equals true if the history can be navigated forward or false if not.
HTMLIFrameElement.getMuted()
}); returns callback version: a domrequest that represents the get muted request.
HTMLIFrameElement.getVisible()
syntax instanceofdomrequest = instanceofhtmliframeelement.getvisible(); returns a domrequest object to handle the getvisible() request's success and error cases.
HTMLIFrameElement.getVolume()
}); returns callback version: a domrequest that represents the get volume request.
HTMLIFrameElement.goBack()
syntax instanceofhtmliframeelement.goback(); returns void.
HTMLIFrameElement.goForward()
syntax instanceofhtmliframeelement.goforward(); returns void.
mozbrowserasyncscroll
details the details property returns an anonymous javascript object with the following properties: top the scroll top position in css pixels of the document within the browser <iframe>.
mozbrowsercaretstatechanged
details the details property returns an anonymous javascript object with the following properties: rect an object that defines information about the bounding rectangle of the current selection.
mozbrowsererror
detail the detail property returns an anonymous javascript object with the following properties: type a domstring representing the type of error that occurred.
mozbrowsericonchange
details the details property returns an anonymous javascript object with the following properties: href a domstring representing the path to the new icon.
mozbrowserloadend
detail the detail property returns an anonymous javascript object with the following properties: backgroundcolor a domstring representing the main background color of the browser <iframe> content, expressed as an rgb value.
mozbrowserlocationchange
detail the detail property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new location.
mozbrowsermanifestchange
details the details property returns an anonymous javascript object with the following properties: href the url of the new app manifest.
mozbrowseropensearch
details the details property returns an anonymous javascript object with the following properties: title a domstring representing the title of the search engine.
mozbrowseropentab
details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded.
mozbrowseropenwindow
details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property.
mozbrowserresize
details the details property returns an anonymous javascript object with the following properties: width a number representing the new width of the <iframe> viewport, in device pixels.
mozbrowserscroll
details the details property returns an anonymous javascript object with the following properties: top a number representing the new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport.
mozbrowserscrollareachanged
details the details property returns an anonymous javascript object with the following properties: width a number representing the new scroll area width of the <iframe> viewport, in css pixels.
mozbrowserscrollviewchange
details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of scrolling in the viewport — available values are started and stopped.
mozbrowsersecuritychange
details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of ssl security.
mozbrowserselectionstatechanged
details the details property returns an anonymous javascript object with the following properties: rect an object that represents the bounding rectangle of the selection.
mozbrowsershowmodalprompt
returnvalue a domstring representing the return value for the window.prompt() methods.
mozbrowserusernameandpasswordrequired
details the details property returns an anonymous javascript object with the following members: host a domstring representing the host requesting the http authentification.
mozbrowservisibilitychange
details the details property returns an anonymous javascript object with the following properties: visible a boolean that indicates whether the browser iframe is visible (true) or not (false).
HTMLIFrameElement.mute()
MozillaGeckoChromeAPIBrowser APImute
syntax instanceofhtmliframeelement.mute(); returns void.
HTMLIFrameElement.purgeHistory()
}); returns either a domrequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not.
HTMLIFrameElement.reload()
syntax instanceofhtmliframeelement.reload(hardreload); returns void.
HTMLIframeElement.removeNextPaintListener()
syntax instanceofhtmliframeelement.removenextpaintlistener(listener); returns void.
HTMLIFrameElement.sendMouseEvent()
syntax instanceofhtmliframeelement.sendmouseevent(type, x, y, button, clickcount, modifiers); returns void.
HTMLIFrameElement.sendTouchEvent()
syntax instanceofhtmliframeelement.sendtouchevent(type, x, y, rx, ry, rotationangles, forces, count, modifiers); returns void.
HTMLIFrameElement.setActive()
syntax instanceofhtmliframeelement.setactive(boolean); returns void.
HTMLIFrameElement.setVisible()
syntax instanceofhtmliframeelement.setvisible(visible); returns void.
HTMLIFrameElement.setVolume()
syntax instanceofhtmliframeelement.setvolume(number); returns void.
HTMLIFrameElement.stop()
MozillaGeckoChromeAPIBrowser APIstop
syntax instanceofhtmliframeelement.stop(); returns void.
HTMLIFrameElement.unmute()
syntax instanceofhtmliframeelement.unmute(); returns void.
HTMLIFrameElement.zoom()
MozillaGeckoChromeAPIBrowser APIzoom
syntax var instanceofdomrequest = instanceofhtmliframeelement.zoom(zoomfactor); returns void.
CSS -moz-bool-pref() @supports function
syntax -moz-bool-pref( <string> ) parameters <string> the preference name returns evaluates to true if the preference is enabled, false otherwise.
Embedding the editor
editor incorrectly rooted the editor in a composer window is current owned by the nseditorshell, which in turn is created, owned and destroyed by the nseditorboxobject.
Roll your own browser: An embedding how-to
original document information author(s): doug turner original document: , , and last updated date: december 8, 2004 copyright information: copyright (c) doug turner ...
Gecko SDK
the gecko sdk, also known as the xulrunner sdk, is a set of xpidl files, headers and tools to develop xpcom components which can then in turn e.g.
How Mozilla determines MIME Types
if no ext-to-type-mapping category is found, the externalhelperappservice returns application/x-extension-ext, where ext is the extension of the file.
How to get a stacktrace for a bug report
you can prefix a "bp-" to the beginning of an id to make bugzilla turn it into a link: bp-a70759c6-1295-4160-aa30-bc4772090918 how to get the crash id if firefox crashes on startup if firefox crashes on startup you can still access your submitted crash reports.
PBackground
instead, it simply turns all of its operations into ipdl calls on a set of pbackground-based actors and the processing, file i/o, etc, can be controlled from the pbackground thread regardless of where the dom calls are being made.
Addon
getdatadirectory() requires gecko 32.0(firefox 32.0 / thunderbird 32.0 / seamonkey 2.29) returns the path of the preferred directory, within the current profile, where an add-on should store data files.
AddonUpdateChecker
ion of the add-on to get new compatibility information for ignorecompatibility an optional parameter to get the first compatibility update that is compatible with any version of the application or toolkit appversion the version of the application or null to use the current version platformversion the version of the platform or null to use the current version getnewestcompatibleupdate() returns the newest available update from a list of update objects.
Assert.jsm
returns a promise that resolves when the promise either resolves or rejects.
API-provided widgets
should return the dom node that has been constructed.
DownloadTarget
if the download is in progress or has been finalized, this method does nothing and returns a resolved promise.
Downloads.jsm
observer notifications (for example, "dl-done") and download listeners are replaced by views on the downloadlist object returned by the getlist() method.
Deferred
a deferred object is returned by the promiseutils.defer() method to provide a new promise along with methods to change its state.
PromiseUtils.jsm
return 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() { return "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 return 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.
Mozilla Framework Based on Templates (MFBT)
the function macros control inlining, note whether a function returns, and enforce various c++-related restrictions on inheritance and use.
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 Web Developer FAQ
however, it turns out mozilla is doing that already.
Mozilla Development Strategies
maybe the problem can be turned into an assert, or fixed altogether.
Mozilla Style System Documentation
these methods may all return 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 returned 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 returns for tmpd/ns_os_temp_dir).
Measuring performance using the PerfMeasurement.jsm code module
since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured.
Profile Manager
ability to reset a profile (return it to a default state excluding bookmarks and passwords).
Localization Use Cases
first, there is devicestoragehelper.showformatedsize (sic): function showformatedsize(element, l10nid, size) { if (size === undefined || isnan(size)) { element.textcontent = ''; return; } // kb - 3 kb (nearest ones), mb, gb - 1.2 mb (nearest tenth) var fixeddigits = (size < 1024 * 1024) ?
Midas
insertbronreturn true/false selects whether pressing return inside a paragraph creates another paragraph or just inserts a <br> tag.
Dynamic Library Linking
prlibrary *lib; void *funcptr; funcptr = pr_findsymbolandlibrary("functionname", &lib); when pr_findsymbolandlibrary returns, funcptr is the value of the function pointer you want to look up, and the variable lib references the main executable program.
Monitors
a call to pr_wait temporarily returns the entry count to zero.
PLHashEnumerator
syntax #include <plhash.h> typedef printn (pr_callback *plhashenumerator)(plhashentry *he, printn index, void *arg); /* return value */ #define ht_enumerate_next 0 /* continue enumerating entries */ #define ht_enumerate_stop 1 /* stop enumerating entries */ #define ht_enumerate_remove 2 /* remove and free the current entry */ #define ht_enumerate_unhash 4 /* just unhash the current entry */ description plhashenumerator is a function type used in the enumerating a hash table.
PLHashNumber
plhashnumber is the data type of the return value of a hash function.
PL_CompareValues
syntax #include <plhash.h> printn pl_comparevalues(const void *v1, const void *v2); description pl_comparevalues compares the two void * values v1 and v2 numerically, i.e., it returns the value of the expression v1 == v2.
PL_HashString
returns the hash number for the specified key.
PL_HashTableEnumerateEntries
returns the number of entries enumerated.
PL_NewHashTable
returns the new hash table.
PL_strcpy
returns the function returns a pointer to the buffer specified by the dest parameter.
PRCallOnceFN
the function is expected to return a prstatus indicating the outcome of the process.
PRDir
the function pr_opendir opens a specified directory and returns a pointer to a prdir structure, which can be passed to pr_readdir repeatedly to obtain successive entries (files or subdirectories in the open directory).
PRExplodedTime
when an nspr function returns a prexplodedtime object or sets a prexplodedtime object as output, all of the prexplodedtime members are set, including the nonessential members.
PRHostEnt
all addresses are passed in host order and returned in network order (suitable for use in system calls).
PRIntervalTime
they indicate that the process should wait no time (return immediately) or wait forever (never time out), respectively.
PRLibrary
a reference to such a structure can be returned by some of the functions in the runtime and serve to identify a particular instance of a library.
PRProtoEnt
protocol entry returned by pr_getprotobyname and pr_getprotobynumber.
PRStatus
type for status code returned by some functions.
PRThread
the identifier remains valid until it returns from its root function and, if the thread was created joinable, is joined.
PRThreadScope
the scope of an nspr thread, specified as a parameter to pr_createthread or returned by pr_getthreadscope.
PRThreadType
pr_system_thread nspr ignores threads of type pr_system_thread when determining when a call to pr_cleanup should return.
PRTimeParameters
in pdt, the clock is turned forward by one hour, so the local time is 7 hours behind gmt.
PR_ASSERT
returns nothing description this macro evaluates the specified expression.
PR_Access
returns one of the following values: if the requested access is permitted, pr_success.
PR_Assert
returns nothing description this function displays data in the log.
PR_AtomicAdd
returns the returned value is the result of the addition.
PR_AtomicIncrement
returns the function returns the incremented value (i.e., the result).
PR_AttachThread
returns the function returns one of these values: if successful, a pointer to a prthread object.
PR_Bind
returns the function returns one of the following values: upon successful binding of an address to a socket, pr_success.
PR_CALLBACK
the pr_callback attribute is included as part of the function's definition between its return value type and the function's name.
PR_CExitMonitor
returns the function returns one of the following values: if successful, pr_success.
PR_CLIST_IS_EMPTY
description pr_clist_is_empty returns a non-zero value if the specified list is an empty list, otherwise returns zero.
PR_CNotify
returns pr_success indicates that the calling thread is the holder of the mutex for the monitor referred to by the address parameter.
PR_CNotifyAll
returns pr_success indicates that the referenced monitor was located and the calling thread was in the monitor.
PR_CallOnce
it should return a prstatus indicating the result of the initialization process.
PR_CloseFileMap
returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success.
PR_Connect
returns the function returns one of the following values: upon successful completion of connection setup, pr_success.
PR ConvertIPv4AddrToIPv6
v6addr a pointer to a buffer, allocated by the caller, that is filled in with the ipv6 address on return.
PR_CreateThreadPool
returns pointer to a prthreadpool structure or null on error.
PR_Delete
returns one of the following values: if file is deleted successfully, pr_success.
PR_DeleteSemaphore
returns prstatus ...
PR_DestroyPollableEvent
returns the function returns one of the following values: if successful, pr_success.
PR_ExitMonitor
returns the function returns one of the following values: if successful, pr_success.
PR_ExportFileMapAsString
returns prstatus description creates an identifier, as a string, from a prfilemap object previously created with pr_openanonfilemap.
PR_Free
returns nothing.
PR_FreeLibraryName
returns nothing.
PR GetAddrInfoByName
include pr_ai_nocanonname to suppress the determination of the canonical name corresponding to hostname returns the function returns one of the following values: if successful, a pointer to the opaque praddrinfo structure containing the results of the host lookup.
PR_GetDefaultIOMethods
syntax #include <prio.h> const priomethods* pr_getdefaultiomethods(void); returns if successful, the function returns a pointer to a priomethods structure.
PR_GetErrorText
returns the actual number of bytes copied.
PR_GetIdentitiesLayer
returns the function returns one of the following values: if successful, a pointer to a file descriptor of the layer with the specified identity in the given stack of layers.
PR_GetInheritedFileMap
returns pointer to prfilemap or null on error.
PR_GetLayersIdentity
returns if successful, the function returns the prdescidentity for the layer of the specified file descriptor.
PR_GetOpenFileInfo
returns the function returns one of the following values: if file information is successfully obtained, pr_success.
PR_GetOpenFileInfo64
returns the function returns one of the following values: if file information is successfully obtained, pr_success.
PR_GetSocketOption
returns if successful, pr_success.
PR_GetThreadPriority
returns the priority of a specified thread.
PR_GetThreadPrivate
returns null if the data has not been set.
PR_GetThreadScope
syntax #include <prthread.h> prthreadscope pr_getthreadscope(void); returns a value of type prthreadscope indicating whether the thread is local or global.
PR_ImportFileMapFromString
returns prfilemap pointer or null on error.
PR_InitializeNetAddr
returns the function returns one of the following values: if successful, pr_success.
PR_Initialized
syntax #include <prinit.h> prbool pr_initialized(void); returns the function returns one of the following values: if pr_init has already been called, pr_true.
PR_IntervalToMicroseconds
returns equivalent in microseconds of the value passed in the ticks parameter.
PR_IntervalToMilliseconds
returns equivalent in milliseconds of the value passed in the ticks parameter.
PR_IntervalToSeconds
returns equivalent in seconds of the value passed in the ticks parameter.
PR_JoinThreadPool
returns prstatus ...
PR_LOG
returns nothing description this macro formats the specified arguments and writes the output to the log file, if logging is enabled for the specified module and level.
PR_LOG_TEST
possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug returns pr_true when logging is enabled for the given module and level, otherwise pr_false.
PR_Lock
description when pr_lock returns, the calling thread is "in the monitor," also called "holding the monitor's lock." any thread that attempts to acquire the same lock blocks until the holder of the lock exits the monitor.
PR_LogFlush
returns nothing description this function flushes the log buffer to external media.
PR_LogPrint
returns nothing description this function unconditionally writes a message to the log using the specified format string.
PR_MicrosecondsToInterval
returns platform-dependent equivalent of the value passed in the micro parameter.
PR_MillisecondsToInterval
returns platform-dependent equivalent of the value passed in the milli parameter.
PR_MkDir
returns if successful, pr_success.
PR_NOT_REACHED
returns nothing description this macro writes the specified reason string to the log and terminates the application.
PR_NetAddrToString
returns the function returns one of the following values: if successful, pr_success.
PR_NewCondVar
returns the function returns one of the following values: if successful, a pointer to the new condition variable object.
PR_NewLock
syntax #include <prlock.h> prlock* pr_newlock(void); returns the function returns one of the following values: if successful, a pointer to the new lock object.
PR_NewLogModule
returns a pointer to a prlogmoduleinfo structure.
PR_NewMonitor
syntax #include <prmon.h> prmonitor* pr_newmonitor(void); returns the function returns one of the following values: if successful, a pointer to a prmonitor object.
PR_NewPollableEvent
returns pointer to prfiledesc or null, on error.
PR_NewTCPSocket
syntax #include <prio.h> prfiledesc* pr_newtcpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened ipv4 tcp socket.
PR_NewUDPSocket
syntax #include <prio.h> prfiledesc* pr_newudpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
PR_Notify
returns the function returns one of the following values: if successful, pr_success.
PR_NotifyAll
returns the function returns one of the following values: if successful, pr_success.
PR_NotifyAllCondVar
syntax #include <prcvar.h> prstatus pr_notifyallcondvar(prcondvar *cvar); returns the function returns one of the following values: if successful, pr_success.
PR_NotifyCondVar
returns the function returns one of the following values: if successful, pr_success.
PR_OpenSemaphore
returns a pointer to a prsem structure or null/code> on error.
PR_OpenTCPSocket
returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened tcp socket.
PR OpenUDPSocket
returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
PR_ProcessAttrSetInheritableFileMap
returns prstatus description pr_processattrsetinheritablefilemap connects the prfilemap to prprocessattr with shmname.
PR_QueueJob
returns pointer to a prjob structure or null on error.
PR_QueueJob_Accept
returns pointer to a prjob structure or null on error.
PR_QueueJob_Connect
returns pointer to a prjob structure or null on error.
PR_QueueJob_Read
returns pointer to a prjob structure or null on error.
PR_QueueJob_Timer
returns pointer to a prjob structure or null on error.
PR_QueueJob_Write
returns pointer to a prjob structure or null on error.
PR_Read
returns one of the following values: a positive number indicates the number of bytes actually read in.
PR_Recv
returns the function returns one of the following values: a positive number indicates the number of bytes actually received.
PR_Rename
returns one of the following values: if file is successfully renamed, pr_success.
PR_STATIC_ASSERT
returns nothing description this macro evaluates the specified expression.
PR_SecondsToInterval
returns platform-dependent equivalent of the value passed in the seconds parameter.
PR_Send
returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent.
PR_SendTo
returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent.
PR_SetError
the runtime merely stores the value and returns it when requested.
PR_SetLibraryPath
returns the function returns one of the following values: if successful, pr_success.
PR_SetLogBuffering
returns nothing description this function sets the size of the buffer used in nspr logging.
PR_SetLogFile
returns pr_true when successful.
PR_SetPollableEvent
returns the function returns one of the following values: if successful, pr_success.
PR_SetSocketOption
returns if successful, pr_success.
PR_Shutdown
returns the function returns one of the following values: upon successful completion of shutdown request, pr_success.
PR_ShutdownThreadPool
returns prstatus ...
PR_Sleep
returns calling pr_sleep with a parameter equivalent to pr_interval_no_timeout is an error and results in a pr_failure error.
PR_StringToNetAddr
returns the function returns one of the following values: if successful, pr_success.
PR_Sync
returns the function returns one of the following values: on successful completion, pr_success.
PR_TransmitFile
returns a positive number indicates the number of bytes successfully written, including both the headers and the file.
PR_Unlock
returns the function returns one of the following values: if successful, pr_success.
PR_VersionCheck
returns the function returns one of the following values: if the version of the shared library is compatible with that expected by the caller, pr_true.
PR_Wait
returns the function returns one of the following values: pr_success means the thread is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired.
PR_WaitCondVar
returns the function returns one of the following values: if successful, pr_success.
PR_cnvtf
on return, the result is written to the buffer pointed to by buf of size bufsz.
PR_htonl
returns the value of the conversion parameter in network byte order.
PR_htons
returns the value of the conversion parameter in network byte order.
PR_ntohl
returns the value of the conversion parameter in host byte order.
PR_ntohs
returns 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 return values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities controlling per-thread private data interrupting and yielding setting global thread concurrency getting a thread's scope process initialization identity and versioning name and version constants initializat...
NSS CERTVerify Log
on return: log->count is the number of entries.
CERT_FindCertByDERCert
returns a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found.
CERT_FindCertByIssuerAndSN
returns 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_importderprivatekeyinfoandreturnkey mxr 3.4 and later pk11_importencryptedprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfoandreturnkey 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 returns the result data.
HTTP delegation
one might expect the api defines a simple function that accepts the uri and data to be sent, and returns the result data.
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
ssl_getclientauthdatahook sets a callback to return the local certificate for ssl client auth.
JSS 4.4.0 Release Notes
bugs fixed in jss 4.4.0 this bugzilla query returns 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 return 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 return 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 returns 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 returns 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 returns 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) return 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 return 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returning from a function.
NSS Sample Code sample3
*/ if (key) pk11_freesymkey(key); if (slot) pk11_freeslot(slot); return status; } ...
NSS Sample Code sample5
* publicvalue arg (4th) can be null for rsa key - i think it is even * ignored */ pk11_importderprivatekeyinfoandreturnkey(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 return.
nss tech note7
the returned public key may be used after the certificate is destroyed.
NSS Tools sslstrength
for example, ciphers=bfi will turn on these cipher preferences and turn off all others.
NSS release notes template
bugs fixed in nss 3.xx this bugzilla query returns all the bugs fixed in nss 3.xx: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.xx (make a link) acknowledgements the nss development team would like to thank ...
FC_CloseAllSessions
return value examples see also fc_closesession, nsc_closeallsessions ...
FC_CloseSession
return value examples see also fc_opensession ...
FC_CopyObject
return value examples see also fc_destroyobject, nsc_copyobject ...
FC_CreateObject
return value examples see also fc_destroyobject, nsc_createobject ...
FC_Decrypt
return value examples see also fc_decryptinit, nsc_decrypt ...
FC_DecryptDigestUpdate
return value examples see also nsc_decryptdigestupdate ...
FC_DecryptInit
return value examples see also nsc_decryptinit ...
FC_DecryptUpdate
return value examples see also fc_decryptinit, nsc_decryptupdate ...
FC_DecryptVerifyUpdate
return value examples see also nsc_decryptverifyupdate ...
FC_DeriveKey
return value examples see also nsc_derivekey ...
FC_DestroyObject
return value examples see also nsc_destroyobject ...
FC_Digest
return value examples see also fc_digestinit, nsc_digest ...
FC_DigestEncryptUpdate
return value examples see also nsc_digestencryptupdate ...
FC_DigestInit
return value examples see also nsc_digestinit ...
FC_Encrypt
return value examples see also fc_encryptinit, nsc_encrypt ...
FC_EncryptInit
return value ckr_ok slot information was successfully copied.
FC_EncryptUpdate
return value examples see also fc_encryptinit, nsc_encryptupdate ...
FC_FindObjectsFinal
return value examples see also fc_findobjects, nsc_findobjectsfinal ...
FC_FindObjectsInit
return value examples see also fc_findobjects, nsc_findobjectsinit ...
FC_GenerateRandom
return value examples see also nsc_generaterandom ...
FC_GetAttributeValue
return value examples see also nsc_getattributevalue ...
FC_GetFunctionList
return value fc_getfunctionlist always returns ckr_ok.
FC_GetMechanismInfo
return value ckr_ok examples see also nsc_getmechanisminfo ...
FC_GetMechanismList
return value ckr_ok examples see also nsc_getmechanismlist ...
FC_GetObjectSize
return value examples see also nsc_getobjectsize ...
FC_GetOperationState
return value examples see also fc_setoperationstate, nsc_getoperationstate ...
FC_GetSlotInfo
return value ckr_ok slot information was successfully copied.
FC_GetSlotList
return value ckr_ok examples see also nsc_getslotlist ...
FC_InitPIN
return value fc_initpin() returns the following return codes.
FC_InitToken
return value fc_inittoken() returns the following return codes.
FC_Logout
return value examples see also fc_closesession, nsc_logout ...
FC_OpenSession
return value examples see also fc_closesession, nsc_opensession ...
FC_SeedRandom
return value examples see also nsc_seedrandom ...
FC_SetAttributeValue
return value examples see also nsc_setattributevalue ...
FC_SetOperationState
return value examples see also fc_getoperationstate, nsc_setoperationstate ...
FC_SetPIN
return value ckr_ok examples see also nsc_setpin ...
FC_Sign
return value examples see also fc_signinit, nsc_sign ...
FC_SignEncryptUpdate
return value examples see also nsc_signencryptupdate ...
FC_SignInit
return value examples see also nsc_signinit fc_sign fc_signupdate fc_signfinal ...
FC_SignRecoverInit
return value examples see also nsc_signrecoverinit ...
FC_VerifyFinal
return value examples see also fc_verifyupdate, nsc_verifyfinal ...
FC_VerifyInit
return value examples see also nsc_verifyinit ...
FC_VerifyRecoverInit
return value examples see also nsc_verifyrecoverinit ...
FC_WaitForSlotEvent
return value fc_waitforslotevent always returns ckr_function_not_supported.
NSC_InitToken
return value nsc_inittoken() returns the following return codes.
NSPR functions
the nspr function pr_now returns the current time in prtime.
NSS_Initialize
return value nss_initialize returns secsuccess on success, or secfailure on failure.
NSS cryptographic module
the standard pkcs #11 function c_getfunctionlist or the equivalent nsc_getfunctionlist function returns pointers to the functions that implement the default mode of operation.
NSS functions
mxr 3.2 and later pk11_hasrootcerts mxr 3.4 and later pk11_importcert mxr 3.5 and later pk11_importcertforkeytoslot mxr 3.2 and later pk11_importcrl mxr 3.6 and later pk11_importdercert mxr 3.6 and later pk11_importderprivatekeyinfoandreturnkey mxr 3.4 and later pk11_importencryptedprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfoandreturnkey mxr 3.4 and later pk11_importpublickey mxr 3.4 and later pk11_importsymkeywithflags mxr 3.4...
gtstd.html
each slot for a pkcs #11 module can in turn contain a token, which is the hardware or software device that actually provides cryptographic services and optionally stores certificates and keys.
sslintro.html
brings an ordinary nspr socket into the ssl library, returning a new nspr socket that can be used to make ssl calls.
NSS Tools certutil-tasks
sorting by trust will return ca certs first.
NSS Tools modutil
a complex string must notinclude newlines or carriage returns.) outside of complex strings, all white space (for example, spaces, tabs, and carriage returns) is considered equal and is used only to delimit tokens.
NSS Tools pk12util
error codes pk12util can return the following values: 0 - no error 1 - user cancelled 2 - usage error 6 - nls init error 8 - certificate db open error 9 - key db open error 10 - file initialization error 11 - unicode conversion error 12 - temporary file creation error 13 - pkcs11 get slot error 14 - pkcs12 decoder start error 15 - error read from import file 16 - pkcs12 decode error 17 - pkcs12 decoder verify error 18 - pkcs12 ...
NSS Tools sslstrength
for example, ciphers=bfi will turn on these cipher preferences and turn off all others.
The JavaScript Runtime
the generated bytecodes in turn depend upon runtime support routines.
Rhino scopes and contexts
that context will be returned and an internal counter incremented.
GCIntegration - SpiderMonkey Redirect 1
this will return a jsobject *.
Bytecodes
there are also some slots reserved for dedicated functionality, holding values like this and the callee / return value.
Garbage collection
typically, a weak pointer value has a get() method that returns a null pointer if the object has been gc'd.
SpiderMonkey Internals: Thread Safety
thread-safety in spidermonkey is turned on by compiling with -djs_threadsafe.
JS::AutoSaveExceptionState
return ok; see also mxr id search for js::autosaveexceptionstate js_saveexceptionstate js_restoreexceptionstate js_dropexceptionstate bug 972319 ...
JS::Call
on success, *rval receives the return value from the function call.
JS::CompileOffThread
if maybecx is not specified, the resources will be freed, but no script will be returned.
JS::CreateError
if successful, js::createerror stores the created error object to *rval and returns true, otherwise returns false and the value of *rval is undefined.
JS::DeflateStringToUTF8Buffer
examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx, js_newucstringcopyn(cx, uchars, 2)); if (!str) return false; js::rooted<jsflatstring*> flatstr(cx, js_flattenstring(cx, str)); if (!flatstr) return false; size_t length = js::getdeflatedutf8stringlength(flatstr); char* buffer = static_cast<char*>(js_malloc(cx, length + 1)); if (!buffer) return false; js::deflatestringtoutf8buffer(flatstr, mozilla::rangedptr<char>(buffer, length)); buffer[length] = '\0'; printf("utf8: [%s]\n", buffer); js_free(...
JS::DoubleNaNValue
syntax js::value js::doublenanvalue() description js::doublenanvalue returns a value of type js::value that represents an ieee floating-point quiet not-a-number (nan).
JS::ObjectOrNullValue
if the pointer is null, it returns javascript null.
JS::PropertySpecNameEqualsId
description js::propertyspecnameequalsid determines if the given jspropertyspec::name or jsfunctionspec::name value equals the given jsid, and returns true if so.
JS::PropertySpecNameIsSymbol
description js::propertyspecnameissymbol determines if the given jspropertyspec::name or jsfunctionspec::name value is actually a symbol code and not a string, and returns true if so.
JS::SetOutOfMemoryCallback
if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out-of-memory callback is only called if the allocation still fails after the large-allocation-failure callback has returned.
JS::ToBoolean
it implements the toboolean operation described in ecma 262 §7.1.2.this function can not fail and the return value is always the boolean conversion of the argument.
JSBool
jsbool is the return type of many jsapi functions and callbacks.
JSCheckAccessOp
description check whether obj[id] may be accessed per mode, returning 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) return false; myprinter *p = new myprinter; if (p == null) { js_reportoutofmemory(cx); return false; } js_setprivate(cx, obj, p); args.rval().setobject(*obj); /* spidermonkey 31 or older * js_set_rval(cx, vp, object_to_jsval(obj)); */ return 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, returned by js_reporterrornumber function.
JSExceptionState
syntax struct jsexceptionstate; description a jsexceptionstate object is returned by the js_saveexceptionstate function, and is passed to functions js_restoreexceptionstate and js_dropexceptionstate.
JSFreeOp
methods method description jsruntime *runtime() const returns a pointer to jsruntime passed to constructor.
JSHasInstanceOp
return 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 returns 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 returns true if it's an integer.
JSID_IS_STRING
description jsid_is_string tests whether a specified js id, id, is a string, and returns 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 returns true if it's a js symbol.
JSID_VOID
a void jsid is not a valid id and only arises as an exceptional api return value, such as in js_nextproperty.
JSIteratorOp
the callback should return 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 returns a jsproperty pointer, the property is locked.
JSObjectOps.getAttributes
returns js_false on error or exception, else js_true with current attributes in *attrsp.
JSPrincipals
obsolete since jsapi 13 getprincipalarray void * (*)(jscontext *, jsprincipals *) pointer to the function that returns an array of principal definitions.
JSVAL_IS_OBJECT
syntax jsbool jsval_is_object(jsval v); description jsval_is_object(v) returns true if v is either an object or jsval_null.
JSVAL_TO_STRING
(the difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) to convert the return type of this macro (jsstring *) to a char pointer, use js_getstringbytes.
JS_BindCallable
if callable is not callable, will throw and return nullptr.
JS_CStringsAreUTF8
js_cstringsareutf8 returns js_true if the javascript engine is configured (either at compile time or at run time) to interpret char strings as utf-8.
JS_CheckForInterrupt
js_checkforinterrupt returns false if interrupt callback returns false.
JS_ClearRegExpStatics
on successful, js_clearregexpstatics returns true, otherwise returns false.
JS_DoubleIsInt32
2(double d, int32_t *ip); name type description d double a double value to compare ip int32_t * a pointer to int32_t value to compare description js_doubleisint32 returns true if d i sequal to *ip.
JS_EnumerateResolvedStandardClasses
return the augmented array on success, null on failure with ida (if it was non-null on entry) destroyed.
JS_ExecuteRegExp
if successful, js_executeregexp and js_newregexpobjectnostatics returns true and stores the result to *rval, otherwise returns false and the value of *rval is undefined see also mxr id search for js_executeregexp mxr id search for js_executeregexpnostatics regexp bug 571355 - added js_executeregexpnostatics function ...
JS_FORGET_STRING_FLATNESS
syntax static moz_always_inline jsstring * js_forget_string_flatness(jsflatstring *fstr) { return (jsstring *)fstr; } name type description fstr jsflatstring * a string to convert description js_forget_string_flatness converts jsflatstring * to jsstring *.
JS_FileEscapedString
if successful, js_fileescapedstring returns true, otherwise false.
JS_GET_CLASS
description js_get_class returns a pointer to the jsclass associated with a specified js object, obj.
JS_GetClassObject
if successful, js_getclassobject stores the class constructor to *objp and returns true, otherwise returns false and the value of *objp is undefined.
JS_GetClassPrototype
if successful, js_getclassprototype stores the class prototype object to *objp and returns true, otherwise returns false and the value of *objp is undefined.
JS_GetEmptyStringValue
description js_getemptystringvalue returns the empty string as a js::value.
JS_GetExternalStringFinalizer
description js_getexternalstringfinalizer returns the fin parameter passed to js_newexternalstring.
JS_GetFunctionArity
description js_getfunctionarity returns the number of formal parameters of a function, fun.
JS_GetImplementationVersion
syntax const char * js_getimplementationversion(void); description js_getimplementationversion returns a hard-coded, english language string that specifies the version number of the js engine currently in use, and its release date.
JS_GetLatin1FlatStringChars
description js_getlatin1flatstringchars and js_gettwobyteflatstringchars return a pointer to the string.
JS_GetLatin1InternedStringChars
if successful, js_getlatin1stringcharsandlength and js_gettwobytestringcharsandlength return a pointer to the string, otherwise return null.
JS_GetLatin1StringCharsAndLength
if successful, js_getlatin1stringcharsandlength and js_gettwobytestringcharsandlength return a pointer to the string, and store the length to *length, otherwise return null.
JS_GetLocaleCallbacks
js_getlocalecallbacks returns the address of the current locale callbacks struct, which may be nullptr.
JS_GetOptions
this function returns a uint32 value that is the logical or of zero or more of the jsoption flags described in js_setoptions.
JS_GetOwnPropertyDescriptor
description js_getownpropertydescriptor and js_getownpropertydescriptorbyid get a detailed description of that property (returned in desc->obj).
JS_GetParentRuntime
if the cx's runtime has no parent runtime, js_getparentruntime returns cx's runtime itself.
JS_GetPropertyDescriptor
description js_getpropertydescriptor and js_getpropertydescriptorbyid find a specified property of an object and gets a detailed description of that property on the prototype chain (returned in desc->obj).
JS_GetReservedSlot
they cannot be returned from functions, set as properties on objects, embedded in javascript arrays, and so on.) new objects' reserved slots are initialized to undefined.
JS_GetStringCharsAndLength
description js_getstringcharsandlength gets the characters and the length of the string, str if successful, js_getstringcharsandlength returns a pointer to the string, and store the length to *length, otherwise returns null see also bug 1037869 ...
JS_GetStringEncodingLength
description js_getstringencodinglength returns the length of the specified string in bytes, regardless of its encoding.
JS_GetTwoByteExternalStringChars
js_gettwobyteexternalstringchars always succeeds, and returns a pointer to the string.
JS_GetVersion
description js_getversion returns the javascript version currently used by the given jscontext, cx.
JS_Init
syntax #include "js/initialization.h" // previously "jsapi.h" bool js_init(void); description initialize spidermonkey, returning true only if initialization succeeded.
JS_InitStandardClasses
js_initstandardclasses returns js_true on success, and js_false if an error occurs.
JS_IsAssigning
syntax jsbool js_isassigning(jscontext *cx); name type description description js_isassigning returns true if a script is executing and its current bytecode is a set (assignment) operation, even if there are native (no script) stack frames between the script and the caller to js_isassigning.
JS_IsExtensible
if successful, js_isextensible stores [[extensible]] property to *extensible and returns true, otherwise returns false and the value of *extensible is undefined.
JS_IsExternalString
description js_isexternalstring returns true if the string is an external string; otherwise it's false.
JS_IsGlobalObject
description js_isglobalobject returns true if obj is a global object, false otherwise.
JS_IsNative
description js_isnative returns true if the object is a native object.
JS_IsStopIteration
description js_isstopiteration returns true if v is stopiteration, otherwise false.
JS_IterateCompartments
beware that there is no guarantee that the compartment will survive after the callback returns.
JS_LinkConstructorAndPrototype
on successful, js_linkconstructorandprototype returns true.
JS_LooselyEqual
if the comparison attempt was successful, the method returns js_true and stores the result in *equal; otherwise it returns js_false.
JS_MakeStringImmutable
(when an application shares a string by storing it in a javascript object that another thread can read, the javascript engine automatically makes the string thread-safe.) after a successful call to js_makestringimmutable, subsequent calls to js_getstringcharsz on the same string are guaranteed to succeed, and subsequent calls to js_getstringchars on the same string are guaranteed to return a null-terminated string.
JS_NewDateObject
description creates and returns a new jsobject representing a javascript date object, which is pre-configured using the specified values.
JS_NewDateObjectMsec
description the returned jsobject is a standard javascript date.
JS_NewExternalString
this must be an id number previously returned by a successful call to js_addexternalstringfinalizer.
JS_NewObjectForConstructor
if the constructor does not have a prototype property, this function will return null and set an exception on cx.
JS_Now
syntax int64_t js_now(void); description js_now returns microseconds since the epoch, midnight, january 1, 1970 utc.
JS_ObjectIsDate
this function returns true if the object is a date.
JS_ParseJSON
this article covers features introduced in spidermonkey 1.8.6 parse a string using the json syntax described in ecmascript 5 and return the corresponding value.
JS_PopArguments
description js_poparguments frees the stack frame pointer previously allocated by js_pusharguments and unroots the jsvals which have been associated with it (those returned by js_pusharguments as well).
JS_RemoveExternalStringFinalizer
description remove finalizer from the global gc finalizers table, returning its type code if found, -1 if not found.
JS_Remove*Root
js_removeroot always returns js_true.
JS_RemoveRootRT
js_removerootrt always returns js_true.
JS_ReportError
the callback must then return js_false to cause the exception to be propagated to the calling script.
JS_SET_TRACING_DETAILS
the storage for name or callback's arguments needs to live only until the following call to js_calltracer returns.
JS_SetCheckObjectAccessCallback
js_setcheckobjectaccesscallback returns the previous check-object-access callback.
JS_SetErrorReporter
js_seterrorreporter js_geterrorreporter returns the value set by js_seterrorreporter.
JS_SetInterruptCallback
(in this case, the callback may terminate the script by returning false.) js_getinterruptcallback returns the currently installed interrupt callback, or null if none is currently installed.
JS_SetObjectPrincipalsFinder
js_setobjectprincipalsfinder returns the previous object-principals-finder callback.
JS_SetPendingException
a native function or hook using this to throw an exception must also return false to ensure the exception is thrown.
JS_SetPrincipalsTranscoder
js_setprincipalstranscoder returns the previous principals transcoder.
JS_SetRegExpInput
on successful, js_setregexpinput returns true, otherwise returns false.
JS_SetVersion
js_setversion returns the js version in effect for the context before you changed it.
JS_StrictlyEqual
if the comparison attempt was successful, the method returns true and stores the result in *equal; otherwise it returns false.
JS_StringHasBeenInterned
description js_stringhasbeeninterned returns true if the string str is interned.
JS_StringHasLatin1Chars
description js_stringhaslatin1chars returns true iff the string's characters are stored as latin1.
JS_StringIsFlat
description js_stringisflat returns true if the string is flattened.
Stored value
es5 accessor properties, as in {get length() { return 0; }, automatically have jsprop_shared.
jsid
a void jsid is not a valid id and only arises as an exceptional api return value, such as in js_nextproperty.
JSDBGAPI
_frameiterator js_getframescript js_getframepc js_getscriptedcaller js_stackframeprincipals js_evalframeprincipals js_getframeannotation js_setframeannotation js_getframeprincipalarray js_isnativeframe js_getframeobject js_getframescopechain js_getframecallobject js_getframethis js_getframefunction js_getframefunctionobject js_isconstructorframe js_isdebuggerframe js_getframereturnvalue js_setframereturnvalue js_getframecalleeobject js_getscriptfilename js_getscriptbaselinenumber js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags js_getscriptfilenameflags js_flagscriptfilenameprefix jsfilename_null jsfilename_system jsfilename_protected evaluating debug code js_evaluateinstackframe examining object properties typedef jspro...
SpiderMonkey 1.8.7
this means that the int_fits_in_jsval macro is always returns true (be careful to only use this macro with jsints, not 64-bit integers).
Running Automated JavaScript Tests
for a smoke test or if you are not changing language-level functionality, you may wish to use jstests.py path_to_js_shell --exclude=test262 other options allow you to show the test command lines being run, command output and return codes, run tests named in a given file, exclude tests named in a given file, hide the progress bar, change the timeout, run skipped tests, print output in tinderbox format, run a test in the debugger, or run tests in valgrind.
SavedFrame
function properties of the savedframe.prototype object tostring return this frame and its parents formatted as a human readable stack trace string.
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 return 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.
Using the Places livemark service
getsiteuri() returns null if there is no uri for the specified livemark.
places.sqlite Database Troubleshooting
sqlite> .clone places.sqlite sqlite> pragma user_version; note the version number returned by the last pragma query.
Building the WebLock UI
« previousnext » copyright (c) 2003 by doug turner and ian oeschger.
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()); return; } 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 return 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 return 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 returned 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) { return 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.
Components.utils.importGlobalProperties
cu.import() will return the full global of a code module.
Components.utils.isXrayWrapper
returns true if the object is an xray: false otherwise.
Components.utils.reportError
components.utils.reporterror reports a javascript error object to the error console, and returns.
Components.utils.unwaiveXrays
returns the object with xrays restored.
XPConnect wrappers
this case is where a js object was passed in via some idl-declared interface, creating an xpcwrappedjs, and is now being returned to javascript via some other interface.
nsLocalFile
createinstance(components.interfaces.nsilocalfile); file.initwithpath(path); return file.filesize; } see also components, nsicomponentmanager ...
Standard XPCOM components
this service returns the locations of "well known" directories in an os-independent manner.
NS_Free
it is equivalent to calling free on the nsimemory instance returned from ns_getmemorymanager.
Length
« xpcom api reference summary the length function returns the number of storage units in the string's internal buffer (not including the null-terminator if present).
Length
« xpcom api reference summary the length function returns the number of storage units in the string's internal buffer (not including the null-terminator if present).
get
« xpcom api reference summary the get function returns a const pointer to the string's null-terminated, internal buffer.
nsEmbedCString
get the get function returns a const pointer to the string's null-terminated, internal buffer.
get
« xpcom api reference summary the get function returns a const pointer to the string's null-terminated, internal buffer.
nsEmbedString
get the get function returns a const pointer to the string's null-terminated, internal buffer.
nsMemory
getglobalmemoryservice the getglobalmemoryservice function returns a reference to xpcom's global nsimemory object.
IJSDebugger
on return, the debugger object has been added to the global context.
imgIDecoder
return value the number of bytes actually written to the image, or undefined if an error occurred.
mozIJSSubScriptLoader
if the script returns a value, it will be returned by this method.
mozIPersonalDictionary
return value true if the word is in either the dictionary or the ignore list, false if it is not in either list.
mozIRegistry
there's another component that turns out to also be real important when you go to hook up your code with other mozilla components.
mozIStorageBindingParamsArray
newbindingparams() creates and returns a new, empty, mozistoragebindingparams object to which you can add parameters and their values for binding.
mozIStorageError
the mozistorageerror interface represents errors returned by the storage api, offering attributes to obtain the error code as well as a human-readable error message corresponding to the error that occurred.
mozIStorageProgressHandler
return value return true to abort the request or false to allow it to continue.
mozIStorageStatementWrapper
return value returns true if the stepping the wrapped statement was successful, otherwise returns false.
FirstChild
« nsiaccessible page summary returns first child node in accessible tree.
GetActionDescription
return value returns the description of the accessible action.
GetActionName
return value returns the name of the accessible action.
GetBounds
« nsiaccessible page summary this method returns accessible's (x and y) coordinates relative to the screen and accessible's width and height.
GetKeyBindings
return values returns array of localized string of global keyboard accelerator.
GroupPosition
« nsiaccessible page summary this method returns grouping information.
LastChild
« nsiaccessible page summary returns last child node in accessible tree.
NextSibling
« nsiaccessible page summary returns next sibling in accessible tree.
Parent
« nsiaccessible page summary returns parent node in accessible tree.
PreviousSibling
« nsiaccessible page summary returns previous node in accessible tree.
RelationsCount
« nsiaccessible page summary returns the number of accessible relations for this object.
nsIAccessibleCaretMoveEvent
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) attributes attribute type description caretoffset long return caret offset.
nsIAccessibleEditableText
ext(in long startpos, in long endpos); void inserttext(in astring text, in long position); void pastetext(in long position); void setattributes(in long startpos, in long endpos, in nsisupports attributes); unimplemented void settextcontents(in astring text); attributes attribute type description associatededitor nsieditor returns an editor associated with the accessible.
nsIAuthModule
unwrap() this method is used to unpack, decrypt, and verify the checksums on data returned by a server when security layers are in use.
nsIAuthPromptAdapterFactory
return value an nsiauthprompt2.
nsIBadCertListener2
return value the consumer shall return true if it wants to suppress the error message related to the bad cert (the connection will still get canceled).
nsIBoxObject
methods getlookandfeelmetric() obsolete since gecko 1.9 (firefox 3) wstring getlookandfeelmetric( in wstring propertyname ); parameters propertyname return value getproperty() wstring getproperty( in wstring propertyname ); parameters propertyname return value getpropertyassupports() nsisupports getpropertyassupports( in wstring propertyname ); parameters propertyname return value removeproperty() void removeproperty( in wstring propertyname ); parameters propertyname setproperty() void setproperty( in wstring propertyname, ...
nsIBrowserHistory
for performance reasons this does not return the real number of entries.
nsICacheEntryInfo
return value returns true if the cache entry is stream based, otherwise returns false.
nsICacheMetaDataVisitor
return value returns true if the provided key/value finds a cache entry, otherwise returns false.
nsIClipboardDragDropHookList
return value returns nsisimpleenumerator for nsiclipboarddragdrophooks.
nsICookiePromptService
return value returns 0 for denying a cookie, 1 for accepting a cookie, and 2 for accepting cookie for the current session only.
nsICycleCollectorListener
if begin() returns an error none of the other functions will be called.
nsIDBChangeListener
ator) {}, onjunkscorechanged: function(ainstigator) {}, onhdrpropertychanged: function(ahdrtochange, aprechange, astatus, ainstigator) {}, onevent: function(adb, aevent) {}, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsidbchangelistener) && !aiid.equals(components.interfaces.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; and to attach it in thunderbird, we must call addlistener on a nsidbchangeannouncer, typically through a nsimsgdatabase.
nsIDNSListener
void onlookupcomplete( in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus ); parameters arequest the value returned from asyncresolve.
nsIDOMChromeWindow
title domstring obsolete since gecko 1.9.1 windowstate unsigned short returns current window state, the value is one of state_* constants.
nsIDOMEventGroup
return value returns true if the two objects are the same, otherwise false.
nsIDOMFontFace
it's returned in a list you can get using inidomutils.getusedfontfaces().
nsIDOMGeoGeolocation
return value an id number that can be used to reference the watcher in the future when calling clearwatch().
nsIDOMHTMLMediaElement
dom/interfaces/html/nsidomhtmlmediaelement.idlscriptable the basis for the nsidomhtmlaudioelement and nsidomhtmlvideoelement interfaces, which in turn implement the <audio> and <video> html5 elements.
nsIDOMSerializer
return value the serialized subtree in the form of a unicode string.
nsIDataSignatureVerifier
return value true if the signature matches the data, false if not.
getFiles
return values the elements of the returned nsisimpleenumerator instance must support nsifile and may support nsilocalfile.
nsIDragSession
return value true if the specified flavor matches any of the native data on the clipboard, otherwise false.
nsIException
return value a string suitable for output.
nsIExternalURLHandlerService
return value an nsihanderinfo for the protocol.
nsIFactory
unlike getservice, this returns a new instance each time it is called.
nsIFeed
subtitle nsifeedtextconstruct returns a subtitle for the feed, based on its description, subtitle, and appropriate extensions.
nsIFeedContainer
note: the returned 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 return value getint() long getint( in autf8string key ); parameters key return value getstring() autf8string getstring( in autf8string key ); parameters key return 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 return value ...
nsIGeolocationProvider
return value true if the device is ready and has a position available to return; otherwise false.
nsIGlobalHistory
return value true if a page has been passed into addpage().
nsIGlobalHistory2
return value true if a uri has been visited.
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 ( ) { return 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,...
nsIInProcessContentFrameMessageManager
return value the nsicontent object representing the owner's content.
nsIInterfaceRequestor
the main difference is that interfaces returned are not required to provide a way back to the object implementing nsiinterfacerequestor.
nsIJumpListItem
return value true if items are the same, otherwise false ...
nsILocale
return value the locale code to be used for the given category.
nsIMenuBoxObject
return value true if the event was handled, false if not.
nsIMimeHeaders
methods extractheader() string extractheader( [const] in string headername, in boolean getallofthem ); parameters headername missing description getallofthem missing description return 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\") return true; return 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
return value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded.
nsIMsgSearchSession
countsearchscopes() long countsearchscopes(); getnthsearchscope() void getnthsearchscope(in long which, out nsmsgsearchscopevalue scopeid, out nsimsgfolder folder); parameters which return values scopeid folder addscopeterm() add a scope (e.g.
nsIMsgSendLater
return value the nsimsgfolder containing unsent messages.
nsIMsgWindow
if set to an alias, the actual character set is returned.
nsIMutableArray
conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value.
nsINavBookmarkObserver
queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsinavbookmarkobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_error_no_interface; } see also places manipulating bookmarks using places nsinavbookmarksservice ...
nsINavHistoryObserver
queryinterface: function(iid) { if (iid.equals(ci.nsinavhistoryobserver) || iid.equals(ci.nsinavhistoryobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_error_no_interface; } see also nsinavhistoryresult ...
nsINavHistoryQueryResultNode
methods getqueries() returns the queries that build the node's children; only valid for result_type_query nodes.
nsINavHistoryResult
changing this value updates the corresponding options for the result so that reusing the current options and queries will always return results based on the current view.
nsINetworkLinkService
note: as of gecko 8.0, all operating systems currently return link_type_unknown.
nsIPrefLocalizedString
return value returns wstring - the string containing the data stored within this object.
nsIProfileLock
toolkit/profile/public/nsitoolkitprofile.idlscriptable an object returned by the nsitoolkitprofile.lock method; as long as you hold a reference to the object, the profile remains locked.
nsIProfileUnlocker
profile/public/nsiprofileunlocker.idlscriptable returned by the nsitoolkitprofile.lock method; you can use this to attempt to force a profile to be unlocked.
nsIProtocolProxyFilter
return value the proxy (or list of proxies) that should be used in place of aproxy.
nsIPushMessage
when called from javascript, nsipushmessage.binary() returns data.
nsISSLErrorListener
return value the consumer shall return true if it wants to suppress the error message related to the error (the connection will still get canceled).
nsISeekableStream
return value the current offset, in bytes, from the start of the stream.
nsIServerSocketListener
the address of the client can be found by calling the nsisockettransport.getaddress() method or by inspecting nsisockettransport.gethost(), which returns a string representation of the client's ip address, which may be either an ipv4 or an ipv6 address.
nsISessionStartup
return value true if the session should be restored, otherwise false.
nsISocketTransportService
return value an nsisockettransport containing the sockettransport.
nsIStackFrame
return value a string suitable for output.
nsIStyleSheetService
return value returns true if a style sheet at sheeturi has previously been added to the list of style sheets specified by type.
nsISupportsVoid
return value a string valued representation of the object.
nsISupportsWeakReference
return value the resulting nsiweakreference instance.
nsISyncJPAKE
it returns a key confirmation value (sha256d of the key) and the encryption and hmac keys.
nsITaskbarTabPreview
return value the hwnd for the preview's proxy window.
nsIThreadEventFilter
return value implement this method to return true if the event is accepted, or false to reject it.
nsIThreadPool
when this method returns, the thread pool and all its threads will have been shut down, and it is no longer be possible to dispatch events to the thread pool.
nsIUUIDGenerator
return value this method returns a nsidptr containing a unique id.
nsIUpdateItem
objectsource astring returns a js object source representing an nsiupdateitem.
nsIUpdatePatch
return value the patch object serialized into an nsidomelement.
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 return value ...
nsIWebNavigation
this attribute never returns null except for unexpected error situations.
nsIWebProgressListener2
return value true if the refresh may proceed.
nsIWebappsSupport
return 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 return value ...
nsIWinAppHelper
returns 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 returns false.
nsIWindowCreator
return value an nsiwebbrowserchrome for the new window.
nsIWorkerGlobalScope
onerror nsidomeventlistener self nsiworkerglobalscope returns 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 returns 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 returns 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 returns string, you dont want arraybuffer.
nsIXPCException
return 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.
nsIXULBrowserWindow
return value a string indicating the revised target for the link.
nsIXULBuilderListener
example create an object which implements nsixulbuilderlistener: var mylistener = { queryinterface: function(aiid) { if (aiid.equals(components.interfaces.nsixulbuilderlistener) || aiid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, willrebuild : function(builder) {}, didrebuild : function(builder) { } } attach the listener to a element: myelement.addlistener(mylistener); ...
nsIXULRuntime
returns one of process type constants.
nsIXmlRpcFault
xml-rpc server fault codes are returned wrapped in this; access it using nsixpconnect.getpendingexception->data.
nsPIPromptService
the pressed button number will be returned.
NS_ENSURE_ARG_POINTER
summary macro returns ns_error_invalid_pointer if the macro argument evaluates to false and shows a warning (ns_warning) in this case.
NS_StringContainerFinish
return values this function does not return a value.
nsMsgMessageFlags
not returned in header.flags.
nsStaticModuleInfo
getmodule this member provides a function pointer of type nsgetmoduleproc that returns a nsimodule instance.
xptcall FAQ
this code also does the platform specific cleanup as the call returns.
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
MozillaTechXPIDLxpidl
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
MozillaTechXULOverlays
(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.
DB Views (message lists)
nsmsggroupview is used when grouping is turned on.
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 returned 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) return "false"; else return "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); return 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"); return retval; }, getsortstringforrow: function(hdr) { return hdr.getstringproperty("x-superfluous"); }, isstring: function() {return true;}, getcellproperties: function(row, col, props){}, getimagesrc: function(row, col) {return null;}, getsortlongforrow: function(hdr) {return 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; return 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 returned by nsixulappinfo.
Zombie compartments
return 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 returning 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 returned 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 return 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 return only nodes whose names are exactly "tab".
DOM Inspector internals - Firefox Developer Tools
this comparison turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser.
Set watch expressions - Firefox Developer Tools
as you step through code, the debugger will watch the expression and return any results.
Set a conditional breakpoint - Firefox Developer Tools
press return to finish.
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').return); } }); 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 return 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) { return 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 &lt; namelength; j++) { name += chars[randomint(0, chars.length-1)]; } return name; } this.name = randomname(); this.eyecount = randomint(0, 25); this.tentaclecount = rando...
Network request details - Firefox Developer Tools
clicking the icon at the right-hand end of the toolbar closes the details pane and returns you to the list view.
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) { return; } 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) { return; } if (e.target.id != "icon") { return; } 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 return.): 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.
Allocations - Firefox Developer Tools
this in turn can hurt the responsiveness of a page.
Call Tree - Firefox Developer Tools
to do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn.
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 returns 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...
Tips - Firefox Developer Tools
$$() returns an array with the results from document.queryselectorall().
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 return enter add a new line, for entering multiline expressions shift + enter shift + return shift + enter autocomplete popup these shortcuts apply while the autocomplete popup is open: command windows macos linux choose the current autocomplete suggestion tab tab tab cancel the autocomplete popup esc esc esc mo...
about:debugging (before Firefox 68) - Firefox Developer Tools
the "enable add-on debugging" button works by turning on the devtools.chrome.enabled and devtools.debugger.remote-enabled preferences.
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.drawArraysInstancedANGLE() - Web APIs
return value none.
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
return value none.
ANGLE_instanced_arrays.vertexAttribDivisorANGLE() - Web APIs
return value none.
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 returns a glint describing the frequency divisor used for instanced rendering when used in the gl.getvertexattrib() as the pname parameter.
AbortController.abort() - Web APIs
return value void.
AbortController.signal - Web APIs
the signal read-only property of the abortcontroller interface returns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired.
AbortController - Web APIs
properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request.
AbortSignal.aborted - Web APIs
the aborted read-only property returns a boolean that indicates whether the dom request(s) the signal is communicating with is/are aborted (true) or not (false).
AbstractRange.collapsed - Web APIs
the collapsed read-only property of the abstractrange interface returns true if the range's start position and end position are the same.
AbstractRange.endContainer - Web APIs
the endcontainer property of the abstractrange interface returns the node in which the end of the range is located.
AbstractRange.endOffset - Web APIs
the endoffset property of the abstractrange interface returns the offset into the end node of the range's end position.
AbstractRange.startContainer - Web APIs
the read-only startcontainer property of the abstractrange interface returns the start node for the range.
AbstractRange.startOffset - Web APIs
the read-only startoffset property of the abstractrange interface returns the offset into the start node of the range's start position.
AbstractRange - Web APIs
as it turns out, the dom specification fortunately addresses this exact issue.
Accelerometer.Accelerometer() - Web APIs
the accelerometer constructor creates a new accelerometer object which returns the acceleration of the device along all three axes at the time it is read.
Accelerometer.x - Web APIs
WebAPIAccelerometerx
the x read-only property of the accelerometer interface returns a double precision integer containing the acceleration of the device along the its x axis.
Accelerometer.y - Web APIs
WebAPIAccelerometery
the y read-only property of the accelerometer interface returns a double precision integer containing the acceleration of the device along the its y axis.
Accelerometer.z - Web APIs
WebAPIAccelerometerz
the z read-only property of the accelerometer interface returns a double precision integer containing the acceleration of the device along the its z axis.
AddressErrors.addressLine - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.city - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.dependentLocality - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.languageCode - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.phone - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.postalCode - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.recipient - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.region - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.regionCode - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AddressErrors.sortingCode - Web APIs
the returned string explains the error and should offer suggestions for how to correct it.
AmbientLightSensor.AmbientLightSensor() - Web APIs
the ambinentlightsensor() constructor creates a new ambientlightsensor object, which returns the current light level or illuminance of the ambient light around the hosting device.
AmbientLightSensor.illuminance - Web APIs
the illuminance property of the ambientlightsensor interface returns the current light level in lux of the ambient light level around the hosting device.
Ambient Light Sensor API - Web APIs
interfaces ambientlightsensor returns an interface for accessing ambientlightsensorreadings.
AnalyserNode.AnalyserNode() - Web APIs
return value a new analysernode object instance.
AnalyserNode.maxDecibels - Web APIs
when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of maxdecibels or higher will be returned as +1.0 or 255, respectively.
AnalyserNode.minDecibels - Web APIs
when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of mindecibels or lower will be returned as 0.0 or 0, respectively.
Animation() - Web APIs
the animation() constructor of the web animations api returns a new animation object instance.
Animation.cancel() - Web APIs
WebAPIAnimationcancel
return value none.
Animation.commitStyles() - Web APIs
return value none.
Animation.id - Web APIs
WebAPIAnimationid
the animation.id property of the web animations api returns or sets a string used to identify the animation.
Animation.pause() - Web APIs
WebAPIAnimationpause
return value none.
Animation.persist() - Web APIs
WebAPIAnimationpersist
return value none.
Animation.play() - Web APIs
WebAPIAnimationplay
return value undefined example in the growing/shrinking alice game example, clicking or tapping the cake causes alice's growing animation (alicechange) to play forward, causing her to get bigger, as well as triggering the cake's animation.
Animation.playState - Web APIs
the animation.playstate property of the web animations api returns and sets an enumerated value describing the playback state of an animation.
Animation.playbackRate - Web APIs
the animation.playbackrate property of the web animations api returns or sets the playback rate of the animation.
Animation.ready - Web APIs
WebAPIAnimationready
the read-only animation.ready property of the web animations api returns a promise which resolves when the animation is ready to play.
Animation.replaceState - Web APIs
the read-only animation.replacestate property of the web animations api returns the replace state of the animation.
Animation.reverse() - Web APIs
WebAPIAnimationreverse
return value undefined example in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to play backwards, causing her to get smaller.
Animation.startTime - Web APIs
*/ function addcat(){ var newcat = document.createelement("div"); newcat.classlist.add("cat"); return newcat; } /* this is the function that adds a cat to the waapi column */ function animatenewcatwithwaapi() { // make a new cat var newcat = addcat(); // animate said cat with the waapi's "animate" function var newanimationplayer = newcat.animate(keyframes, timing); // set the animation's start time to be the same as the original .cat#withwaapi newanimationplayer.starttime = catrunn...
Animation.timeline - Web APIs
the animation.timeline property of the animation interface returns or sets the timeline associated with this animation.
Animation.updatePlaybackRate() - Web APIs
return value none.
AnimationEffect.updateTiming() - Web APIs
return value none.
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
the animationplaybackevent() constructor of the web animations api returns a new animationplaybackevent object instance.
AnimationTimeline.currentTime - Web APIs
the currenttime read-only property of the web animations api's animationtimeline interface returns the timeline's current time in milliseconds, or null if the timeline is inactive.
AnimationTimeline - Web APIs
properties animationtimeline.currenttime read only returns the time value in milliseconds for this timeline or null if this timeline is inactive.
Attr.prefix - Web APIs
WebAPIAttrprefix
the attr.prefix read-only property returns the namespace prefix of the specified attribute, or null if no prefix is specified.
AudioBuffer() - Web APIs
return value a new audiobuffer object instance.
AudioBuffer.copyFromChannel() - Web APIs
return value undefined.
AudioBuffer.duration - Web APIs
the duration property of the audiobuffer interface returns a double representing the duration, in seconds, of the pcm data stored in the buffer.
AudioBuffer.length - Web APIs
the length property of the audiobuffer interface returns an integer representing the length, in sample-frames, of the pcm data stored in the buffer.
AudioBuffer.numberOfChannels - Web APIs
the numberofchannels property of the audiobuffer interface returns an integer representing the number of discrete audio channels described by the pcm data stored in the buffer.
AudioBuffer.sampleRate - Web APIs
the samplerate property of the audiobuffer interface returns a float representing the sample rate, in samples per second, of the pcm data stored in the buffer.
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
return value a new audiobuffersourcenode object instance.
AudioBufferSourceNode.detune - Web APIs
syntax var source = audioctx.createbuffersource(); source.detune.value = 100; // value in cents note: though the audioparam returned is read-only, the value it represents is not.
AudioBufferSourceNode.loopEnd - Web APIs
syntax audiobuffersourcenode.loopend = endoffsetinseconds; var endoffsetinseconds = audiobuffersourcenode.loopend; value a floating-point number indicating the offset, in seconds, into the audio buffer at which each loop will loop return to the beginning of the loop (that is, the current play time gets reset to audiobuffersourcenode.loopstart).
AudioBufferSourceNode.start() - Web APIs
return value undefined.
AudioBufferSourceNode - Web APIs
number of inputs 0 number of outputs 1 channel count defined by the associated audiobuffer constructor audiobuffersourcenode() creates and returns a new audiobuffersourcenode object.
AudioContext() - Web APIs
return value the newly constructed audiocontext instance.
AudioContext.baseLatency - Web APIs
the baselatency read-only property of the audiocontext interface returns a double that represents the number of seconds of processing latency incurred by the audiocontext passing an audio buffer from the audiodestinationnode — i.e.
AudioContext.createMediaElementSource() - Web APIs
returns a mediaelementaudiosourcenode.
AudioContext.createMediaStreamDestination() - Web APIs
syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); returns a mediastreamaudiodestinationnode.
AudioContext.createMediaStreamSource() - Web APIs
return value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream.
AudioContext.resume() - Web APIs
return value a promise that resolves when the context has resumed.
AudioContext.suspend() - Web APIs
}); returns a promise that resolves with void.
AudioListener.setOrientation() - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setorientation(0,0,-1,0,1,0); returns void.
AudioListener.setPosition() - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setposition(1,1,1); returns void.
AudioNode.context - Web APIs
WebAPIAudioNodecontext
the read-only context property of the audionode interface returns the associated baseaudiocontext, that is the object representing the processing graph the node is participating in.
AudioNode.disconnect() - Web APIs
syntax audionode.disconnect(); audionode.disconnect(output); audionode.disconnect(destination); audionode.disconnect(destination, output); audionode.disconnect(destination, output, input); return value undefined parameters there are several versions of the disconnect() method, which accept different combinations of parameters to control which nodes to disconnect from.
AudioNode.numberOfInputs - Web APIs
the numberofinputs property of the audionode interface returns the number of inputs feeding the node.
AudioNode.numberOfOutputs - Web APIs
the numberofoutputs property of the audionode interface returns the number of outputs coming out of the node.
AudioParam.cancelAndHoldAtTime() - Web APIs
return value a reference to the audioparam it was called on.
AudioScheduledSourceNode.stop() - Web APIs
return value undefined exceptions invalidstatenode the node has not been started by calling start().
AudioTrack.sourceBuffer - Web APIs
the read-only audiotrack property sourcebuffer returns 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.
AudioTrackList.length - Web APIs
the read-only audiotracklist property length returns the number of entries in the audiotracklist, each of which is an audiotrack representing one audio track in the media element.
AudioWorkletNode() - Web APIs
return value the newly constructed audioworkletnode instance.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
the authenticatordata property of the authenticatorassertionresponse interface returns an arraybuffer containing information from the authenticator such as the relying party id hash (rpidhash), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator.
AuthenticatorAssertionResponse - Web APIs
the authenticatorassertionresponse interface of the web authentication api is returned by credentialscontainer.get() when a publickeycredential is passed, and provides proof to a service that it has a key pair and that the authentication request is valid and approved.
AuthenticatorAttestationResponse.attestationObject - Web APIs
the attestationobject property of the authenticatorattestationresponse interface returns an arraybuffer containing the new public key, as well as signature over the entire attestationobject with a private key that is stored in the authenticator when it is manufactured.
AuthenticatorResponse.clientDataJSON - Web APIs
examples function arraybuffertostr(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } // pk is a publickeycredential that is the result of a create() or get() promise var clientdatastr = arraybuffertostr(pk.clientdatajson); var clientdataobj = json.parse(clientdatastr); console.log(clientdataobj.type); // "webauthn.create" or "webauthn.get" console.log(clientdataobj.challenge); // base64 encoded string containing the o...
AuthenticatorResponse - Web APIs
the child interfaces include information from the browser such as the challenge origin and either may be returned from publickeycredential.response.
BaseAudioContext.audioWorklet - Web APIs
the audioworklet read-only property of the baseaudiocontext interface returns an instance of audioworklet that can be used for adding audioworkletprocessor-derived classes which implement custom audio processing.
BaseAudioContext.createAnalyser() - Web APIs
syntax var analysernode = baseaudiocontext.createanalyser(); returns an analysernode.
BaseAudioContext.createBiquadFilter() - Web APIs
syntax baseaudiocontext.createbiquadfilter(); returns a biquadfilternode.
BaseAudioContext.createBuffer() - Web APIs
returns an audiobuffer configured based on the specified options.
BaseAudioContext.createChannelMerger() - Web APIs
returns a channelmergernode.
BaseAudioContext.createChannelSplitter() - Web APIs
returns a channelsplitternode.
BaseAudioContext.createConstantSource() - Web APIs
returns a constantsourcenode instance.
BaseAudioContext.createConvolver() - Web APIs
syntax baseaudiocontext.createconvolver(); returns a convolvernode.
BaseAudioContext.createDelay() - Web APIs
returns a delaynode.
BaseAudioContext.createDynamicsCompressor() - Web APIs
syntax baseaudioctx.createdynamicscompressor(); returns a dynamicscompressornode.
BaseAudioContext.createGain() - Web APIs
syntax var gainnode = audiocontext.creategain(); return value a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's gainnode.gain a-rate parameter.
BaseAudioContext.createIIRFilter() - Web APIs
return value an iirfilternode implementing the filter with the specified feedback and feedforward coefficient arrays.
BaseAudioContext.createOscillator() - Web APIs
syntax var oscillatornode = audioctx.createoscillator(); returns an oscillatornode.
BaseAudioContext.createPanner() - Web APIs
syntax baseaudioctx.createpanner(); returns a pannernode.
BaseAudioContext.createPeriodicWave() - Web APIs
syntax var wave = audiocontext.createperiodicwave(real, imag[, constraints]); returns a periodicwave.
BaseAudioContext.createScriptProcessor() - Web APIs
returns a scriptprocessornode.
BaseAudioContext.createStereoPanner() - Web APIs
syntax baseaudiocontext.createstereopanner(); returns a stereopannernode.
BaseAudioContext.currentTime - Web APIs
the currenttime read-only property of the baseaudiocontext interface returns a double representing an ever-increasing hardware timestamp in seconds that can be used for scheduling audio playback, visualizing timelines, etc.
BaseAudioContext.destination - Web APIs
the destination property of the baseaudiocontext interface returns an audiodestinationnode representing the final destination of all audio in the context.
BaseAudioContext.listener - Web APIs
the listener property of the baseaudiocontext interface returns an audiolistener object that can then be used for implementing 3d audio spatialization.
BaseAudioContext.sampleRate - Web APIs
the samplerate property of the baseaudiocontext interface returns a floating point number representing the sample rate, in samples per second, used by all nodes in this audio context.
BaseAudioContext.state - Web APIs
the state read-only property of the baseaudiocontext interface returns the current state of the audiocontext.
BatteryManager.charging - Web APIs
syntax var charging = battery.charging on return, charging indicates whether or not the battery, which is a batterymanager object, is currently being charged; if the battery is charging, this value is true.
BatteryManager - Web APIs
the navigator.getbattery() method returns a battery promise that is resolved in a batterymanager interface which you can use to interact with the battery status api.
Battery Status API - Web APIs
the battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status.
BeforeInstallPromptEvent.prompt() - Web APIs
returns an empty promise.
BiquadFilterNode() - Web APIs
return value a new biquadfilternode object instance.
BiquadFilterNode.Q - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not.
BiquadFilterNode.detune - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; note: though the audioparam returned is read-only, the value it represents is not.
BiquadFilterNode.frequency - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam returned is read-only, the value it represents is not.
BiquadFilterNode.gain - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam returned is read-only, the value it represents is not.
BiquadFilterNode.getFrequencyResponse() - Web APIs
return value undefined exceptions invalidaccesserror the three arrays provided are not all of the same length.
BiquadFilterNode - Web APIs
note: though the audioparam objects returned are read-only, the values they represent are not.
Blob.size - Web APIs
WebAPIBlobsize
the blob interface's size property returns the size of the blob or file in bytes.
Blob.type - Web APIs
WebAPIBlobtype
the type property of a blob object returns the mime type of the file.
BlobEvent.BlobEvent() - Web APIs
the blobevent() constructor returns a newly created blobevent object with an associated blob.
Bluetooth.referringDevice - Web APIs
the bluetooth.referringdevice attribute of the bluetooth interface returns a bluetoothdevice if the current document was opened in response to an instruction sent by this device and null otherwise.
BluetoothAdvertisingData.appearance - Web APIs
the appearance read-only property of the bluetoothadvertisingdata interface returns one of the values defined by the org.bluetooth.characteristic.gap.appearance characteristic.
manufacturerData - Web APIs
the manufacturerdata read-only property of the bluetoothadvertisingdata interface returns a map that relates company identifier codes to arraybuffers.
rssi - Web APIs
the rssi read-only property of the bluetoothadvertisingdata interface returns the power at which the device’s packets are being received, measured in dbm.
serviceData - Web APIs
the servicedata read-only property of the bluetoothadvertisingdata interface returns a map that relates uuids to arraybuffers.
txPower - Web APIs
the txpower read-only property of the bluetoothadvertisingdata interface returns the transmission power at which the device is broadcasting, measured in dbm.
BluetoothCharacteristicProperties.authenticatedSignedWrites - Web APIs
the authenticatedsignedwrites read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if signed writing to the characteristic value is permitted.
BluetoothCharacteristicProperties.broadcast - Web APIs
the broadcast read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if the broadcast of the characteristic value is permitted using the server characteristic configuration descriptor.
BluetoothCharacteristicProperties.indicate - Web APIs
the indicate read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if indications of the characteristic value with acknowledgement is permitted.
BluetoothCharacteristicProperties.notify - Web APIs
the notify read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted.
BluetoothCharacteristicProperties.read - Web APIs
the read read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if the reading of the characteristic value is permitted.
BluetoothCharacteristicProperties.reliableWrite - Web APIs
the reliablewrite read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if reliable writes to the characteristic is permitted.
BluetoothCharacteristicProperties.writableAuxiliaries - Web APIs
the writableauxiliaries read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if reliable writes to the characteristic descriptor is permitted.
BluetoothCharacteristicProperties.write - Web APIs
the write read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if the writing to the characteristic with response is permitted.
BluetoothCharacteristicProperties.writeWithoutResponse - Web APIs
the writewithoutresponse read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if the writing to the characteristic without response is permitted.
BluetoothDevice.uuids - Web APIs
syntax var uuids[] =​ instanceofbluetoothdevice.uuids returns an array.
BluetoothRemoteGATTServer.connect() - Web APIs
}) returns a promise that resolves to a bluetoothremotegattserver.
BluetoothRemoteGATTServer.connected - Web APIs
the bluetoothremotegattserver.connected read-only property returns a boolean value that returns true while this script execution environment is connected to this.device.
BluetoothRemoteGATTServer.device - Web APIs
the bluetoothremotegattserver.device read-only property returns a reference to the bluetoothdevice running the server.
BluetoothRemoteGATTServer.disconnect() - Web APIs
syntax bluetoothremotegattserver.disconnect() returns none.
BroadcastChannel.name - Web APIs
the read-only broadcastchannel.name property returns a domstring, which uniquely identifies the given channel with its name.
BroadcastChannel - Web APIs
broadcastchannel.name read only returns a domstring, the name of the channel.
BudgetState.budgetAt - Web APIs
the budgetat read-only property of the budgetstate interface returns the anticipated processing budget at the specified time.
BudgetState.time - Web APIs
WebAPIBudgetStatetime
the time read-only property of the budgetstate interface returns a timestamp at which the budgetat value is valid.
ByteLengthQueuingStrategy - Web APIs
methods bytelengthqueuingstrategy.size() returns the given chunk’s bytelength property.
ByteString - Web APIs
bytestring maps to a string when returned in javascript; generally, it's only used when interfacing with protocols that use bytes and strings interchangably, such as http.
CSS.escape() - Web APIs
WebAPICSSescape
the css.escape() static method returns a cssomstring containing the escaped string passed as parameter, mostly for use as part of a css selector.
CSS.registerProperty() - Web APIs
return value undefined.
CSSGroupingRule - Web APIs
it has one specific property: cssgroupingrule.cssrules read only returns a cssrulelist of the css rules in the media rule.
CSSImageValue - Web APIs
we then get() the background-image from the stylemap and stringify it: // get the element const button = document.queryselector( 'button' ); // retrieve all computed styles with computedstylemap() const allcomputedstyles = button.computedstylemap(); // return the cssimagevalue example console.log( allcomputedstyles.get('background-image') ); console.log( allcomputedstyles.get('background-image').tostring() ); specifications specification status comment css typed om level 1the definition of 'cssimagevalue' in that specification.
CSSKeyframeRule - Web APIs
csskeyframe.style read only returns a cssstyledeclaration of the css style associated with the keyframe.
CSSKeywordValue.CSSKeywordValue() - Web APIs
syntax var csskeywordvalue = new csskeywordvalue(val) parameters value sets or returns the value of the new csskeywordvalue.
CSSKeywordValue.value - Web APIs
the value property of the csskeywordvalue interface returns or sets the value of the csskeywordvalue.
CSSMathProduct.values - Web APIs
the cssmathproduct.values read-only property of the cssmathproduct interface returns a cssnumericarray object which contains one or more cssnumericvalue objects.
CSSMathProduct - Web APIs
properties cssmathproduct.values returns a cssnumericarray object which contains one or more cssnumericvalue objects.
CSSMathSum.values - Web APIs
WebAPICSSMathSumvalues
the cssmathsum.values read-only property of the cssmathsum interface returns a cssnumericarray object which contains one or more cssnumericvalue objects.
CSSMathValue - Web APIs
n div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values[1].value ); // -20 the cssmathvalue.operator returns 'sum' because stylemap.get('width').values[1].value ); is -20: adding a negative number.
CSSNumericValue.add() - Web APIs
return value a cssmathsum exceptions typeerror indicates that an invalid type was passed to the method.
CSSNumericValue.div() - Web APIs
return value a cssmathproduct.
CSSNumericValue.mul() - Web APIs
return value a cssmathproduct exceptions typeerror indicates that an invalid type was passed to the method.
CSSNumericValue.sub() - Web APIs
return value a cssmathsum exceptions typeerror indicates that an invalid type was passed to the method.
CSSNumericValue.sum() - Web APIs
syntax var cssmathsum = cssnumericvalue.sub(number); parameters number either a number or a cssmathsum return value a cssmathsum exceptions typeerror indicates that an invalid type was passed to the method.
CSSNumericValue.to() - Web APIs
return value a cssmathsum.
CSSNumericValue.toSum() - Web APIs
return value a cssnumericvalue.
CSSNumericValue - Web APIs
cssnumericvalue.min returns the minimum value passed cssnumericvalue.max returns the maximum value passed cssnumericvalue.equals true if all the values are the exact same type and value, in the same order.
CSSPageRule - Web APIs
csspagerule.style read only returns the declaration block associated with the at-rule.
CSSPositionValue.x - Web APIs
the x property of the csspositionvalue interface returns returns the item's position along the web page's horizontal axis.
CSSPositionValue.y - Web APIs
the y property of the csspositionvalue interface returns the item's position along the vertical axis.
CSSPrimitiveValue.getCounterValue() - Web APIs
syntax var countervalue = cssprimitivevalue.getcountervalue(); return value a counter object representing the counter value.
CSSPrimitiveValue.getRectValue() - Web APIs
syntax var rectvalue = cssprimitivevalue.getrectvalue(); return value a rect object representing the rect value.
CSSPrimitiveValue.getStringValue() - Web APIs
syntax var stringvalue = cssprimitivevalue.getstringvalue(); return value a string value.
CSSPrimitiveValue.setStringValue() - Web APIs
return value void.
CSSPseudoElement.element - Web APIs
the element read-only property of the csspseudoelement interface returns a reference to the originating element of the pseudo-element, in other words its parent element.
CSSPseudoElement.type - Web APIs
the type read-only property of the csspseudoelement interface returns the type of the pseudo-element as a string, represented in the form of a css selector.
CSSRule.cssText - Web APIs
WebAPICSSRulecssText
the csstext property of the cssrule interface returns the actual text of a cssstylesheet style-rule.
CSSRule.parentStyleSheet - Web APIs
the parentstylesheet property of the cssrule interface returns the stylesheet object in which the current rule is defined.
CSSRuleList - Web APIs
example // get the first style sheet’s first rule var first_rule = document.stylesheets[0].cssrules[0]; see also cssrule cssrulelist implementations there are multiple properties in the cssom that will return a cssrulelist.
CSSStyleDeclaration.cssText - Web APIs
the csstext property of the cssstyledeclaration interface returns or sets the text of the element's inline style declaration only.
CSSStyleDeclaration.length - Web APIs
the read-only property returns an integer that represents the number of style declarations in this css declaration block.
CSSStyleDeclaration.parentRule - Web APIs
the cssstyledeclaration.parentrule read-only property returns a cssrule that is the parent of this style block, e.g.
CSSStyleDeclaration.removeProperty() - Web APIs
return value oldvalue is a domstring equal to the value of the css property before it was removed.
CSSStyleRule.styleMap - Web APIs
the stylemap read-only property of the cssstylerule interface returns a stylepropertymap object which provides access to the rule's property-value pairs.
CSSStyleSheet.addRule() - Web APIs
return value always returns -1.
CSSStyleSheet.cssRules - Web APIs
the read-only cssstylesheet property cssrules returns a live cssrulelist which provides a real-time, up-to-date list of every css rule which comprises the stylesheet.
CSSStyleSheet.deleteRule() - Web APIs
return value undefined example this example removes the first rule from the stylesheet mystyles.
CSSStyleSheet.removeRule() - Web APIs
return value undefined example this example removes the first rule from the stylesheet mystyles.
CSSUnitValue.unit - Web APIs
WebAPICSSUnitValueunit
the cssunitvalue.unit read-only property of the cssunitvalue interface returns a usvstring indicating the type of unit.
CSSUnitValue.value - Web APIs
the cssunitvalue.value property of the cssunitvalue interface returns a double indicating the number of units.
CSSUnparsedValue.forEach() - Web APIs
return value undefined.
CSSUnparsedValue.length - Web APIs
the length read-only property of the cssunparsedvalue interface returns the number of items in the object.
CSSValueList - Web APIs
if index is greater than or equal to the number of values in the list, this returns null.
CSSVariableReferenceValue.fallback - Web APIs
the fallback read-only property of the cssvariablereferencevalue interface returns the custom property fallback value of the cssvariablereferencevalue.
CSSVariableReferenceValue.variable - Web APIs
the variable property of the cssvariablereferencevalue interface returns the custom property name of the cssvariablereferencevalue.
CanvasCaptureMediaStreamTrack.canvas - Web APIs
the canvascapturemediastreamtrack canvas read-only property returns the htmlcanvaselement from which frames are being captured.
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
syntax stream.requestframe(); return value undefined usage notes there is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean.
CanvasCaptureMediaStreamTrack - Web APIs
canvascapturemediastreamtrack.canvas read only returns the htmlcanvaselement object whose surface is captured in real-time.
CanvasGradient - Web APIs
it is returned by the methods canvasrenderingcontext2d.createlineargradient() or canvasrenderingcontext2d.createradialgradient().
CanvasRenderingContext2D.clip() - Web APIs
the canvasrenderingcontext2d.clip() method of the canvas 2d api turns the current or given path into the current clipping region.
CanvasRenderingContext2D.createImageData() - Web APIs
return value a new imagedata object with the specified width and height.
CanvasRenderingContext2D.currentTransform - Web APIs
the canvasrenderingcontext2d.currenttransform property of the canvas 2d api returns or sets a dommatrix (current specification) or svgmatrix (old specification) object for the current transformation matrix.
CanvasRenderingContext2D.fillText() - Web APIs
return value undefined.
CanvasRenderingContext2D.getLineDash() - Web APIs
syntax ctx.getlinedash(); return value an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units).
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
on getting the imagesmoothingenabled property, the last value it was set to is returned.
CanvasRenderingContext2D.isPointInPath() - Web APIs
return value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false.
CanvasRenderingContext2D.isPointInStroke() - Web APIs
return value boolean a boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false.
CanvasRenderingContext2D.lineTo() - Web APIs
return value undefined.
CanvasRenderingContext2D.putImageData() - Web APIs
agedata object from it var imagedata = ctx.getimagedata(0, 0, 100, 100); // use the putimagedata function that illustrates how putimagedata works putimagedata(ctx, imagedata, 150, 0, 50, 50, 25, 25); result data loss due to browser optimization due to the lossy nature of converting to and from premultiplied alpha color values, pixels that have just been set using putimagedata() might be returned to an equivalent getimagedata() as different values.
CanvasRenderingContext2D.strokeText() - Web APIs
return value undefined.
Advanced animations - Web APIs
how about adding a paddle, some bricks, and turn this demo into a breakout game?
Drawing shapes with canvas - Web APIs
let's see how we can construct a path2d object: path2d() the path2d() constructor returns 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.
Drawing text - Web APIs
measuretext() returns 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'); return document.getelementbyid('myvideo'); } } this returns the htmlvideoelement object for the video, which, as covered earlier, is one of the objects that can be used as a canvasimagesource.
ChannelMergerNode() - Web APIs
return value a new channelmergernode object instance.
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
return value a new channelsplitternode object instance.
Using channel messaging - Web APIs
receiving the confirmation in the main page returning to the main page, let's now look at the onmessage handler function.
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 return 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
WebAPIChildNodeafter
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')) { return; } 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
WebAPIChildNodebefore
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')) { return; } 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
WebAPIChildNoderemove
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')) { return; } 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) return; if (!i) // if there are no arguments parent.removechild(this); while (i--) { // i-- decrements i and returns 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
WebAPIClientid
the id read-only property of the client interface returns the universally unique identifier of the client object.
Client.type - Web APIs
WebAPIClienttype
a document) function sendmessage(message) { return 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.claim() - Web APIs
WebAPIClientsclaim
return value a promise that resolves to undefined.
Clients.openWindow() - Web APIs
return 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.
Clipboard.write() - Web APIs
WebAPIClipboardwrite
return value a promise which is resolved when the data has been written to the clipboard.
Clipboard.writeText() - Web APIs
return value a promise which is resolved once the clipboard's contents have been updated.
ClipboardEvent() - Web APIs
the clipboardevent() constructor returns a newly created clipboardevent, representing an event providing information related to modification of the clipboard, that is cut, copy, and paste events.
ClipboardItem() - Web APIs
examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api.
Clipboard API - Web APIs
since readtext() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe.
Comment() - Web APIs
WebAPICommentComment
the comment() constructor returns a newly created comment object with the optional domstring given in parameter as its textual content.
Comment - Web APIs
WebAPIComment
constructor comment() returns a comment object with the parameter as its textual content.
CompositionEvent.data - Web APIs
the data read-only property of the compositionevent interface returns the characters generated by the input method that raised the event; its exact nature varies depending on the type of event that generated the compositionevent object.
CompositionEvent.initCompositionEvent() - Web APIs
return value void.
CompositionEvent.locale - Web APIs
the locale read-only property of the compositionevent interface returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime).
Console.timeLog() - Web APIs
WebAPIConsoletimeLog
return if no label parameter included: default: 1042ms if an existing label is included: timer name: 1242ms exceptions if there is no running timer, timelog() returns the warning: timer “default” doesn’t exist.
ConstantSourceNode - Web APIs
number of inputs 0 number of outputs 1 constructor constantsourcenode() creates and returns a new constantsourcenode instance, optionally specifying an object which establishes initial values for the object's properties.
ContentIndexEvent - Web APIs
constructor contentindexevent() creates and returns a new contentindexevent object whose type and other options are configured as specified.
ConvolverNode() - Web APIs
return value a new convolvernode object instance.
ConvolverNode - Web APIs
let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ...
CountQueuingStrategy - Web APIs
methods countqueuingstrategy.size() returns 1.
CrashReportBody - Web APIs
the crashreportbody interface of the reporting api represents the body of a crash report (the return value of its report.body property).
Credential.id - Web APIs
WebAPICredentialid
the id property of the credential interface returns a domstring containing the credential's identifier.
Credential.name - Web APIs
WebAPICredentialname
the name property of the credential interface returns a domstring, containing the name associated with a credential.
Credential.type - Web APIs
WebAPICredentialtype
the type property of the credential interface returns a domstring containing the credential's type.
Crypto.getRandomValues() - Web APIs
return value the same array passed as typedarray but with its contents replaced with the newly generated random numbers.
Crypto.subtle - Web APIs
WebAPICryptosubtle
the crypto.subtle read-only property returns a subtlecrypto which can then be used to perform low-level cryptographic operations.
Crypto - Web APIs
WebAPICrypto
crypto.subtle read only secure context returns a subtlecrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption.
CustomElementRegistry.upgrade() - Web APIs
return value void.
CustomEvent() - Web APIs
return 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() returns a boolean domconfiguration.getparameter() returns a domuserdata domconfiguration.setparameter() sets a parameter specification http://www.w3.org/tr/dom-level-3-cor...mconfiguration ...
DOMException.code - Web APIs
WebAPIDOMExceptioncode
the code read-only property of the domexception interface returns 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 returns a domstring representing a message or description associated with the given error name.
DOMException.name - Web APIs
WebAPIDOMExceptionname
the name read-only property of the domexception interface returns a domstring that contains one of the strings associated with an error name.
DOMImplementation.createDocumentType() - Web APIs
the domimplementation.createdocumenttype() method returns 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 returned 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() return value returns 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
return value returns 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.
DOMMatrixReadOnly.translate() - Web APIs
return value returns a dommatrix containing a new matrix being the result of the matrix being translated by the given vector.
DOMParser() - Web APIs
return value a new domparser object.
DOMPoint.DOMPoint() - Web APIs
WebAPIDOMPointDOMPoint
the dompoint() constructor creates and returns a new dompoint object, given the values for some or all of its properties.
DOMPoint - Web APIs
WebAPIDOMPoint
constructor dompoint() creates and returns 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
WebAPIDOMPointInitw
the dompointreadonly.tojson() method returns a dompointinit object that describes the same point as the original point.
DOMPointInit.x - Web APIs
WebAPIDOMPointInitx
dompointinit is used as an input when calling either dompointreadonly.frompoint() or dompoint.frompoint(), and is returned by the dompointreadonly.tojson() and dompoint.tojson() methods.
DOMPointInit.y - Web APIs
WebAPIDOMPointInity
the dompointreadonly.tojson() method returns a dompointinit object that describes the same point as the original point.
DOMPointInit.z - Web APIs
WebAPIDOMPointInitz
the dompointreadonly.tojson() method returns a dompointinit object that describes the same point as the original point.
DOMPointInit - Web APIs
it's used as the return value when calling tojson().
DOMPointReadOnly - Web APIs
tojson() returns a json representation of the dompointreadonly object.
DOMRect.DOMRect() - Web APIs
WebAPIDOMRectDOMRect
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 return // 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 return // 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.
DOMRectReadOnly.bottom - Web APIs
the bottom read-only property of the domrectreadonly interface returns the bottom coordinate value of the domrect.
DOMRectReadOnly.fromRect() - Web APIs
return value an instance of domrect.
DOMRectReadOnly.left - Web APIs
the left read-only property of the domrectreadonly interface returns the left coordinate value of the domrect.
DOMRectReadOnly.right - Web APIs
the right read-only property of the domrectreadonly interface returns the right coordinate value of the domrect.
DOMRectReadOnly.top - Web APIs
the top read-only property of the domrectreadonly interface returns the top coordinate value of the domrect.
DOMTokenList.add() - Web APIs
WebAPIDOMTokenListadd
return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.forEach() - Web APIs
return value undefined.
DOMTokenList.remove() - Web APIs
return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.value - Web APIs
the value property of the domtokenlist interface is a stringifier that returns the value of the list as a domstring, or clears and sets the list to the given value.
DataTransfer.addElement() - Web APIs
return value void example this example shows the use of the addelement() method function change_drag_node(event, node) { var dt = event.datatransfer; dt.addelement(node); } specifications this method is not defined in any web standard.
DataTransfer.dropEffect - Web APIs
on getting, it returns its current value.
DataTransfer.files - Web APIs
syntax datatransfer.files; return value a list of the files in a drag operation, one list item for each file in the operation.
DataTransfer.items - Web APIs
syntax itemlist = datatransfer.items; return value a datatransferitemlist object containing datatransferitem objects representing the items being dragged in a drag operation, one list item for each object being dragged.
DataTransfer.mozClearDataAt() - Web APIs
return value void example this example shows the use of the mozcleardataat() method in a dragend event handler.
DataTransfer.mozSetDataAt() - Web APIs
return value void example this example shows the use of the mozsetdataat() method in a dragstart handler.
DataTransfer.setData() - Web APIs
return value void example this example shows the use of the datatransfer object's getdata(), setdata() and cleardata() methods.
DataTransfer.setDragImage() - Web APIs
return value void example this example shows how to use the setdragimage() method.
DataTransferItemList.clear() - Web APIs
return value undefined example this example shows the use of the clear() method.
DataTransferItemList.length - Web APIs
the read-only length property of the datatransferitemlist interface returns the number of items currently in the drag item list.
DataTransferItemList.remove() - Web APIs
return value undefined.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
returns void.
DelayNode() - Web APIs
return value a new delaynode object instance.
DelayNode.delayTime - Web APIs
syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not.
Using light sensors - Web APIs
window.addeventlistener("devicelight", function (event) { // read out the lux value var luminosity = event.value; alert(luminosity); }); example: window.addeventlistener('devicelight', function(event) { var bodybg= document.body.style; //event.value is the lux value returned by the sensor on the device if (event.value < 100) { alert('hey, you!
DeviceMotionEvent.acceleration - Web APIs
the acceleration property returns the amount of acceleration recorded by the device, in meters per second squared (m/s2).
DeviceMotionEvent.accelerationIncludingGravity - Web APIs
the accelerationincludinggravity property returns the amount of acceleration recorded by the device, in meters per second squared (m/s2).
DeviceMotionEvent.interval - Web APIs
returns the interval, in milliseconds, at which data is obtained from the underlaying hardware.
DeviceMotionEventAcceleration: x - Web APIs
syntax var xaccel = devicemotioneventacceleration.x; return value x a double indicating the amount of acceleration along the x axis.
DeviceMotionEventAcceleration: y - Web APIs
syntax var yaccel = devicemotioneventacceleration.y; return value y a double indicating the amount of acceleration along the y axis.
DeviceMotionEventAcceleration: z - Web APIs
syntax var zaccel = devicemotioneventacceleration.z; return value z a double indicating the amount of acceleration along the z axis.
DeviceMotionEventRotationRate: alpha - Web APIs
return value alpha a double indicating the rate of rotation around the z axis, in degrees per second.
DeviceMotionEventRotationRate: beta - Web APIs
return value beta a double indicating the rate of rotation around the x axis, in degrees per second.
DeviceMotionEventRotationRate: gamma - Web APIs
return value gamma a double indicating the rate of rotation around the y axis, in degrees per second.
DeviceOrientationEvent.absolute - Web APIs
syntax var absolute = instanceofdeviceorientationevent.absolute; on return, absolute is true if the orientation data in instanceofdeviceorientationevent is provided as the difference between the earth's coordinate frame and the device's coordinate frame, or false if the orientation data is being provided in reference to some arbitrary, device-determined coordinate frame.
DeviceOrientationEvent.alpha - Web APIs
returns the rotation of the device around the z axis; that is, the number of degrees by which the device is being twisted around the center of the screen.
DeviceOrientationEvent.beta - Web APIs
returns the rotation of the device around the x axis; that is, the number of degrees, ranged between -180 and 180, by which the device is tipped forward or backward.
DeviceOrientationEvent.gamma - Web APIs
returns the rotation of the device around the y axis; that is, the number of degrees, ranged between -90 and 90, by which the device is tilted left or right.
Device Memory API - Web APIs
javascript api you may query the approximate amount of ram device has by retreiving navigator.devicememory var ram1 = window.navigator.devicememory; var ram2 = navigator.devicememory; both of these will return the same result.
Document.URL - Web APIs
WebAPIDocumentURL
the url read-only property of the document interface returns the document location as a string.
Document.adoptNode() - Web APIs
return value the copied importednode in the scope of the importing document.
Document.alinkColor - Web APIs
returns or sets the color of an active link in the document body.
Document.body - Web APIs
WebAPIDocumentbody
in documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element.
Document.contentType - Web APIs
the document.contenttype read-only property returns the mime type that the document is being rendered as.
Document.cookie - Web APIs
WebAPIDocumentcookie
3:59:59 gmt"; } } <button onclick="doonce()">only do something once</button> example #4: reset the previous cookie function resetonce() { document.cookie = "dosomethingonlyonce=; expires=thu, 01 jan 1970 00:00:00 gmt"; } <button onclick="resetonce()">reset only once cookie</button> example #5: check a cookie existence //es5 if (document.cookie.split(';').some(function(item) { return item.trim().indexof('reader=') == 0 })) { console.log('the cookie "reader" exists (es5)') } //es2016 if (document.cookie.split(';').some((item) => item.trim().startswith('reader='))) { console.log('the cookie "reader" exists (es6)') } example #6: check that a cookie has a specific value //es5 if (document.cookie.split(';').some(function(item) { return item.indexof('reader=1') >=...
Document.createCDATASection() - Web APIs
createcdatasection() creates a new cdata section node, and returns it.
Document.createComment() - Web APIs
createcomment() creates a new comment node, and returns it.
Document.createElement() - Web APIs
return value the new element.
Document.createElementNS() - Web APIs
return value the new element.
Document.createEntityReference() - Web APIs
prior to gecko 7.0 this method showed up as present, due to bug bug 9850, it always only returned null.
Document.createEvent() - Web APIs
the returned object should be first initialized and can then be passed to eventtarget.dispatchevent.
Document.createExpression() - Web APIs
return value xpathexpression ...
Document.createNSResolver() - Web APIs
return value nsresolver is an xpathnsresolver object.
Document.createRange() - Web APIs
the document.createrange() method returns a new range object.
Document.currentScript - Web APIs
the document.currentscript property returns the <script> element whose script is currently being processed and isn't a javascript module.
Document.defaultView - Web APIs
in browsers, document.defaultview returns the window object associated with a document, or null if none is available.
Document.documentElement - Web APIs
document.documentelement returns the element that is the root element of the document (for example, the <html> element for html documents).
Document.documentURI - Web APIs
the documenturi read-only property of the document interface returns the document location as a string.
Document.documentURIObject - Web APIs
the document.documenturiobject read-only property returns an nsiuri object representing the uri of the document.
Document.domConfig - Web APIs
this should return the domconfiguration for the document.
Document.embeds - Web APIs
WebAPIDocumentembeds
the embeds read-only property of the document interface returns a list of the embedded <object> elements within the current document.
Document.exitFullscreen() - Web APIs
return value a promise which is resolved once the user agent has finished exiting full-screen mode.
Document.featurePolicy - Web APIs
the featurepolicy read-only property of the document interface returns the featurepolicy interface which provides a simple api for inspecting the feature policies applied to a specific document.
Document.fullscreen - Web APIs
function isdocumentinfullscreenmode() { return document.fullscreen; } this next example, on the other hand, uses the current fullscreenelement property to determine the same thing: function isdocumentinfullscreenmode() { return document.fullscreenelement !== null; } if fullscreenelement isn't null, this returns true, indicating that full-screen mode is in effect.
Document.getBoxObjectFor() - Web APIs
returns a boxobject (x, y, width, height) for a specified element.
Document.head - Web APIs
WebAPIDocumenthead
the head read-only property of the document interface returns the <head> element of the current document.
Document.height - Web APIs
WebAPIDocumentheight
returns the height of the document object.
Document.hidden - Web APIs
WebAPIDocumenthidden
the document.hidden read-only property returns a boolean value indicating if the page is considered hidden or not.
Document.implementation - Web APIs
the document.implementation property returns a domimplementation object associated with the current document.
Document.importNode() - Web APIs
return value the copied importednode in the scope of the importing document.
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) { return; } // 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) { return; } // do something }); examples this example logs the keyboardevent.code value whenever you release a key.
Document.links - Web APIs
WebAPIDocumentlinks
the links read-only property of the document interface returns a collection of all <area> elements and <a> elements in a document with a value for the href attribute.
Document.mozSyntheticDocument - Web APIs
syntax var issynthetic = document.mozsyntheticdocument; on return, issynthetic is true if the document is a synthetic one; otherwise it's false.
Document.ononline - Web APIs
WebAPIDocumentononline
window.navigator.online returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network).
Document.open() - Web APIs
WebAPIDocumentopen
return value a document object instance.
Document.plugins - Web APIs
WebAPIDocumentplugins
the plugins read-only property of the document interface returns an htmlcollection object containing one or more htmlembedelements representing the <embed> elements in the current document.
Document.queryCommandState() - Web APIs
syntax querycommandstate(string command) parameters command is a command from document.execcommand() return value querycommandstate() can return a boolean value or null if the state is unknown.
Document.registerElement() - Web APIs
the document.registerelement() method registers a new custom element in the browser and returns a constructor for the new element.
Document.selectedStyleSheetSet - Web APIs
syntax currentstylesheetset = document.selectedstylesheetset; document.selectedstylesheet = newstylesheetset; on return, currentstylesheetset indicates the name of the style sheet set currently in use.
Document.tooltipNode - Web APIs
the document.tooltipnode property returns the node which is the target of the current <xul:tooltip>.
Document.visibilityState - Web APIs
the document.visibilitystate read-only property returns the visibility of the document, that is in which context this element is now visible.
Document.width - Web APIs
WebAPIDocumentwidth
returns the width of the <body> element of the current document in pixels.
Document.xmlEncoding - Web APIs
returns the encoding as determined by the xml declaration.
DocumentFragment() - Web APIs
the documentfragment() constructor returns a new, empty documentfragment object .
DocumentOrShadowRoot.pointerLockElement - Web APIs
syntax var element = document.pointerlockelement; return value an element or null.
DocumentTimeline - Web APIs
animationtimeline.currenttime returns the time value in milliseconds for this timeline or null if it is inactive.
Example - Web APIs
<html> <head> <title>my document</title> <script type="text/javascript"> function change() { // document.getelementsbytagname("h1") returns a nodelist of the h1 // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h1").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document".
Using the W3C DOM Level 1 Core - Web APIs
the following script would do the job: html content <body> <input type="button" value="change this document." onclick="change()"> <h2>header</h2> <p>paragraph</p> </body> javascript content function change() { // document.getelementsbytagname("h2") returns a nodelist of the <h2> // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h2").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document".
DragEvent.dataTransfer - Web APIs
syntax let data = dragevent.datatransfer; return value data a datatransfer object which contains the drag event's data.
DynamicsCompressorNode.attack - Web APIs
note: though the audioparam returned is read-only, the value it represents is not.
DynamicsCompressorNode.knee - Web APIs
note: though the audioparam returned is read-only, the value it represents is not.
DynamicsCompressorNode.ratio - Web APIs
note: though the audioparam returned is read-only, the value it represents is not.
DynamicsCompressorNode.reduction - Web APIs
intended for metering purposes, it returns a value in db, or 0 (no gain reduction) if no signal is fed into the dynamicscompressornode.
DynamicsCompressorNode.release - Web APIs
note: though the audioparam returned is read-only, the value it represents is not.
DynamicsCompressorNode.threshold - Web APIs
note: though the audioparam returned is read-only, the value it represents is not.
EXT_disjoint_timer_query.beginQueryEXT() - Web APIs
return value none.
EXT_disjoint_timer_query.createQueryEXT() - Web APIs
return value a webglquery object.
EXT_disjoint_timer_query.deleteQueryEXT() - Web APIs
return value none.
EXT_disjoint_timer_query.endQueryEXT() - Web APIs
return value none.
EXT_disjoint_timer_query.queryCounterEXT() - Web APIs
return value none.
EXT_sRGB - Web APIs
WebAPIEXT sRGB
ext.framebuffer_attachment_color_encoding_ext returns the framebuffer color encoding (gl.linear or ext.srgb_ext).
EXT_texture_filter_anisotropic - Web APIs
constants ext.max_texture_max_anisotropy_ext this is the pname argument to the gl.getparameter() call, and it returns the maximum available anisotropy.
EffectTiming.direction - Web APIs
the value of direction corresponds directly to animationeffecttimingreadonly.direction in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
EffectTiming.easing - Web APIs
the value of easing corresponds directly to animationeffecttimingreadonly.easing in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
EffectTiming.endDelay - Web APIs
the value of enddelay corresponds directly to animationeffecttimingreadonly.enddelay in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
the value of fill corresponds directly to fill in effecttiming objects returned by gettiming() in animationeffect and keyframeeffect.
EffectTiming.iterationStart - Web APIs
the value of iterationstart corresponds directly to animationeffecttimingreadonly.iterationstart in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
EffectTiming.iterations - Web APIs
the value of iterations corresponds directly to animationeffecttimingreadonly.iterations in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect.
Element.attributes - Web APIs
the element.attributes property returns a live collection of all attribute nodes registered to the specified node.
Element: auxclick event - Web APIs
javascript let button = document.queryselector('button'); let html = document.queryselector('html'); function random(number) { return math.floor(math.random() * number); } function randomcolor() { return `rgb(${random(255)}, ${random(255)}, ${random(255)})`; } button.onclick = function() { button.style.backgroundcolor = randomcolor(); }; button.onauxclick = function(e) { e.preventdefault(); button.style.color = randomcolor(); } button.oncontextmenu = function(e) { e.preventdefault(); } notice that in addition ...
Element.className - Web APIs
WebAPIElementclassName
however, take into account that element.getattribute returns null instead of "" if the element has an empty class attribute.
Element.clientHeight - Web APIs
when clientheight is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's height (excluding any scrollbar) is returned.
Element.clientLeft - Web APIs
note: when an element has display: inline, clientleft returns 0 regardless of the element's border.
Element.clientWidth - Web APIs
when clientwidth is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's width (excluding any scrollbar) is returned.
Element.createShadowRoot() - Web APIs
result value returns a shadowroot.
Element.getAttributeNode() - Web APIs
returns the specified attribute of the specified element, as an attr node.
Element.getAttributeNodeNS() - Web APIs
returns the attr node for the attribute with the given namespace and name.
Element.hasAttributeNS() - Web APIs
hasattributens returns a boolean value indicating whether the current element has the specified attribute.
Element.hasPointerCapture() - Web APIs
return value a boolean value — true if the element does have pointer capture, false if it doesn't.
Element.insertAdjacentElement() - Web APIs
return value the element that was inserted, or null, if the insertion failed.
Element.insertAdjacentText() - Web APIs
return value void.
Element: 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) { return; } // do something }); examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element.
Element: 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) { return; } // do something }); examples addeventlistener keyup example this example logs the keyboardevent.code value whenever you release a key inside the <input> element.
Element: mousedown event - Web APIs
when the drawline() function returns, we adjust the coordinates and then save them in x and y.
Element: mousemove event - Web APIs
when the drawline() function returns, we adjust the coordinates and then save them in x and y.
Element: mouseup event - Web APIs
when the drawline() function returns, we adjust the coordinates and then save them in x and y.
Element.msZoomTo() - Web APIs
WebAPIElementmsZoomTo
return value this method does not return a value.
Element.name - Web APIs
WebAPIElementname
when used with a form or elements collection, it may return a single element or a collection.
Element.part - Web APIs
WebAPIElementpart
set using the part attribute), returned as a domtokenlist.
Element: paste event - Web APIs
solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const target = document.queryselector('div.target'); target.addeventlistener('paste', (event) => { let paste = (event.clipboarddata || window.clipboarddata).getdata('text'); paste = paste.touppercase(); const selection = window.getselection(); if (!selection.rangecount) return false; selection.deletefromdocument(); selection.getrangeat(0).insertnode(document.createtextnode(paste)); event.preventdefault(); }); result specifications specification status clipboard api and events working draft ...
Element.prefix - Web APIs
WebAPIElementprefix
the element.prefix read-only property returns the namespace prefix of the specified element, or null if no prefix is specified.
Element.releasePointerCapture() - Web APIs
return value this method returns undefined.
Element.scrollLeftMax - Web APIs
the element.scrollleftmax read-only property returns a number representing the maximum left scroll offset possible for the element.
Element.scrollTop - Web APIs
WebAPIElementscrollTop
when scrolltop is used on the root element (the <html> element), the scrolly of the window is returned.
Element.scrollTopMax - Web APIs
the element.scrolltopmax read-only property returns a number representing the maximum top scroll offset possible for the element.
Element.scrollWidth - Web APIs
<button id="anotherbutton"> check for overflow </button> </body> <script> var buttonone = document.getelementbyid('abutton'), buttontwo = document.getelementbyid('anotherbutton'), divone = document.getelementbyid('adiv'), divtwo = document.getelementbyid('anotherdiv'); //check to determine if an overflow is happening function isoverflowing(element) { return (element.scrollwidth > element.offsetwidth); } function alertoverflow(element) { if (isoverflowing(element)) { alert('contents are overflowing the container.'); } else { alert('no overflows!'); } } buttonone.addeventlistener('click', function() { alertoverflow(divone); }); buttontwo.addeventlistener('click', functi...
Element.setAttribute() - Web APIs
return value undefined.
Element.setPointerCapture() - Web APIs
return value this method returns undefined.
Element.slot - Web APIs
WebAPIElementslot
the slot property of the element interface returns the name of the shadow dom slot the element is inserted in.
Element.tabStop - Web APIs
WebAPIElementtabStop
the tabstop property of the element interface returns a boolean indicating if the element can receive input focus via the tab key.
Element: webkitmouseforcewillbegin event - Web APIs
this offers the opportunity to tell the system not to trigger any default force touch actions if and when the click turns into a force touch event.
ElementCSSInlineStyle - Web APIs
when getting, it returns 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.methodsthis interface has no methods.
Event.cancelBubble - Web APIs
setting its value to true before returning from an event handler prevents propagation of the event.
Event.defaultPrevented - Web APIs
the defaultprevented read-only property of the event interface returns a boolean indicating whether or not the call to event.preventdefault() canceled the event.
Event.eventPhase - Web APIs
WebAPIEventeventPhase
syntax let phase = event.eventphase; value returns an integer value which specifies the current evaluation phase of the event flow.
Event.explicitOriginalTarget - Web APIs
function mycommand(ev) { alert(ev.explicitoriginaltarget.nodename); // returns 'menuitem' } <xul:command id="my-cmd-anaction" oncommand="mycommand(event);"/> <xul:menulist> <xul:menupopup> <xul:menuitem label="get my element name!" command="my-cmd-anaction"/> </xul:menupopup> </menulist> specifications this is a mozilla-specific property.
Event.stopPropagation() - Web APIs
return value undefined.
Event.timeStamp - Web APIs
WebAPIEventtimeStamp
the timestamp read-only property of the event interface returns the time (in milliseconds) at which the event was created.
Event.type - Web APIs
WebAPIEventtype
the type read-only property of the event interface returns a string containing the event's type.
EventSource() - Web APIs
the eventsource() constructor returns a newly-created eventsource, which represents a remote resource.
EventSource.close() - Web APIs
WebAPIEventSourceclose
return value void.
EventSource.readyState - Web APIs
the readystate read-only property of the eventsource interface returns a number representing the state of the connection.
EventSource.url - Web APIs
WebAPIEventSourceurl
the url read-only property of the eventsource interface returns a domstring representing the url of the source.
EventSource.withCredentials - Web APIs
the withcredentials read-only property of the eventsource interface returns a boolean indicating whether the eventsource object was instantiated with cors credentials set.
EventSource - Web APIs
it, in turn, creates a new <li> element and writes the message's data into it, then appends the new element to the list element already in the document.
ExtendableEvent - Web APIs
resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return 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); }) ); }); important: when fetching resources, it's very important to use {mode: 'no...
ExtendableMessageEvent.data - Web APIs
the data read-only property of the extendablemessageevent interface returns the event's data.
ExtendableMessageEvent.origin - Web APIs
the origin read-only property of the extendablemessageevent interface returns the origin of the client that sent the message.
ExtendableMessageEvent.ports - Web APIs
the ports read-only property of the extendablemessageevent interface returns the array containing the messageport objects representing the ports of the associated message channel (the channel the message is being sent through.) syntax var myports = extendablemessageevent.ports; value an array of messageport objects.
ExtendableMessageEvent.source - Web APIs
the source read-only property of the extendablemessageevent interface returns a reference to the client object from which the message was sent.
FederatedCredential.protocol - Web APIs
the protocol property of the federatedcredential interface returns a read-only domstring containing a credential's federated identity protocol.
FederatedCredential.provider - Web APIs
the provider property of the federatedcredential interface returns a usvstring containing a credential's federated identity provider.
FetchEvent() - Web APIs
preloadresponse read only a promise which returns a previously-loaded response to the client.
FetchEvent.client - Web APIs
WebAPIFetchEventclient
the fetchevent.client read-only property returns the client that the current service worker is controlling.
FetchEvent.clientId - Web APIs
the clientid read-only property of the fetchevent interface returns the id of the client that the current service worker is controlling.
File.fileName - Web APIs
WebAPIFilefileName
returns the name of the file.
File.fileSize - Web APIs
WebAPIFilefileSize
returns the size of a file in bytes.
File.getAsBinary() - Web APIs
WebAPIFilegetAsBinary
syntax var binary = instanceoffile.getasbinary(); returns a string.
File.getAsDataURL() - Web APIs
WebAPIFilegetAsDataURL
syntax var url = instanceoffile.getasdataurl(); returns a string representing a data: url example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // array with acceptable file types var accept = ["image/png"]; // img is a htmlimgelement: <img id="myimg"> var img = document.getelementbyid("myimg"); // if we accept the first selected file type if (accept.indexof(files[0].mediatype) > -1) { // display the image // ...
File.name - Web APIs
WebAPIFilename
returns the name of the file represented by a file object.
File.size - Web APIs
WebAPIFilesize
summary returns the size of a file in bytes.
FileReader.abort() - Web APIs
WebAPIFileReaderabort
upon return, the readystate will be done.
FileReader.readAsText() - Web APIs
encoding optional a string specifying the encoding to use for the returned data.
FileReader.result - Web APIs
WebAPIFileReaderresult
the filereader result property returns the file's contents.
FileReaderSync.readAsArrayBuffer() - Web APIs
return value an arraybuffer representing the file's data.
FileReaderSync.readAsBinaryString() - Web APIs
return value an domstring representing the input data.
FileReaderSync.readAsDataURL() - Web APIs
return value an domstring representing the input data as a data url.
FileReaderSync.readAsText() - Web APIs
return value an domstring representing the input data.
FileSystemDirectoryEntry.removeRecursively() - Web APIs
return value undefined.
FileSystemDirectoryReader - Web APIs
methods readentries() returns an array containing some number of the directory's entries.
FileSystemEntry.copyTo() - Web APIs
return value undefined.
FileSystemEntry.getMetadata() - Web APIs
return value undefined.
FileSystemEntry.moveTo() - Web APIs
return value undefined.
FileSystemEntry.remove() - Web APIs
return value undefined.
File and Directory Entries API support in Firefox - Web APIs
in particular, the filesystemfileentry.createwriter() method, used to create a filewriter to handle writing to a file, is not implemented and will just treturn an error.
FocusEvent() - Web APIs
the focusevent() constructor returns a newly created focusevent object with an optional eventtarget.
FontFace.loaded - Web APIs
WebAPIFontFaceloaded
the loaded read-only property of the fontface interface returns 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 - Web APIs
WebAPIFontFacestatus
the status read-only property of the fontface interface returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "error".
FontFaceSet - Web APIs
fontfaceset.load() returns a promise which resolves to a list of font-faces for a requested font.
FontFaceSetLoadEvent.fontfaces - Web APIs
the fontfaces read-only property of the fontfaceloadeventinit interface returns an array of fontface instances, each of which represents a single usable font.
FontFaceSetLoadEvent - Web APIs
properties fontfacesetloadevent.fontfacesread only returns an array of fontface instances each of which represents a single usable font.
FormData.append() - Web APIs
WebAPIFormDataappend
returns void.
FormData.delete() - Web APIs
WebAPIFormDatadelete
returns void.
FormDataEvent.formData - Web APIs
syntax formdata = formdataevent.formdata returns a formdata object.
Guide to the Fullscreen API - Web APIs
pressing the return or enter key lets the user toggle between windowed and fullscreen presentation of the video.
GainNode() - Web APIs
WebAPIGainNodeGainNode
return value a new gainnode object instance.
GainNode.gain - Web APIs
WebAPIGainNodegain
note: though the audioparam returned is read-only, the value it represents is not.
Gamepad.axes - Web APIs
WebAPIGamepadaxes
the gamepad.axes property of the gamepad interface returns an array representing the controls with axes present on the device (e.g.
Gamepad.buttons - Web APIs
WebAPIGamepadbuttons
the gamepad.buttons property of the gamepad interface returns an array of gamepadbutton objects representing the buttons present on the device.
Gamepad.connected - Web APIs
WebAPIGamepadconnected
the gamepad.connected property of the gamepad interface returns a boolean indicating whether the gamepad is still connected to the system.
Gamepad.hapticActuators - Web APIs
the hapticactuators read-only property of the gamepad interface returns an array containing gamepadhapticactuator objects, each of which represents haptic feedback hardware available on the controller.
Gamepad.index - Web APIs
WebAPIGamepadindex
the gamepad.index property of the gamepad interface returns an integer that is auto-incremented to be unique for each device currently connected to the system.
Gamepad.mapping - Web APIs
WebAPIGamepadmapping
the gamepad.mapping property of the gamepad interface returns a string indicating whether the browser has remapped the controls on the device to a known layout.
Gamepad.timestamp - Web APIs
WebAPIGamepadtimestamp
the gamepad.timestamp property of the gamepad interface returns a domhighrestimestamp representing the last time the data for this gamepad was updated.
Gamepad - Web APIs
WebAPIGamepad
a gamepad object can be returned in one of two ways: via the gamepad property of the gamepadconnected and gamepaddisconnected events, or by grabbing any position in the array returned by the navigator.getgamepads() method.
GamepadButton.pressed - Web APIs
the gamepadbutton.pressed property of the gamepadbutton interface returns a boolean indicating whether the button is currently pressed (true) or unpressed (false).
GamepadButton.value - Web APIs
the gamepadbutton.value property of the gamepadbutton interface returns a double value used to represent the current state of analog buttons on many modern gamepads, such as the triggers.
GamepadEvent.gamepad - Web APIs
the gamepadevent.gamepad property of the gamepadevent interface returns a gamepad object, providing access to the associated gamepad data for fired gamepadconnected and gamepaddisconnected events.
GamepadHapticActuator.pulse() - Web APIs
return value a promise that resolves with a value of true when the pulse has successfully completed.
GamepadHapticActuator.type - Web APIs
the type read-only property of the gamepadhapticactuator interface returns an enum representing the type of the haptic hardware.
GamepadHapticActuator - Web APIs
properties gamepadhapticactuator.type read only returns an enum representing the type of the haptic hardware.
Gamepad API - Web APIs
extensions to other interfaces navigator navigator.getgamepads() an extension to the navigator object that returns an array of gamepad objects, one for each connected gamepad.
Geolocation.clearWatch() - Web APIs
syntax navigator.geolocation.clearwatch(id); parameters id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove.
Geolocation.watchPosition() - Web APIs
return value an integer id that identifies the registered handler.
Geolocation - Web APIs
geolocation.watchposition() secure context returns a long value representing the newly established callback function to be invoked whenever the device location changes.
GeolocationPosition.timestamp - Web APIs
the geolocationposition.timestamp read-only property returns a domtimestamp object, represents the date and the time of the creation of the geolocationposition object it belongs to.
GeolocationPositionError.code - Web APIs
2 position_unavailable the acquisition of the geolocation failed because one or several internal sources of position returned an internal error.
GeolocationPositionError.message - Web APIs
the geolocationpositionerror.message read-only property returns a human-readable domstring describing the details of the error.
GeometryUtils - Web APIs
methods geometryutils.getboxquads() returns a list of domquad objects representing the css fragments of the node.
GestureEvent - Web APIs
gestureevent derives from uievent, which in turn derives from event.
GlobalEventHandlers.onloadstart - Web APIs
the onloadstart property sets and returns the event handler for the loadstart event.
GlobalEventHandlers.onauxclick - Web APIs
var button = document.queryselector('button'); var html = document.queryselector('html'); function random(number) { return math.floor(math.random() * number); } button.onclick = function() { var rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.backgroundcolor = rndcol; }; button.onauxclick = function() { var rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.color = rndcol; } note: if you are using a three-button mouse, you'll...
GlobalEventHandlers.oncontextmenu - Web APIs
html <div class="shape">spinning</div> <p class="note" hidden>click to unpause.</p> css @keyframes spin { from { transform: rotate(0); } to { transform: rotate(1turn); } } .shape { width: 8em; height: 8em; display: flex; align-items: center; justify-content: center; animation: spin 18s linear infinite; background: lightsalmon; border-radius: 42%; margin: 1em; } .paused { background-color: #ddd; } .paused .shape { animation-play-state: paused; } javascript function pause(e) { body.classlist.add('paused'); note.removeattribute('...
GlobalEventHandlers.ondrag - Web APIs
syntax var draghandler = targetelement.ondrag; return value draghandler the drag event handler for element targetelement.
GlobalEventHandlers.ondragend - Web APIs
syntax var dragendhandler = targetelement.ondragend; return value dragendhandler the dragend event handler for element targetelement.
GlobalEventHandlers.ondragenter - Web APIs
syntax var dragenterhandler = targetelement.ondragenter; return value dragenterhandler the dragenter event handler for element targetelement.
GlobalEventHandlers.ondragexit - Web APIs
syntax var dragexithandler = targetelement.ondragexit; return value dragexithandler the dragexit event handler for element targetelement.
GlobalEventHandlers.ondragleave - Web APIs
syntax var dragleavehandler = targetelement.ondragleave; return value dragleavehandler the dragleave event handler for element targetelement.
GlobalEventHandlers.ondragover - Web APIs
syntax var dragoverhandler = targetelement.ondragover; return value dragoverhandler the dragover event handler for element targetelement.
GlobalEventHandlers.ondragstart - Web APIs
syntax var dragstarthandler = targetelement.ondragstart; return value dragstarthandler the dragstart event handler for element targetelement.
GlobalEventHandlers.ondrop - Web APIs
syntax var drophandler = targetelement.ondrop; return value drophandler the drop event handler for element targetelement.
GlobalEventHandlers.onemptied - Web APIs
the onemptied property sets and returns the event handler for the emptied event.
GlobalEventHandlers.oninput - Web APIs
it also handles these events on elements where contenteditable or designmode are turned on.
GlobalEventHandlers.onmousewheel - Web APIs
the onmousewheel property sets and returns the event handler for the mousewheel event.
GlobalEventHandlers.onpointerdown - Web APIs
the handledown() function, in turn, looks at the value of pointertype to determine what kind of pointing device was used, then uses that information to customize a string to replace the contents of the target box.
GlobalEventHandlers.ontouchcancel - Web APIs
syntax var cancelhandler = someelement.ontouchcancel; return value cancelhandler the touchcancel event handler for element someelement.
GlobalEventHandlers.ontouchend - Web APIs
syntax var endhandler = targetelement.ontouchend; return value endhandler the touchend event handler for element targetelement.
GlobalEventHandlers.ontouchmove - Web APIs
syntax var movehandler = someelement.ontouchmove; return value movehandler the touchmove event handler for element someelement.
GlobalEventHandlers.ontouchstart - Web APIs
syntax var starthandler = someelement.ontouchstart; return value starthandler the touchstart event handler for element someelement.
Gyroscope.x - Web APIs
WebAPIGyroscopex
the x read-only property of the gyroscope interface returns a double precision integer containing the angular velocity of the device along the its x axis.
Gyroscope.y - Web APIs
WebAPIGyroscopey
the y read-only property of the gyroscope interface returns a double precision integer containing the angular velocity of the device along the its y axis.
Gyroscope.z - Web APIs
WebAPIGyroscopez
the z read-only property of the gyroscope interface returns a double precision integer containing the angular velocity of the device along the its z axis.
HTMLAreaElement.relList - Web APIs
the property itself is read-only, meaning you can't substitute the domtokenlist by another one, but the content of the returned list can be changed.
HTMLButtonElement - Web APIs
methods inherits methods from its parent, htmlelement name return type description checkvalidity() boolean not supported for reset or button elements.
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
syntax offscreencanvas htmlcanvaselement.transfercontroltooffscreen() return value an offscreencanvas object.
HTMLContentElement.getDistributedNodes() - Web APIs
the htmlcontentelement.getdistributednodes() method returns a static nodelist of the distributed nodes associated with this <content> element.
HTMLContentElement - Web APIs
htmlcontentelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <content> element.
HTMLDataElement.value - Web APIs
the value property of the htmldataelement interface returns a domstring reflecting the value html attribute.
HTMLDialogElement.open - Web APIs
l</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes ...
HTMLDocument - Web APIs
living standard turn the htmldocument interface into a document extension.
accessKeyLabel - Web APIs
the htmlelement.accesskeylabel read-only property returns a string that represents the element's assigned access key (if any); otherwise it returns an empty string.
HTMLElement: beforeinput event - Web APIs
the event also applies to elements with contenteditable enabled, and to any element when designmode is turned on.
HTMLElement.innerText - Web APIs
if the element itself is not being rendered (e.g detached from the document or is hidden from view), the returned value is the same as the node.textcontent property.
HTMLElement: input event - Web APIs
bubbles yes cancelable no interface inputevent event handler property globaleventhandlers.oninput the event also applies to elements with contenteditable enabled, and to any element when designmode is turned on.
HTMLElement.isContentEditable - Web APIs
the htmlelement.iscontenteditable read-only property returns a boolean that is true if the contents of the element are editable; otherwise it returns false.
HTMLElement.lang - Web APIs
WebAPIHTMLElementlang
the language code returned by this property is defined in the tags for identifying languages (bcp47) ietf document.
HTMLElement.offsetLeft - Web APIs
the htmlelement.offsetleft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the htmlelement.offsetparent node.
HTMLElement.outerText - Web APIs
as a getter, it returns the same value as node.innertext.
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.
HTMLFormElement.requestSubmit() - Web APIs
return value none.
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; // returns:'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, returns the origin var result = window.location.origin; // returns:'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; // returns:'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; // returns:'/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; // returns:'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; // returns:'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; // returns:'?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; // returns:'anonymous' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.username' in that specification.
HTMLIFrameElement.allowPaymentRequest - Web APIs
the allowpaymentrequest property of the htmliframeelement interface returns a boolean indicating whether the payment request api may be invoked on a cross-origin iframe.
HTMLIFrameElement.featurePolicy - Web APIs
the featurepolicy read-only property of the htmliframeelement interface returns the featurepolicy interface which provides a simple api for introspecting the feature policies applied to a specific frame.
HTMLIFrameElement.setNfcFocus() - Web APIs
syntax myiframe.setnfcfocus(true); returns void.
HTMLImageElement.complete - Web APIs
let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ...
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="return 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...
HTMLImageElement.x - Web APIs
so the value returned by x would be the distance from that point to the left edge of the content area.
HTMLImageElement.y - Web APIs
so the value returned by y would be the distance from that point to the top edge of the content area.
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 return 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 return a value that does match the form controls constraints.
HTMLKeygenElement - Web APIs
methods name & arguments return description checkvalidity() boolean always returns true because keygen objects are never candidates for constraint validation.
HTMLLabelElement.control - Web APIs
the read-only htmllabelelement.control property returns 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 returns a domstring representing the type of content being loaded by the html link, one of "script", "style", "image", "video", "audio", "track", "font", "fetch".
HTMLLinkElement.relList - Web APIs
the property itself is read-only, meaning you can substitute the domtokenlist by another one, but the content of the returned list can be changed.
HTMLLinkElement - Web APIs
linkstyle.sheet read only returns the stylesheet object associated with the given element, or null if there is none.
HTMLMediaElement.buffered - Web APIs
the htmlmediaelement.buffered read-only property returns 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.canPlayType() - Web APIs
return value a domstring indicating how likely it is that the media can be played.
HTMLMediaElement.controlsList - Web APIs
the controlslist property of the htmlmediaelement interface returns 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.currentTime - Web APIs
example var video = document.createelement('video'); console.log(video.currenttime); usage notes reduced time precision to offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value returned by currenttime.
HTMLMediaElement.duration - Web APIs
if no media data is available, the value nan is returned.
HTMLMediaElement.fastSeek() - Web APIs
return value none.
msClearEffects - Web APIs
return value this method does not return a value.
HTMLMediaElement.msInsertAudioEffect() - Web APIs
return value this method does not return a value.
HTMLMediaElement.pause() - Web APIs
return value none.
HTMLMediaElement: pause event - Web APIs
the event is sent once the pause() method returns and after the media element's paused property has been changed to true.
HTMLMediaElement.srcObject - Web APIs
the srcobject property of the htmlmediaelement interface sets or returns the object which serves as the source of the media associated with the htmlmediaelement.
HTMLObjectElement.contentDocument - Web APIs
the contentdocument read-only property of the htmlobjectelement interface returns a document representing the active document of the object element's nested browsing context, if any; otherwise null.
HTMLObjectElement.contentWindow - Web APIs
the contentwindow read-only property of the htmlobjectelement interface returns a windowproxy representing the window proxy of the object element's nested browsing context, if any; otherwise null.
HTMLObjectElement.data - Web APIs
the data property of the htmlobjectelement interface returns a domstring that reflects the data html attribute, specifying the address of a resource's data.
HTMLObjectElement.height - Web APIs
the height property of the htmlobjectelement interface returns a domstring that reflects the height html attribute, specifying the displayed height of the resource in css pixels.
HTMLObjectElement.name - Web APIs
the name property of the htmlobjectelement interface returns a domstring that reflects the name html attribute, specifying the name of the browsing context.
HTMLObjectElement.setCustomValidity - Web APIs
return value undefined exceptions none.
HTMLObjectElement.type - Web APIs
the type property of the htmlobjectelement interface returns a domstring that reflects the type html attribute, specifying the mime type of the resource.
HTMLObjectElement.useMap - Web APIs
the usemap property of the htmlobjectelement interface returns a domstring that reflects the usemap html attribute, specifying a <map> element to use.
HTMLObjectElement.validationMessage - Web APIs
the validationmessage read-only property of the htmlobjectelement interface returns a domstring representing a localized message that describes the validation constraints that the control does not satisfy (if any).
HTMLObjectElement.validity - Web APIs
the validity read-only property of the htmlobjectelement interface returns a validitystate with the validity states that this element is in.
HTMLObjectElement.width - Web APIs
the width property of the htmlobjectelement interface returns a domstring that reflects the width html attribute, specifying the displayed width of the resource in css pixels.
HTMLObjectElement.willValidate - Web APIs
the willvalidate read-only property of the htmlobjectelement interface returns a boolean that indicates whether the element is a candidate for constraint validation.
HTMLOptionElement - Web APIs
if this attribute isn't specifically set, reading it returns the element's text content.
HTMLOptionsCollection - Web APIs
this object is returned only by the options property of select.
HTMLOrForeignElement.dataset - Web APIs
instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes.
HTMLOrForeignElement - Web APIs
propertiesdataset read only the dataset read-only property of the htmlorforeignelement interface provides read/write access to all the custom data attributes (data-*) set on the element.nonce the nonce property of the htmlorforeignelement interface returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed.tabindexthe tabindex property of the htmlorforeignelement interface represents the tab order of the current element.methodsblur()the htmlelement.blur() method removes keyboard focus from the current element.focus()the htmlelement.focus() method sets focus on th...
HTMLScriptElement - Web APIs
htmlscriptelement.text is a domstring that joins and returns the contents of all text nodes inside the <script> element (ignoring other nodes like comments) in tree order.
HTMLSelectElement.checkValidity() - Web APIs
if the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
HTMLSelectElement.selectedOptions - Web APIs
if no options are currently selected, the collection is empty and returns a length of 0.
HTMLSelectElement.type - Web APIs
the htmlselectelement.type read-only property returns the form control's type.
HTMLShadowElement.getDistributedNodes() - Web APIs
the htmlshadowelement.getdistributednodes() method returns a static nodelist of the distributed nodes associated with this <shadow> element.
HTMLShadowElement - Web APIs
htmlshadowelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <shadow> element.
HTMLSlotElement.name - Web APIs
the name property of the htmlslotelement interface returns or sets the slot name.
HTMLStyleElement.type - Web APIs
the htmlstyleelement.type read-only property returns the type of the current style.
HTMLStyleElement - Web APIs
linkstyle.sheet read only returns the stylesheet object associated with the given element, or null if there is none htmlstyleelement.scoped is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true).
HTMLTableCellElement - Web APIs
if the cell doesn't belong to a <tr>, it returns -1.
HTMLTableElement.deleteRow() - Web APIs
return value no return value errors thrown if the number of the row to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception index_size_err is thrown.
HTMLTableElement.rules - Web APIs
syntax htmltableelement.rules = rules; var rules = htmltableelement.rules; parameters rules is a string with one of the following values: none no rules groups lines between groups only rows lines between rows cols lines between cols all lines between all cells example // turn on all the internal borders of a table var t = document.getelementbyid("tableid"); t.rules = "all"; specification w3c dom 2 html specification ...
HTMLTableRowElement.rowIndex - Web APIs
syntax var index = htmltablerowelement.rowindex value returns the index of the row, or -1 if the row is not part of a table.
HTMLTableSectionElement - Web APIs
htmltablesectionelement.rows read only returns a live htmlcollection containing the rows in the section.
HTMLTemplateElement.content - Web APIs
the htmltemplateelement.content property returns a <template> element's template contents (a documentfragment).
HTMLVideoElement.msFrameStep() - Web APIs
return value this method does not return a value.
HTMLVideoElement.msInsertVideoEffect() - Web APIs
return value this method does not return a value.
msSetVideoRectangle - Web APIs
return value this method does not return a value.
msStereo3DPackingMode - Web APIs
syntax htmlvideoelement.msstereo3dpackingmode(topbottom, sidebyside, none); value the following values return, or set, the stereo 3-d content packing as "topbottom", "sidebyside", or "none" for regular 2-d video.
Dragging and Dropping Multiple Items - Web APIs
as with the types property, it returns a list of strings of the types for an item.
HashChangeEvent.newURL - Web APIs
the newurl read-only property of the hashchangeevent interface returns the new url to which the window is navigating.
HashChangeEvent.oldURL - Web APIs
the oldurl read-only property of the hashchangeevent interface returns the previous url from which the window was navigated.
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 ) { return; } 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
WebAPIHistorystate
the history.state property returns 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) { return; } let lastprimarykey = getlastiteratedarticleid(); if (lastprimarykey > cursor.primarykey) { cursor.continueprimarykey("javascript", lastprimarykey); return; } // 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 returns the direction of traversal of the cursor (set using idbobjectstore.opencursor for example).
IDBCursor.key - Web APIs
WebAPIIDBCursorkey
the key read-only property of the idbcursor interface returns the key for the record at the cursor's position.
IDBCursor.primaryKey - Web APIs
the primarykey read-only property of the idbcursor interface returns the cursor's current effective key.
IDBCursor.request - Web APIs
WebAPIIDBCursorrequest
the request read-only property of the idbcursor interface returns the idbrequest used to obtain the cursor.
IDBCursorSync - Web APIs
returns false if the cursor has reached the end of its range; otherwise returns true.
IDBCursorWithValue.value - Web APIs
the value read-only property of the idbcursorwithvalue interface returns the value of the current cursor, whatever that is.
IDBCursorWithValue - Web APIs
idbcursorwithvalue.value read only returns the value of the current cursor.
IDBDatabase.close() - Web APIs
WebAPIIDBDatabaseclose
the close() method of the idbdatabase interface returns immediately and closes the connection in a separate thread.
IDBDatabase: error event - Web APIs
the error event is fired on idbdatabase when a request returns an error and the event bubbles up to the connection object.
IDBDatabase.onerror - Web APIs
the onerror event handler of the idbdatabase interface handles the error event, fired when a request returns an error and bubbles up to the connection object.
IDBFactory.cmp() - Web APIs
WebAPIIDBFactorycmp
return value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: returned 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: ...
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
return value idbkeyrange: the newly created key range.
IDBKeyRange.lower - Web APIs
WebAPIIDBKeyRangelower
the lower read-only property of the idbkeyrange interface returns the lower bound of the key range.
IDBKeyRange.lowerBound() - Web APIs
return value idbkeyrange: the newly created key range.
IDBKeyRange.lowerOpen - Web APIs
the loweropen read-only property of the idbkeyrange interface returns a boolean indicating whether the lower-bound value is included in the key range.
IDBKeyRange.only() - Web APIs
WebAPIIDBKeyRangeonly
return value idbkeyrange: the newly created key range.
IDBKeyRange.upper - Web APIs
WebAPIIDBKeyRangeupper
the upper read-only property of the idbkeyrange interface returns the upper bound of the key range.
IDBKeyRange.upperBound() - Web APIs
optional return value idbkeyrange: the newly created key range.
IDBKeyRange.upperOpen - Web APIs
the upperopen read-only property of the idbkeyrange interface returns a boolean indicating whether the upper-bound value is included in the key range.
FileHandle.getFile() - Web APIs
syntax var request = instanceoffilehandle.getfile(); return a domrequest object.
IDBObjectStore.autoIncrement - Web APIs
the autoincrement read-only property of the idbobjectstore interface returns the value of the auto increment flag for this object store.
IDBObjectStore.deleteIndex() - Web APIs
return value undefined exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction mode callback.
IDBObjectStore.indexNames - Web APIs
the indexnames read-only property of the idbobjectstore interface returns a list of the names of indexes on objects in this object store.
IDBObjectStore.keyPath - Web APIs
the keypath read-only property of the idbobjectstore interface returns the key path of this object store.
IDBObjectStore.transaction - Web APIs
the transaction read-only property of the idbobjectstore interface returns the transaction object to which this object store belongs.
IDBTransaction.commit() - Web APIs
return value void.
IDBTransaction: error event - Web APIs
the error event is fired on idbtransaction when a request returns an error and the event bubbles up to the transaction object.
IDBTransaction.onerror - Web APIs
the onerror event handler of the idbtransaction interface handles the error event, fired when a request returns an error and bubbles up to the transaction object.
IDBVersionChangeEvent.newVersion - Web APIs
the newversion read-only property of the idbversionchangeevent interface returns the new version number of the database.
IDBVersionChangeEvent.oldVersion - Web APIs
the oldversion read-only property of the idbversionchangeevent interface returns the old version number of the database.
IDBVersionChangeEvent.version - Web APIs
the version property of the idbversionchangeevent interface returns the new version of the database in a versionchange transaction.
IDBVersionChangeRequest - Web APIs
returns immediately and runs a versionchange transaction on the connected database in a separate thread.
IIRFilterNode() - Web APIs
return value a new iirfilternode object instance.
IIRFilterNode.getFrequencyResponse() - Web APIs
return value undefined exceptions notsupportederror the three arrays provided are not all of the same length.
IdleDeadline.didTimeout - Web APIs
if didtimeout is true, the idledeadline object's timeremaining() method will return approximately 0.
ImageBitmap.height - Web APIs
the read-only imagebitmap.height property returns the imagebitmap object's height in css pixels.
ImageBitmap.width - Web APIs
WebAPIImageBitmapwidth
the read-only imagebitmap.width property returns the imagebitmap object's width in css pixels.
ImageCapture() constructor - Web APIs
return value a new imagecapture object which can be used to capture still frames from the specified video track.
ImageCapture.track - Web APIs
the track read-only property of the imagecapture interface returns a reference to the mediastreamtrack passed to the imagecapture() constructor.
ImageData.data - Web APIs
WebAPIImageDatadata
the readonly imagedata.data property returns a uint8clampedarray that contains the imagedata object's pixel data.
ImageData.height - Web APIs
WebAPIImageDataheight
the readonly imagedata.height property returns the number of rows in the imagedata object.
ImageData.width - Web APIs
WebAPIImageDatawidth
the readonly imagedata.width property returns the number of pixels per row in the imagedata object.
Basic concepts - Web APIs
the api doesn't give you data by returning values; instead, you have to pass a callback function.
InputDeviceCapabilities - Web APIs
syntax var inputdevicecapabilities = new inputdevicecapabilities([inputdevicecapabilitiesinit]) returns an instance of the inputdevicecapabilities interface.
InputEvent.data - Web APIs
WebAPIInputEventdata
the data read-only property of the inputevent interface returns a domstring with the inserted characters.
InputEvent.dataTransfer - Web APIs
the datatransfer read-only property of the inputevent interface returns a datatransfer object containing information about richtext or plaintext data being added to or removed from editible content.
InputEvent.inputType - Web APIs
the inputtype read-only property of the inputevent interface returns the type of change made to editible content.
enabled - Web APIs
method of installtrigger object syntax boolean enabled (); parameters none returns true if software installation is enabled for this client machine; otherwise, false.
install - Web APIs
returns install returns true if the function succeeded and false if it did not, but these values are not always reliable as a determinant of the success of the operation.
startSoftwareUpdate - Web APIs
returns true.
InstallTrigger - Web APIs
getversion returns an object representing the version number from the client version registry for the specified component.
IntersectionObserver.disconnect() - Web APIs
return value undefined.
IntersectionObserver.observe() - Web APIs
return value undefined.
IntersectionObserver.rootMargin - Web APIs
the string returned by this property may not match the one specified when the intersectionobserver was instantiated.
IntersectionObserver.thresholds - Web APIs
the intersectionobserver interface's read-only thresholds property returns the list of intersection thresholds that was specified when the observer was instantiated with intersectionobserver().
IntersectionObserver.unobserve() - Web APIs
return value undefined.
IntersectionObserverEntry.boundingClientRect - Web APIs
the intersectionobserverentry interface's read-only boundingclientrect property returns a domrectreadonly which in essence describes a rectangle describing the smallest rectangle that contains the entire target element.
IntersectionObserverEntry.intersectionRatio - Web APIs
if the area of the target's bounds rectangle is zero, the returned value is 1 if isintersecting is true or 0 if not.
InterventionReportBody - Web APIs
the interventionreportbody interface of the reporting api represents the body of an intervention report (the return value of its report.body property).
KeyboardEvent.altKey - Web APIs
syntax var altkeypressed = instanceofkeyboardevent.altkey return 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_return (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) { return; // 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.keyIdentifier - Web APIs
the deprecated keyboardevent.keyidentifier read-only property returns a "key identifier" string that can be used to determine what key was pressed.
KeyboardEvent.shiftKey - Web APIs
syntax var shiftkeypressed = instanceofkeyboardevent.shiftkey return 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 returns 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.forEach() - Web APIs
return value undefined.
KeyboardLayoutMap.keys - Web APIs
the keys read-only property of the keyboardlayoutmap interface returns a new array iterator object that contains the keys for each index in the array.
KeyboardLayoutMap.size - Web APIs
the size read-only property of the keyboardlayoutmap interface returns the number of elements in the map.
KeyboardLayoutMap.values - Web APIs
the values read-only property of the keyboardlayoutmap interface returns 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 returns 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 returns 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 returns 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 returns a double precision integer containing the acceleration of the device along the device's z axis.
LocalMediaStream - Web APIs
however, getusermedia() now returns a mediastream instead, and this interface has been removed from the specification.
Location: hostname - Web APIs
WebAPILocationhostname
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; // returns:'developer.mozilla.org' specifications specification status comment html living standardthe definition of 'hostname' in that specification.
Location: origin - Web APIs
WebAPILocationorigin
syntax string = object.origin; examples // on this page, returns the origin var result = window.location.origin; // returns:'https://developer.mozilla.org' specifications specification status comment html living standardthe definition of 'origin' in that specification.
Location: password - Web APIs
WebAPILocationpassword
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; // returns:'flabada' ...
Location: pathname - Web APIs
WebAPILocationpathname
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; // returns:'/docs/location.pathname' specifications specification status comment html living standardthe definition of 'pathname' in that specification.
Location: port - Web APIs
WebAPILocationport
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; // returns:'443' specifications specification status comment html living standardthe definition of 'location.port' in that specification.
Location: protocol - Web APIs
WebAPILocationprotocol
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; // returns:'https:' specifications specification status comment html living standardthe definition of 'protocol' in that specification.
Location: search - Web APIs
WebAPILocationsearch
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; // returns:'?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
WebAPILocationusername
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; // returns:'anonymous' ...
LockManager - Web APIs
lockmanager.query() returns a promise that resolves with a lockmanagersnapshot which contains information about held and pending locks.
LockedFile.abort() - Web APIs
WebAPILockedFileabort
syntax var request = instanceoflockedfile.abort(); return a filerequest object to handle the success or failure of the operation.
LockedFile.append() - Web APIs
WebAPILockedFileappend
return a filerequest object to handle the success or failure of the operation.
LockedFile.flush() - Web APIs
WebAPILockedFileflush
syntax var request = instanceoflockedfile.flush(); return a filerequest object to handle the success or failure of the operation.
LockedFile.getMetadata() - Web APIs
the following metadata are supported: size : will provide the size of the file lastmodified : will provide the date when the file was last modified return a filerequest object.
LockedFile.readAsArrayBuffer() - Web APIs
return a filerequest object to handle the success or failure of the operation.
LockedFile.truncate() - Web APIs
return a filerequest object to handle the success or failure of the operation.
LockedFile.write() - Web APIs
WebAPILockedFilewrite
return a filerequest object to handle the success or failure of the operation.
MIDIConnectionEvent - Web APIs
properties midiconnectionevent.port returns a reference to a midiport instance for a port that has been connected or disconnected." examples specifications specification status comment web midi api working draft initial definition.
MIDIMessageEvent - Web APIs
note: even though the web midi api specifies a receivedtime property that returns a domhighrestimestamp, chrome (the only implementation at the time of writing) does not support that property since the basic event.timestamp property already returns a domhighrestimestamp in chrome.
MSCandidateWindowHide - Web APIs
the handler of this event will see that the iscandidatewindowvisible method returns false, and no clientrect object is returned from getcandidatewindowclientrect.
MSManipulationEvent.initMSManipulationEvent() - Web APIs
return value this method does not return a value.
Magnetometer.Magnetometer() - Web APIs
the magnetometer constructor creates a new magnetometer object which returns information about the magnetic field as detected by a device’s primary magnetometer sensor.
Magnetometer.x - Web APIs
WebAPIMagnetometerx
the x read-only property of the magnetometer interface returns a double precision integer containing the magnetic field around the device's x axis.
Magnetometer.y - Web APIs
WebAPIMagnetometery
the y read-only property of the magnetometer interface returns a double precision integer containing the magnetic field around the device's y axis.
Magnetometer.z - Web APIs
WebAPIMagnetometerz
the z read-only property of the magnetometer interface returns a double-precision integer containing the magnetic field around the device's z axis.
MediaCapabilitiesInfo - Web APIs
the interface of the promise returned by the the mediacapabilities's encodinginfo() and decodinginfo() methods returning whether the media configuration tested is supported, smooth, and powerefficient.
MediaCapabilitiesInfo - Web APIs
the mediacapabilitiesinfo interface of the media capabilities api is made available when the promise returned by the mediacapabilities.encodinginfo() or mediacapabilities.decodinginfo() methods of the mediacapabilities interface fulfills, providing information as to whether the media type is supported, and whether encoding or decoding such media would be smooth and power efficient.
MediaDeviceInfo.deviceId - Web APIs
the deviceid readonly property of the mediadeviceinfo interface returns a domstring that is an identifier for the represented device and is persisted across sessions.
MediaDeviceInfo.kind - Web APIs
the kind readonly property of the mediadeviceinfo interface returns an enumerated value, that is either "videoinput", "audioinput" or "audiooutput".
MediaDeviceInfo.label - Web APIs
the label readonlyinline property of the mediadeviceinfo interface returns a domstring, that is a label describing this device (for example "external usb webcam").
MediaElementAudioSourceNode() - Web APIs
return value a new mediaelementaudiosourcenode object instance.
MediaError.code - Web APIs
WebAPIMediaErrorcode
the read-only property mediaerror.code returns a numeric value which represents the kind of error that occurred on a media element.
MediaError.message - Web APIs
the read-only property mediaerror.message returns a domstring which contains a human-readable string offering specific diagnostic details related to the error described by the mediaerror object, or an empty string ("") if no diagnostic information can be determined or provided.
message - Web APIs
the mediakeymessageevent.message read-only property returns an arraybuffer with a message from the content decryption module.
MediaKeyMessageEvent - Web APIs
mediakeymessageevent.message read only returns an arraybuffer with a message from the content decryption module.
MediaKeySession.closed - Web APIs
the mediakeysession.closed read-only property returns a promise signaling when a mediakeysession closes.
expiration - Web APIs
the mediakeysession.expiration read-only property returns the time after which the keys in the current session can no longer be used to decrypt media data, or nan if no such time exists.
generateRequest() - Web APIs
the mediakeysession.generaterequest() method returns a promise after generating a media request based on initialization data.
keyStatuses - Web APIs
the mediakeysession.keystatuses read-only property returns a reference to a read-only mediakeystatusmap of the current session's keys and their statuses.
MediaKeyStatusMap.forEach() - Web APIs
returns undefined.
MediaKeyStatusMap.size - Web APIs
the size read-only property of the mediakeystatusmap interface returns the number of key/value pairs in the status map.
createMediaKeys() - Web APIs
the mediakeysystemaccess.createmediakeys() method returns a promise that resolves to a new mediakeys object.
getConfiguration() - Web APIs
the mediakeysystemaccess.getconfiguration() method returns a mediakeysystemconfiguration object with the supported combination of configuration options.
keySystem - Web APIs
the mediakeysystemaccess.keysystem read-only property returns a domstring identifying the key system being used.
audioCapabilities - Web APIs
the mediakeysystemconfiguration.audiocapabilities read-only property returns an array of supported audio type and capability pairs.
initDataTypes - Web APIs
the mediakeysystemconfiguration.initdatatypes read-only property returns a list of supported initialization data type names.
videoCapabilities - Web APIs
the mediakeysystemconfiguration.videocapabilities read-only property returns an array of supported video type and capability pairs.
createSession() - Web APIs
the mediakeys.createsession() method returns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
MediaList.mediaText - Web APIs
the mediatext property of the medialist interface is a stringifier that returns a domstring representing the medialist as text, and also allows you to set a new medialist.
MediaMetadata.album - Web APIs
the album property of the mediametadata interface returns or sets the name of the album or collection containing the media to be played.
MediaMetadata.artist - Web APIs
the artist property of the mediametadata interface returns or sets the name of the artist, group, creator, etc., of the media to be played.
MediaMetadata.artwork - Web APIs
the artwork property of the mediametadata interface returns or sets an array of mediaimage objects representing images associated with playing media.
MediaMetadata.title - Web APIs
the title property of the mediametadata interface returns or sets the title of the media to be played.
MediaPositionState.duration - Web APIs
this information can then, in turn, be used by the user agent to provide a user interface which displays media playback information to the viewer.
MediaPositionState.playbackRate - Web APIs
this information can then, in turn, be used by the user agent to provide a user interface which displays media playback information to the viewer.
MediaPositionState.position - Web APIs
this information is then, in turn, used by the user agent to provide a user interface which displays media playback information to the viewer.
MediaQueryList.addListener() - Web APIs
return value void.
MediaQueryList.matches - Web APIs
the matches read-only property of the mediaquerylist interface is a boolean that returns true if the document currently matches the media query list, or false if not.
MediaQueryList.removeListener() - Web APIs
return value void.
MediaQueryList - Web APIs
matchesread only a boolean that returns true if the document currently matches the media query list, or false if not.
MediaQueryListEvent - Web APIs
mediaquerylistevent.matchesread only a boolean that returns true if the document currently matches the media query list, or false if not.
MediaRecorder.audioBitsPerSecond - Web APIs
the audiobitspersecond read-only property of the mediarecorder interface returns the audio encoding bit rate in use.
MediaRecorder.pause() - Web APIs
syntax mediarecorder.pause() return value undefined.
MediaRecorder.start() - Web APIs
return value undefined.
MediaRecorder.stream - Web APIs
the mediarecorder.stream read-only property returns the stream that was passed into the mediarecorder() constructor when the mediarecorder was created.
MediaRecorder.videoBitsPerSecond - Web APIs
the videobitspersecond read-only property of the mediarecorder interface returns the video encoding bit rate in use.
MediaSession.setPositionState() - Web APIs
return value undefined.
MediaSession - Web APIs
properties metadata returns an instance of mediametadata which contains rich media metadata, for display in a platform ui.
MediaSessionActionDetails.fastSeek - Web APIs
your handler should take steps to return as quickly as possible by skipping any steps of its operation which are only necessary when the seek operation is complete.
MediaSettingsRange.max - Web APIs
the max read-only property of the mediasettingsrange interface returns the maximum value of the settings range.
MediaSettingsRange.min - Web APIs
the min read-only property of the mediasettingsrange interface returns the minimum value of the settings range.
MediaSettingsRange.step - Web APIs
the step read-only property of the mediasettingsrange interface returns the minimum difference between consecutive values of the settings range.
MediaSource.MediaSource() - Web APIs
the mediasource() constructor of the mediasource interface constructs and returns a new mediasource object with no associated source buffers.
MediaSource.activeSourceBuffers - Web APIs
the activesourcebuffers read-only property of the mediasource interface returns a sourcebufferlist object containing a subset of the sourcebuffer objects contained within sourcebuffers — the list of objects providing the selected video track, enabled audio tracks, and shown/hidden text tracks.
MediaSource.clearLiveSeekableRange() - Web APIs
return value undefined specifications specification status comment media source extensionsthe definition of 'clearliveseekablerange()' in that specification.
MediaSource.endOfStream() - Web APIs
return value undefined exceptions exception explanation invalidstateerror mediasource.readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e.
MediaSource.readyState - Web APIs
the readystate read-only property of the mediasource interface returns an enum representing the state of the current mediasource.
MediaSource.removeSourceBuffer() - Web APIs
return value undefined exceptions exception explanation notfounderror the supplied sourcebuffer doesn't exist in mediasource.sourcebuffers.
MediaSource.sourceBuffers - Web APIs
the sourcebuffers read-only property of the mediasource interface returns a sourcebufferlist object containing the list of sourcebuffer objects associated with this mediasource.
MediaStream.addTrack() - Web APIs
return value undefined example specifications specification status comment media capture and streamsthe definition of 'addtrack()' in that specification.
MediaStream.clone() - Web APIs
WebAPIMediaStreamclone
return value a new mediastream instance which has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called.
MediaStreamAudioDestinationNode.MediaStreamAudioDestinationNode() - Web APIs
return value a new mediastreamaudiodestinationnode object instance.
MediaStreamEvent.stream - Web APIs
the read-only property mediastreamevent.stream returns the mediastream associated with the event.
MediaStreamEvent - Web APIs
constructors mediastreamevent() returns a new mediastreamevent.
MediaStreamTrack.applyConstraints() - Web APIs
return value a promise which resolves when the constraints have been successfully applied.
MediaStreamTrack.clone() - Web APIs
syntax const newtrack = track.clone() return value a new mediastreamtrack instance which is identical to the one clone() was called, except for its new unique id.
MediaStreamTrack.enabled - Web APIs
for example, the green "in use" light next to the camera in imac and macbook computers turns off while the track is muted in this way.
MediaStreamTrack.id - Web APIs
the mediastreamtrack.id read-only property returns a domstring containing a unique identifier (guid) for the track, which is generated by the user agent.
MediaStreamTrack.kind - Web APIs
the mediastreamtrack.kind read-only property returns 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 returns 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 returns a boolean value indicating whether or not the track is currently unable to provide media output.
MediaStreamTrack.readyState - Web APIs
the mediastreamtrack.readystate read-only property returns an enumerated value giving the status of the track.
MediaStreamTrack.remote - Web APIs
it returns 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned 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 returned by a call to mediadevices.getsupportedconstraints().
MediaTrackSettings.logicalSurface - Web APIs
a visible display surface (that is, a surface for which logicalsurface returns false) is the portion of a logical display surface which is currently visible onscreen.
MediaTrackSettings.noiseSuppression - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as returned 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 returned 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 returned 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 returned 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 returned by a call to mediadevices.getsupportedconstraints().
MediaTrackSettings - Web APIs
the mediatracksettings dictionary is used to return 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 returned 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 returned 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 returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the channelcount constraint.
MediaTrackSupportedConstraints.cursor - Web APIs
capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
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 returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the deviceid constraint.
MediaTrackSupportedConstraints.displaySurface - Web APIs
capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
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 returned 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 returned 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 returned 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 returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the groupid constraint.
MediaTrackSupportedConstraints.height - Web APIs
the mediatracksupportedconstraints dictionary's height property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the height constraint.
MediaTrackSupportedConstraints.latency - Web APIs
the mediatracksupportedconstraints dictionary's latency property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the latency constraint.
MediaTrackSupportedConstraints.logicalSurface - Web APIs
capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
the mediatracksupportedconstraints dictionary's noisesuppression property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the noisesuppression constraint.
MediaTrackSupportedConstraints.sampleRate - Web APIs
the mediatracksupportedconstraints dictionary's samplerate property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the samplerate constraint.
MediaTrackSupportedConstraints.sampleSize - Web APIs
the mediatracksupportedconstraints dictionary's samplesize property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the samplesize constraint.
MediaTrackSupportedConstraints.volume - Web APIs
the mediatracksupportedconstraints dictionary's volume property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the volume constraint.
MediaTrackSupportedConstraints.width - Web APIs
the mediatracksupportedconstraints dictionary's width property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the width constraint.
MediaTrackSupportedConstraints - Web APIs
an object conforming to mediatracksupportedconstraints is returned by mediadevices.getsupportedconstraints().
Media Capabilities API - Web APIs
mediacapabilitiesinfo the interface of the promise returned by the mediacapabilities's encodinginfo() and decodinginfo() methods; returning whether the media configuration tested is supported, smooth, and powerefficient.
MerchantValidationEvent() - Web APIs
return value a newly-created merchantvalidationevent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete().
MerchantValidationEvent.complete() - Web APIs
return value undefined.
MerchantValidationEvent.methodName - Web APIs
the merchantvalidationevent property methodname is a read-only value which returns a string indicating the payment method identifier which represents the payment handler that requires merchant validation.
MessageChannel.port1 - Web APIs
the port1 read-only property of the messagechannel interface returns the first port of the message channel — the port attached to the context that originated the channel.
MessageChannel.port2 - Web APIs
the port2 read-only property of the messagechannel interface returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to.
MessagePort.close() - Web APIs
WebAPIMessagePortclose
syntax port.close() returns void.
MessagePort.postMessage() - Web APIs
syntax port.postmessage(message, transferlist); returns void.
MessagePort.start() - Web APIs
WebAPIMessagePortstart
syntax port.start() returns void.
MouseEvent.altKey - Web APIs
WebAPIMouseEventaltKey
syntax var altkeypressed = instanceofmouseevent.altkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed.
MouseEvent.buttons - Web APIs
syntax var buttonspressed = instanceofmouseevent.buttons return value a number representing one or more buttons.
MouseEvent.clientX - Web APIs
syntax var x = instanceofmouseevent.clientx return value a double floating point value, as redefined by the cssom view module.
MouseEvent.clientY - Web APIs
syntax var y = instanceofmouseevent.clienty return value a double floating point value, as redefined by the cssom view module.
MouseEvent.ctrlKey - Web APIs
syntax var ctrlkeypressed = instanceofmouseevent.ctrlkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed.
MouseEvent.metaKey - Web APIs
syntax var metakeypressed = instanceofmouseevent.metakey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed.
MouseEvent.movementX - Web APIs
syntax var xshift = instanceofmouseevent.movementx; return value a number example this example logs the amount of mouse movement using movementx and movementy.
MouseEvent.movementY - Web APIs
syntax var yshift = instanceofmouseevent.movementy; return value a number example this example logs the amount of mouse movement using movementx and movementy.
MouseEvent.mozInputSource - Web APIs
syntax var source = instanceofmouseevent.mozinputsource; return value the following values are possible.
MouseEvent.offsetX - Web APIs
syntax var xoffset = instanceofmouseevent.offsetx; return value a double floating point value.
MouseEvent.offsetY - Web APIs
syntax var yoffset = instanceofmouseevent.offsety; return value a double floating point value.
MouseEvent.pageY - Web APIs
WebAPIMouseEventpageY
the pagey read-only property of the mouseevent interface returns the y (vertical) coordinate in pixels of the event relative to the whole document.
MouseEvent.screenX - Web APIs
syntax var x = instanceofmouseevent.screenx return value a double floating point value.
MouseEvent.screenY - Web APIs
syntax var y = instanceofmouseevent.screeny return value a double floating point value.
MouseEvent.shiftKey - Web APIs
syntax var shiftkeypressed = instanceofmouseevent.shiftkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed.
MouseEvent.which - Web APIs
WebAPIMouseEventwhich
syntax var buttonpressed = instanceofmouseevent.which return value a number representing a given button: 0: no button 1: left button 2: middle button (if present) 3: right button for a mouse configured for left-handed use, the button actions are reversed.
MouseWheelEvent - Web APIs
the mousewheelevent interface represents events that occur due to the user turning a mouse wheel.
msGraphicsTrustStatus - Web APIs
msgraphicstruststatus is a read-only property which returns an object containing information on protected video playback.
msIsBoxed - Web APIs
WebAPIMsIsBoxed
returns true if the video is in letterbox or pillarbox mode.
msSetMediaProtectionManager - Web APIs
return value this method does not return a value.
MutationObserver.disconnect() - Web APIs
return value undefined.
MutationObserver.observe() - Web APIs
return value undefined.
NDEFMessage - Web APIs
constructor ndefmessage.ndefmessage() returns a new ndefmessage containing specified data.
NDEFReader - Web APIs
constructor ndefreader.ndefreader() returns an ndefreader with configuration specified in the parameters or default ones if no parameters are specified.
NDEFRecord - Web APIs
constructor ndefrecord() returns a new ndefrecord with configuration specified in the parameters or default ones if no parameters are specified.
NDEFWriter - Web APIs
constructor ndefwriter.ndefwriter() returns an ndefwriter.
NamedNodeMap.getNamedItem() - Web APIs
the getnameditem() method of the namednodemap interface returns the attr corresponding to the given name, or null if there is no corresponding attribute.
Navigator.connection - Web APIs
the navigator.connection read-only property returns a networkinformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered.
Navigator.credentials - Web APIs
the credentials property of the navigator interface returns the credentialscontainer interface, which exposes methods to request credentials.
Navigator.deviceMemory - Web APIs
the devicememory read-only property of the navigator interface returns the approximate amount of device memory in gigabytes.
Navigator.doNotTrack - Web APIs
the navigator.donottrack property returns the user's do not track setting, which indicates whether the user is requesting web sites and advertisers to not track them.
Navigator.geolocation - Web APIs
the navigator.geolocation read-only property returns a geolocation object that gives web content access to the location of the device.
Navigator.getGamepads() - Web APIs
the navigator.getgamepads() method returns an array of gamepad objects, one for each gamepad connected to the device.
Navigator.keyboard - Web APIs
the keyboard read-only property of the navigator interface returns a keyboard object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
Navigator.locks - Web APIs
WebAPINavigatorlocks
the locks read-only property of the navigator interface returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
Navigator.maxTouchPoints - Web APIs
the maxtouchpoints read-only property of the navigator interface returns the maximum number of simultaneous touch contact points are supported by the current device.
Navigator.mediaCapabilities - Web APIs
the navigator.mediacapabilities read-only property returns a mediacapabilities object that can expose information about the decoding and encoding capabilities for a given format and output capabilities as defined by the media capabilities api.
Navigator.msLaunchUri() - Web APIs
return value undefined.
msSaveBlob - Web APIs
return value true is returned as long as the download notification bar is displayed, or false if a failure occured.
msSaveOrOpenBlob - Web APIs
return value true is returned as long as the download notification bar is displayed, or false if a failure occurred.
Navigator.oscpu - Web APIs
WebAPINavigatoroscpu
the navigator.oscpu property returns a string that identifies the current operating system.
Navigator.permissions - Web APIs
the navigator.permissions read-only property returns a permissions object that can be used to query and update permission status of apis covered by the permissions api.
Navigator.serviceWorker - Web APIs
the navigator.serviceworker read-only property returns the serviceworkercontainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the serviceworker.
Navigator.share() - Web APIs
WebAPINavigatorshare
return value a promise that will be fulfilled once a user has completed a share action (usually the user has chosen an application to share to).
Navigator.vibrate() - Web APIs
WebAPINavigatorvibrate
if the method was unable to vibrate because of invalid parameters, it will return false, else it returns true.
Navigator.xr - Web APIs
WebAPINavigatorxr
the read-only xr property provided by the navigator or workernavigator interface returns an xr object which can be used to access the webxr device api.
NavigatorID.taintEnabled() - Web APIs
the navigatorid.taintenabled() method always returns false.
NavigatorID.userAgent - Web APIs
the navigatorid.useragent read-only property returns the user agent string for the current browser.
NavigatorOnLine - Web APIs
navigatoronline.online read only returns a boolean indicating whether the browser is working online.
NavigatorPlugins.javaEnabled() - Web APIs
syntax result = window.navigator.javaenabled() example if (window.navigator.javaenabled()) { // browser has java } notes the return value for this method indicates whether the preference that controls java is on or off - not whether the browser offers java support in general.
NetworkInformation.downlink - Web APIs
the downlink read-only property of the networkinformation interface returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.
NetworkInformation.effectiveType - Web APIs
the effectivetype read-only property of the networkinformation interface returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'.
NetworkInformation.saveData - Web APIs
the networkinformation.savedata read-only property of the networkinformation interface returns true if the user has set a reduced data usage option on the user agent.
Node.childNodes - Web APIs
WebAPINodechildNodes
the node.childnodes read-only property returns a live nodelist of child nodes of the given element where the first child node is assigned index 0.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
the node.clonenode() method returns a duplicate of the node on which this method was called.
Node.getUserData() - Web APIs
WebAPINodegetUserData
the node.getuserdata() method returns any user domuserdata set previously on the given node by node.setuserdata().
Node.lookupPrefix() - Web APIs
WebAPINodelookupPrefix
the node.lookupprefix() method returns a domstring containing the prefix for a given namespace uri, if present, and null if not.
Node.nextSibling - Web APIs
WebAPINodenextSibling
the node.nextsibling read-only property returns the node immediately following the specified one in their parent's childnodes, or returns null if the specified node is the last child in the parent element.
Node.nodePrincipal - Web APIs
the node.nodeprincipal read-only property returns the nsiprincipal object representing current security context of the node.
Node.nodeType - Web APIs
WebAPINodenodeType
syntax var type = node.nodetype; returns an integer which specifies the type of the node.
Node.ownerDocument - Web APIs
the ownerdocument read-only property of the node interface returns the top-level document object of the node.
Node.parentElement - Web APIs
the node.parentelement read-only property returns 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
WebAPINodeprefix
the node.prefix read-only property returns the namespace prefix of the specified node, or null if no prefix is specified.
Node.previousSibling - Web APIs
the node.previoussibling read-only property returns 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.
Node.removeChild() - Web APIs
WebAPINoderemoveChild
the node.removechild() method removes a child node from the dom and returns the removed node.
Node.replaceChild() - Web APIs
WebAPINodereplaceChild
return value the returned value is the replaced node.
NodeIterator.detach() - Web APIs
syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return 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
WebAPINodeIteratorroot
syntax root = nodeiterator.root; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = nodeiterator.root; // document.body in this case specifications specification status comment domthe definition of 'nodeiterator.root' in that specification.
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
return value undefined.
NodeList.length - Web APIs
WebAPINodeListlength
the nodelist.length property returns the number of items in a nodelist.
Notification.actions - Web APIs
the actions read-only property of the notification interface returns 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 returns the url of the image used to represent the notification when there is not enough space to display the notification itself.
Notification.close() - Web APIs
returns void.
Notification.dir - Web APIs
WebAPINotificationdir
var options = { body: 'do you like my body?', dir: 'rtl' } var n = new notification('test notification',options); console.log(n.dir) // should return 'rtl' specifications specification status comment notifications apithe definition of 'dir' in that specification.
Notification.lang - Web APIs
WebAPINotificationlang
var options = { body: 'do you like my body?', lang: 'en-us' } var n = new notification('test notification',options); console.log(n.lang) // should return 'en-us' specifications specification status comment notifications apithe definition of 'lang' in that specification.
Notification.maxActions - Web APIs
the maxactions attribute of the notification interface returns the maximum number of actions supported by the device and the user agent.
Notification.requireInteraction - Web APIs
the requireinteraction read-only property of the notification interface returns a boolean indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically.
Notification.timestamp - Web APIs
the timestamp read-only property of the notification interface returns a domtimestamp, as specified in the timestamp option of the notification() constructor.
Notification - Web APIs
notification.data read only returns a structured clone of the notification’s data.
OES_vertex_array_object.bindVertexArrayOES() - Web APIs
return value none.
OES_vertex_array_object.createVertexArrayOES() - Web APIs
return value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data.
OES_vertex_array_object.deleteVertexArrayOES() - Web APIs
return value none.
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
return value none.
OVR_multiview2 - Web APIs
calling checkframebufferstatus for a framebuffer in this state returns framebuffer_incomplete_view_targets_ovr.
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
return value a new offlineaudiocompletionevent object instance.
OfflineAudioContext.length - Web APIs
the length property of the offlineaudiocontext interface returns an integer representing the size of the buffer in sample-frames.
OfflineAudioContext.resume() - Web APIs
returns a promise resolving to void.
OffscreenCanvas.convertToBlob() - Web APIs
return value a promise returning a blob object representing the image contained in the canvas.
OffscreenCanvas() - Web APIs
the offscreencanvas() constructor returns a newly instantiated offscreencanvas object.
OffscreenCanvas.convertToBlob() - Web APIs
return value a promise returning a blob object representing the image contained in the canvas.
OffscreenCanvas.convertToBlob() - Web APIs
return value a promise returning a blob object representing the image contained in the canvas.
OffscreenCanvas.transferToImageBitmap() - Web APIs
syntax imagebitmap offscreencanvas.transfertoimagebitmap() return value an imagebitmap.
OrientationSensor.populateMatrix() - Web APIs
parameters targetmatrix tbd return value undefined example // tbd specifications specification status comment orientation sensorthe definition of 'populatematrix' in that specification.
OrientationSensor.quaternion - Web APIs
the quaternion read-only property of the orientationsensor interface returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation.
OrientationSensor - Web APIs
absoluteorientationsensor relativeorientationsensor properties orientationsensor.quaternion returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation.
OscillatorNode.OscillatorNode() - Web APIs
return value a new oscillatornode object instance.
OscillatorNode.detune - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents note: though the audioparam returned is read-only, the value it represents is not.
OscillatorNode.frequency - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz note: though the audioparam returned is read-only, the value it represents is not.
OscillatorNode.setPeriodicWave() - Web APIs
returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave.
OverconstrainedError.constraint - Web APIs
the constraint read-only property of the overconstrainederror interface returns the constraint that was supplied in the constructor, meaning the contraint that was not satisfied.
OverconstrainedError.message - Web APIs
the message read-only property of the overconstrainederror interface returns the text supplied in the constructor.
OverconstrainedError.name - Web APIs
the name read-only property of the overconstrainederror interface will always return 'overconstrainederror'.
Paint​Worklet​.device​Pixel​Ratio - Web APIs
the paintworklet.devicepixelratio read-only property of the paintworklet interface returns the current device's ratio of physical pixels to logical pixels.
PaintWorklet.devicePixelRatio - Web APIs
the paintworklet.devicepixelratio read-only property of the paintworklet interface returns the current device's ratio of physical pixels to logical pixels.
PaintWorklet.devicePixelRatio - Web APIs
the paintworklet.devicepixelratio read-only property of the paintworklet interface returns the current device's ratio of physical pixels to logical pixels.
PaintWorklet.registerPaint - Web APIs
return value undefined exceptions typeerror thrown when one of the arguments is invalid or missing.
PaintWorklet - Web APIs
properties paintworklet.devicepixelratio returns the current device's ratio of physical pixels to logical pixels.
PannerNode.PannerNode() - Web APIs
return value a new pannernode object instance.
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 return [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 return [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 return [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 return [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 return [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 return [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.setOrientation() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setorientation(1,0,0); returns void.
PannerNode.setPosition() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setposition(0,0,0); returns void.
PannerNode.setVelocity() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setvelocity(0,0,17); returns void.
ParentNode.replaceChildren() - Web APIs
syntax // [throws, unscopable] parentnode.replacechildren(...nodesordomstrings) // returns undefined parameters nodesordomstrings a set of node or domstring objects to replace the parentnode's existing children with.
PasswordCredential.iconURL - Web APIs
the iconurl read-only property of the passwordcredential interface returns a usvstring containing a url pointing to an image for an icon.
PasswordCredential.idName - Web APIs
the idname property of the passwordcredential interface returns a usvstring, representing the name that will be used for the id field, when submitting the current object to a remote endpoint via fetch.
PasswordCredential.name - Web APIs
the name read-only property of the passwordcredential interface returns a usvstring containing a human-readable public name for display in a credential chooser.
PasswordCredential.password - Web APIs
the password read-only property of the passwordcredential interface returns a usvstring containing the password of the credential.
PasswordCredential.passwordName - Web APIs
the passwordname property of the passwordcredential interface returns a usvstring, depicting the name used by the password field, when submitting the current object to a remote endpoint via fetch.
Path2D() - Web APIs
WebAPIPath2DPath2D
the path2d() constructor returns 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
WebAPIPayerErrorsname
the name property is included in a payererrors object if the payername returned in the response couldn't be validated.
PayerErrors.phone - Web APIs
WebAPIPayerErrorsphone
the phone property is found in a payererrors object if the payername returned 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 returns a string containing the city or town portion of the address.
PaymentAddress.languageCode - Web APIs
the languagecode read-only property of the paymentaddress interface returns a string containing the bcp-47 language code for the address.
PaymentAddress.organization - Web APIs
the organization read-only property of the paymentaddress interface returns 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 returns 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 returns 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 returns a string containing the name of the recipient, purchaser, or contact person at the payment address.
PaymentAddress.sortingCode - Web APIs
the sortingcode read-only property of the paymentaddress interface returns a string containing a postal sorting code such as is used in france.
PaymentAddress - Web APIs
methods paymentaddress.tojson() a standard serializer that returns 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]+)?$/; return validregex.test(price); } this function, checkpriceformat(), will return 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 returning 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 returns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time.
PaymentMethodChangeEvent - Web APIs
return 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 returns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary.
PaymentRequest.PaymentRequest() - Web APIs
return value a new paymentrequest object, configured for use as configured by the input parameters.
PaymentRequest.abort() - Web APIs
syntax paymentrequest.abort(); returns void.
PaymentRequest.onmerchantvalidation - Web APIs
examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
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 = []; return 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]; return promise.resolve(details); })(details, request.shippingaddress)); }); specific...
PaymentRequest.shippingAddress - Web APIs
the shippingaddress read-only property of the paymentrequest interface returns the shipping address provided by the user.
PaymentRequest.shippingType - Web APIs
the shippingtype read-only property of the paymentrequest interface returns 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 returns 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 returns 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.
PaymentRequestEvent.modifiers - Web APIs
the modifiers read-only property of the paymentrequestevent interface returns an array of objects containing changes to payment details.
paymentRequestId - Web APIs
the paymentrequestid read-only property of the paymentrequestevent interface returns the id of the paymentrequest object.
PaymentRequestEvent.paymentRequestOrigin - Web APIs
the paymentrequestorigin read-only property of the paymentrequestevent interface returns the origin where the paymentrequest object was initialized.
PaymentRequestEvent.respondWith() - Web APIs
return value a paymentresponse object.
PaymentRequestEvent.topOrigin - Web APIs
the toporigin read-only property of the paymentrequestevent interface returns the top level payee origin where the paymentrequest object was initialized.
PaymentRequestEvent.total - Web APIs
the total readonly property of the paymentrequestevent interface returns a paymentcurrencyamount object containing the total amount being requested for payment.
PaymentRequestUpdateEvent.PaymentRequestUpdateEvent() - Web APIs
return value a new paymentrequestupdateevent object.payment request apithe definition of 'paymentrequestupdateevent' in that specification.
PaymentRequestUpdateEvent.updateWith() - Web APIs
return value undefined.
PaymentResponse.onpayerdetailchange - Web APIs
response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by calling a function // that validates each type of data, returning a promise which // resolves if the data is valid.
PaymentResponse.payerEmail - Web APIs
the payeremail read-only property of the paymentresponse interface returns the email address supplied by the user.
PaymentRequest.payerName - Web APIs
the payername read-only property of the paymentresponse interface returns the name supplied by the user.
PayerResponse.payerPhone - Web APIs
the payerphone read-only property of the paymentresponse interface returns the phone number supplied by the user.
PaymentResponse: payerdetailchange event - Web APIs
response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by calling a function // that validates each type of data, returning a promise which // resolves if the data is valid.
PaymentResponse.requestId - Web APIs
the requestid read-only property of the paymentresponse interface rreturns the free-form identifier supplied by the paymentresponse() constructor by details.id.
PaymentResponse.shippingAddress - Web APIs
the shippingaddress read-only property of the paymentrequest interface returns a paymentaddress object containing the shipping address provided by the user.
PaymentValidationErrors - Web APIs
when validation of the paymentresponse returned by the paymentrequest.show() or paymentresponse.retry() methods fails, your code creates a paymentvalidationerrors object to pass into retry() so that the user agent knows what needs to be fixed and what if any error messages to display to the user.
Payment processing concepts - Web APIs
this results in the creation and returning of a payment method-specific object that contains the information needed to handle the transaction.
Payment Request API - Web APIs
paymentresponse an object returned after the user selects a payment method and approves a payment request.
performance.clearMarks() - Web APIs
return value void example the following example shows both uses of the clearmarks() method.
performance.clearMeasures() - Web APIs
return value void example the following example shows both uses of the clearmeasures() method.
performance.mark() - Web APIs
WebAPIPerformancemark
return value void example the following example shows how to use mark() to create and retrieve performancemark entries.
performance.measure() - Web APIs
return value void example the following example shows how measure() is used to create a new measure performance entry in the browser's performance entry buffer.
Performance.navigation - Web APIs
the legacy performance.navigation read-only property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the number of redirections needed to fetch the resource.
Performance.onresourcetimingbufferfull - Web APIs
syntax callback = performance.onresourcetimingbufferfull = buffer_full_cb; return value callback an eventhandler that is invoked when the resourcetimingbufferfull event is fired.
Performance.timeOrigin - Web APIs
the timeorigin read-only property of the performance interface returns the high resolution timestamp of the start time of the performance measurement.
Performance.timing - Web APIs
the legacy performance.timing read-only property returns a performancetiming object containing latency-related performance information.
PerformanceLongTaskTiming.attribution - Web APIs
the attribution readonly property of the performancelongtasktiming interface returns a sequence of taskattributiontiming instances.
PerformanceLongTaskTiming - Web APIs
0" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="326" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancelongtasktiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties performancelongtasktiming.attribution read only returns a sequence of taskattributiontiming instances.
PerformanceNavigation.redirectCount - Web APIs
the legacy performancenavigation.redirectcount read-only property returns an unsigned short representing the number of redirects done before reaching the page.
PerformanceNavigation.type - Web APIs
the legacy performancenavigation.type read-only property returns an unsigned short containing a constant describing how the navigation to this page was done.
PerformanceNavigation - Web APIs
performancenavigation.tojson() is a jsonizer returning a json object representing the performancenavigation object.
PerformanceObserver() - Web APIs
return value a new performanceobserver object which will call the specified callback when observed performance events occur.
PerformanceResourceTiming.serverTiming - Web APIs
the servertiming read-only property returns an array of performanceservertiming entries containing server timing metrics.
PerformanceServerTiming.description - Web APIs
the description read-only property returns a domstring value of the server-specified metric description, or an empty string.
PerformanceServerTiming.duration - Web APIs
the duration read-only property returns a double that contains the server-specified metric duration, or value 0.0.
PerformanceServerTiming.name - Web APIs
the name read-only property returns a domstring value of the server-specified metric name.
PerformanceTiming.connectEnd - Web APIs
the legacy performancetiming.connectend read-only property returns 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 returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the request to open a connection is sent to the network.
PerformanceTiming.domComplete - Web APIs
the legacy performancetiming.domcomplete read-only property returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the browser is ready to fetch the document using an http request.
PerformanceTiming.navigationStart - Web APIs
the legacy performancetiming.navigationstart read-only property returns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after the prompt for unload terminates on the previous document in the same browsing context.
PerformanceTiming.requestStart - Web APIs
the legacy performancetiming.requeststart read-only property returns 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 returns 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 returns 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.
PeriodicWave.PeriodicWave() - Web APIs
return value a new periodicwave object instance.
PeriodicWave - Web APIs
the periodicwave itself is created/returned by audiocontext.createperiodicwave().
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() returns 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 returned 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.fillLightMode - Web APIs
the filllightmode read-only property of the photocapabilities interface returns all available fill light options of the source device.
PhotoCapabilities.imageHeight - Web APIs
the imageheight read-only property of the photocapabilities interface returns 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 returns a mediasettingsrange object indicating the image width range supported by the user agent.
PointerEvent.height - Web APIs
syntax var contactheight = pointerevent.height; return value contactheight the height of the event's contact area (in css pixels).
PointerEvent.pointerId - Web APIs
syntax var id = pointerevent.pointerid; return value id the pointer event's unique identifier number.
PointerEvent.pointerType - Web APIs
syntax var ptype = pointerevent.pointertype; return value ptype the event's pointer type.
PointerEvent.pressure - Web APIs
syntax var pressure = pointerevent.pressure; return 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; return 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; return 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; return 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; return 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; return value contactwidth the width of the event's contact area (in css pixels).
Multi-touch interaction - Web APIs
function get_cache(ev) { // return the cache for this event's target element switch(ev.target.id) { case "target1": return evcache1; case "target2": return evcache2; case "target3": return 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) return; 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 returns 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 return '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 returns a promise that resolves to the pushpermissionstatus of the requesting webapp, which will be one of granted, denied, or default.
PushManager.register() - Web APIs
syntax var request = navigator.push.register(); return a domrequest object to handle the success or failure of the method call.
PushManager.registrations() - Web APIs
syntax var request = navigator.push.registrations(); return a domrequest object to handle the success or failure of the method call.
PushManager.supportedContentEncodings - Web APIs
the supportedcontentencodings read-only property of the pushmanager interface returns an array of supported content codings that can be used to encrypt the payload of a push message.
PushManager.unregister() - Web APIs
return a domrequest object to handle the success or failure of the method call.
PushMessageData.arrayBuffer() - Web APIs
returns an arraybuffer.
PushMessageData.blob() - Web APIs
returns a blob.
PushMessageData.text() - Web APIs
returns a usvstring.
PushSubscription.endpoint - Web APIs
the endpoint read-only property of the pushsubscription interface returns a usvstring containing the endpoint associated with the push subscription.
PushSubscription.expirationTime - Web APIs
the expirationtime read-only property of the pushsubscription interface returns a domhighrestimestamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise.
PushSubscription.options - Web APIs
syntax var options = pushsubscription.options value an read-only options object containing the following values: uservisibleonly: a boolean, indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.
PushSubscription.subscriptionId - Web APIs
the endpoint read-only property of the pushsubscription interface returns a domstring containing the subscription id associated with the push subscription.
Push API - Web APIs
WebAPIPush API
serviceworkerregistration.pushmanager read only returns a reference to the pushmanager interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.
RTCCertificate - Web APIs
properties rtccertificate.expires read only returns the expiration date of the certificate.
RTCConfiguration.iceTransportPolicy - Web APIs
this includes, for example, those candidates relayed by a stun or turn server.
RTCDTMFSender.insertDTMF() - Web APIs
return value undefined exceptions invalidstateerror the dtmf tones couldn't be sent because the track has been stopped, or is in a read-only or inactive state.
RTCDTMFSender.toneBuffer - Web APIs
the rtcdtmfsender interface's tonebuffer property returns a string containing a list of the dtmf tones currently queued for sending to the remote peer over the rtcpeerconnection.
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
return value a newly-created rtcdtmftonechangeevent, configured as specified in the provided options.
RTCDTMFToneChangeEvent.tone - Web APIs
the read-only property rtcdtmftonechangeevent.tone returns the dtmf character which has just begun to play, or an empty string ("").
RTCDTMFToneChangeEvent - Web APIs
constructors rtcdtmftonechangeevent() returns a new rtcdtmftonechangeevent.
RTCDataChannel.bufferedAmount - Web APIs
the read-only rtcdatachannel property bufferedamount returns the number of bytes of data currently queued to be sent over the data channel.
RTCDataChannel.id - Web APIs
WebAPIRTCDataChannelid
the read-only rtcdatachannel property id returns an id number (between 0 and 65,534) which uniquely identifies the rtcdatachannel.
RTCDataChannel.label - Web APIs
the read-only rtcdatachannel property label returns a domstring containing a name describing the data channel.
RTCDataChannel.maxPacketLifeTime - Web APIs
the read-only rtcdatachannel property maxpacketlifetime returns 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.
RTCDataChannel.maxRetransmits - Web APIs
the read-only rtcdatachannel property maxretransmits returns 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.
RTCDataChannel.onerror - Web APIs
that event object, in turn, describes the error that took place.
RTCDataChannel.protocol - Web APIs
the read-only rtcdatachannel property protocol returns a domstring containing the name of the subprotocol in use.
RTCDataChannel.readyState - Web APIs
the read-only rtcdatachannel property readystate returns an enum of type rtcdatachannelstate which indicates the state of the data channel's underlying data connection.
RTCDataChannel.send() - Web APIs
return value undefined.
RTCDataChannel.stream - Web APIs
the deprecated (and never part of the official specification) read-only rtcdatachannel property stream returns an id number (between 0 and 65,535) which uniquely identifies the rtcdatachannel.
RTCDataChannelEvent.channel - Web APIs
the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event.
RTCError - Web APIs
WebAPIRTCError
constructor rtcerror() creates and returns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property.
RTCErrorEvent - Web APIs
constructor rtcerrorevent() creates and returns a new rtcerrorevent object.
RTCIceCandidate.relatedPort - Web APIs
for relay candidates, the related address and port provide the mapped address selected by the turn server.
RTCIceCandidate.sdpMid - Web APIs
the read-only property sdpmid on the rtcicecandidate interface returns a domstring specifying the media stream identification tag of the media component with which the candidate is associated.
RTCIceCandidate.usernameFragment - Web APIs
to avoid including candidates obsoleted by an ice restart, we can use code like this: const ssnewcandidate = signalmsg => { let candidate = new rtcicecandidate(signalmsg.candidate); let receivers = pc.getreceivers(); receivers.foreach(receiver => { let parameters = receiver.transport.getparameters(); if (parameters.usernamefragment === candidate.usernamefragment) { return; } }); pc.addicecandidate(candidate) .catch(reporterror); } this walks through the list of the rtcrtpreceiver objects being used to receive ice data, and looks to see if the usernamefragment indicated in the candidate matches any of them.
RTCIceCandidateInit - Web APIs
it's also used as the return value from the rtcicecandidate.tojson() method, and can be passed directly into rtcpeerconnection.addicecandidate() to add a candidate to the peer connection.
RTCIceCandidatePair.local - Web APIs
the rtcicecandidatepair is returned by the rtcicetransport method getselectedcandidatepair().
RTCIceCandidatePair.remote - Web APIs
the rtcicecandidatepair is returned by the rtcicetransport method getselectedcandidatepair().
RTCIceCandidatePair - Web APIs
it is used as the return value from rtcicetransport.getselectedcandidatepair() to identify the currently-selected candidate pair identified by the ice agent.
RTCIceCandidatePairStats.requestsReceived - Web APIs
because there's no way to tell the difference between requests made to check connectivity and requests made to check consent, the returned figure includes both.
RTCIceCandidateStats.address - Web APIs
if multiple ip addresses are returned in response to the query, the user agent selects one, which is then used for the duration of ice processing.
RTCIceCandidateStats.deleted - Web APIs
remote (turn) candidate a value of true means the candidate's turn allocation is no longer active.
RTCIceGathererState - Web APIs
the rtcicegathererstate enumerated type provides the string values which can be returned by an rtcicetransport object's gatheringstate.
RTCIceTransport.gatheringState - Web APIs
the read-only rtcicetransport property gatheringstate returns a domstring from the enumerated type rtcicegathererstate that indicates what gathering state the ice agent is currently in: "new", "gathering", or "complete".
RTCIceTransport.onselectedcandidatepairchange - Web APIs
the event handler can determine the current state by calling the transport's getselectedcandidatepair() method, which returns a rtcicecandidatepair whose rtcicecandidatepair.local and rtcicecandidatepair.global properties specify rtcicecandidate objects describing the local and remote candidates that are currently being used.
RTCIceTransport: selectedcandidatepairchange event - Web APIs
the pair of candidates is in turn described by an rtcicecandidatepair object which contains one rtcicecandidate representing the local end of the connection, and another representing the remote end of the connection.
RTCIceTransport.state - Web APIs
the read-only rtcicetransport property state returns the current state of the ice transport, so you can determine the state of ice gathering in which the ice agent currently is operating.
RTCIceTransportState - Web APIs
the rtcicetransportstate enumerated type defines the string values which may be returned by the state property on rtcicetransport objects.
RTCIdentityAssertion - Web APIs
if no peer has yet been set and verified this interface returns null.
RTCIdentityErrorEvent.idp - Web APIs
the read-only property rtcidentityerrorevent.idp returns the domstring describing the domain name of the identity provider (idp) generating the error response event.
RTCIdentityEvent.assertion - Web APIs
the read-only property rtcidentityevent.assertion returns the domstring containing a blob being the coded assertion associated with the event.
RTCIdentityEvent - Web APIs
rtcidentityevent.assertion read only returns the domstring containing a blob being the assertion generated.
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
by using the fec parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged packets, which in turn helps to reduce lag, or the need to skip damaged frames entirely.
RTCPeerConnection.addStream() - Web APIs
return value none.
RTCPeerConnection.createDataChannel() - Web APIs
return value a new rtcdatachannel object with the specified label, configured using the options specified by options if that parameter is included; otherwise, the defaults listed above are established.
RTCPeerConnection: identityresult event - Web APIs
instead, the peeridentity property returns a promise that resolves with an identity or rejects if an error occurs or if unable to validate the identity.
RTCPeerConnection: idpassertionerror event - Web APIs
bubbles no cancelable no interface rtcidentityerrorevent event handler property onidpassertionerror warning: this event is no longer used; instead, you can detect an assertion error by detecting when the promise returned by rtcpeerconnection.peeridentity is rejected.
RTCPeerConnection: idpvalidationerror event - Web APIs
bubbles no cancelable no interface rtcidentityerrorevent event handler property onidpvalidationerror warning: this event is no longer used; instead, you can detect a validation error by detecting when the promise returned by rtcpeerconnection.peeridentity is rejected.
RTCPeerConnection.onicecandidateerror - Web APIs
turn adds a few more error codes; see // rfc 5766, section 15 for details.
RTCPeerConnection.onidpassertionerror - Web APIs
you should instead detect idp assertion errors by handling rejection of the promise returned by rtcpeerconnection.peeridentity.
RTCPeerConnection.onidpvalidationerror - Web APIs
you should instead detect idp validation errors by watching for the promise returned by rtcpeerconnection.peeridentity to be rejected.
RTCPeerConnection.onpeeridentity - Web APIs
to detect successful validation of the identity, wait for the promise returned by peeridentity to resolve successfully with the peer's identity.
RTCPeerConnection: peeridentity event - Web APIs
instead of using this event to detect when an identity is available, simply wait for the promise returned by rtcpeerconnection.peeridentity to be resolved.
RTCPeerConnection.removeStream() - Web APIs
return value undefined.
RTCPeerConnection.removeTrack() - Web APIs
return value undefined.
RTCPeerConnection.sctp - Web APIs
the read-only sctp property on the rtcpeerconnection interface returns an rtcsctptransport describing the sctp transport over which sctp data is being sent and received.
RTCPeerConnection.setIdentityProvider() - Web APIs
syntax pc.setidentityprovider(domainname [, protocol] [, username]); there is no return value for this method.
RTCPeerConnection.signalingState - Web APIs
the read-only signalingstate property on the rtcpeerconnection interface returns one of the string values specified by the rtcsignalingstate enum; these values describe the state of the signaling process on the local end of the connection while connecting or reconnecting to another peer.
RTCPeerConnectionIceErrorEvent.address - Web APIs
the rtcpeerconnectioniceerrorevent property address is a string which indicates the local ip address being used to communicate with the stun or turn server during negotiations.
RTCPeerConnectionIceEvent.candidate - Web APIs
the read-only candidate property of the rtcpeerconnectioniceevent interface returns the rtcicecandidate associated with the event.
RTCPeerConnectionIceEvent - Web APIs
constructors rtcpeerconnectioniceevent() returns a new rtcpeerconnectioniceevent.
RTCRtcpParameters - Web APIs
function getrtpcname(rtpobject) { let parameters = rtpobject.getparameters(); return parameters.rtcp.cname; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtcpparameters' in that specification.
RTCRtpCapabilities - Web APIs
the rtcrtpcapabilities dictionary is a data type used to describe the capabilities of an rtcrtpsender or rtcrtpreceiver in response to a call to the rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities() static functions, both of which return an array of rtcrtpcapabilities objects.
RTCRtpCodecCapability - Web APIs
an array of objects of this type is returned in the codecs property of the rtcrtpcapabilities object returned in response to a call to either of the static functions rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities().
RTCRtpContributingSource.rtpTimestamp - Web APIs
the read-only rtptimestamp property of the rtcrtpcontributingsource interface returns a domhighrestimestamp indicating the source-generated time at which the media contained int he packet was first sampled or obtained.
RTCRtpContributingSource.source - Web APIs
the read-only source property of the rtcrtpcontributingsource interface returns the source identifier of a particular stream of rtp packets.
RTCRtpContributingSource.timestamp - Web APIs
the read-only timestamp property of the rtcrtpcontributingsource interface returns a domhighrestimestamp indicating the most recent time of playout of an rtp packet from the source.
RTCRtpEncodingParameters - Web APIs
dtx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity).
RTCRtpParameters - Web APIs
function getrtpcname(rtpobject) { let parameters = rtpobject.getparameters(); return parameters.rtcp.cname; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiveparameters' in that specification.
RTCRtpReceiver.track - Web APIs
the track read-only property of the rtcrtpreceiver interface returns the mediastreamtrack associated with the current rtcrtpreceiver instance.
RTCRtpSendParameters.encodings - Web APIs
dtx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity).
RTCRtpSender.setStreams() - Web APIs
return value none.
RTCRtpSender.track - Web APIs
the track read-only property of the rtcrtpsender interface returns the mediastreamtrack which is being handled by the rtcrtpsender.
RTCRtpStreamStats - Web APIs
the rtcrtpstreamstats dictionary is returned by the rtcpeerconnection.getstats(), rtcrtpsender.getstats(), and rtcrtpreceiver.getstats() methods to provide detailed statistics about webrtc connectivity.
RTCSessionDescriptionCallback - Web APIs
return value the callback doesn't need to return anything, so the return value is undefined.
RTCStatsReport - Web APIs
the rtcrtpreceiver and rtcrtpsender versions of getstats() specifically only return statistics available to the incoming or outgoing stream on which you call them.
RTCTrackEvent - Web APIs
constructor rtctrackevent() creates and returns a new rtctrackevent object, initialized with properties taken from the specified rtctrackeventinit dictionary.
Range() - Web APIs
WebAPIRangeRange
the range() constructor returns a newly created range object whose start and end is the global document object.
Range.cloneContents() - Web APIs
the range.clonecontents() returns a documentfragment copying the objects of type node included in the range.
Range.commonAncestorContainer - Web APIs
the range.commonancestorcontainer read-only property returns the deepest — or furthest down the document tree — node that contains both boundary points of the range.
Range.compareBoundaryPoints() - Web APIs
syntax compare = range.compareboundarypoints(how, sourcerange); return value compare a number, -1, 0, or 1, indicating whether the corresponding boundary-point of the range is respectively before, equal to, or after the corresponding boundary-point of sourcerange.
Range.createContextualFragment() - Web APIs
the range.createcontextualfragment() method returns a documentfragment by invoking the html fragment parsing algorithm or the xml fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node.
Range.deleteContents() - Web APIs
unlike range.extractcontents(), this method does not return a documentfragment containing the deleted content.
Range.endContainer - Web APIs
the range.endcontainer read-only property returns the node within which the range ends.
Range.endOffset - Web APIs
WebAPIRangeendOffset
the range.endoffset read-only property returns a number representing where in the range.endcontainer the range ends.
Range.getClientRects() - Web APIs
the range.getclientrects() method returns a list of domrect objects representing the area of the screen occupied by the range.
Range.intersectsNode() - Web APIs
the range.intersectsnode() method returns a boolean indicating whether the given node intersects the range.
Range.setEnd() - Web APIs
WebAPIRangesetEnd
return value undefined.
Range.startContainer - Web APIs
the range.startcontainer read-only property returns the node within which the range starts.
Range.startOffset - Web APIs
WebAPIRangestartOffset
the range.startoffset read-only property returns a number representing where in the startcontainer the range starts.
Range.toString() - Web APIs
WebAPIRangetoString
the range.tostring() method is a stringifier returning the text of the range.
ReadableByteStreamController.byobRequest - Web APIs
the byobrequest read-only property of the readablebytestreamcontroller interface returns the current byob pull request, or undefined if there are no pending requests.
ReadableByteStreamController.close() - Web APIs
return value undefined.
ReadableByteStreamController.desiredSize - Web APIs
the desiredsize read-only property of the readablebytestreamcontroller interface returns the desired size required to fill the stream's internal queue.
ReadableByteStreamController.enqueue() - Web APIs
return value undefined.
ReadableByteStreamController.error() - Web APIs
return value undefined.
ReadableStreamBYOBReader.cancel() - Web APIs
return value a promise, which fulfills with the value given in the reason parameter.
ReadableStreamBYOBReader.closed - Web APIs
the closed read-only property of the readablestreambyobreader interface returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors.
ReadableStreamBYOBRequest.respond() - Web APIs
the error() method of the readablestreambyobrequest interface xxx syntax readablestreambyobrequestinstance.respond(byteswritten); parameters byteswritten xxx return value void.
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
the respondwithnewview() method of the readablestreambyobrequest interface xxx syntax readablestreambyobrequestinstance.respondwithnewview(view); parameters view xxx return value void.
ReadableStreamBYOBRequest.view - Web APIs
the view getter property of the readablestreambyobrequest interface returns the current view.
ReadableStreamBYOBRequest - Web APIs
properties readablestreambyobrequest.view read only returns the current view.
ReadableStreamDefaultController.close() - Web APIs
return value undefined.
ReadableStreamDefaultController.desiredSize - Web APIs
the desiredsize read-only property of the readablestreamdefaultcontroller interface returns the desired size required to fill the stream's internal queue.
ReadableStreamDefaultController.enqueue() - Web APIs
return value undefined.
ReadableStreamDefaultController.error() - Web APIs
return value undefined.
ReadableStreamDefaultController - Web APIs
properties readablestreamdefaultcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue.
ReadableStreamDefaultReader.closed - Web APIs
the closed read-only property of the readablestreamdefaultreader interface returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors.
RenderingContext - Web APIs
the primary use of this type is the definition of the <canvas> element's htmlcanvaselement.getcontext() method, which returns a renderingcontext (meaning it returns any one of the rendering context types).
Report - Web APIs
WebAPIReport
reports can be accessed in a number of ways: via the reportingobserver.takerecords() method — this returns all reports in an observer's report queue, and then empties the queue.
ReportingObserver.disconnect() - Web APIs
after calling disconnect(), neither reportingobserver.takerecords() nor the records parameter of the reportingobserver() callback will return any reports.
Request() - Web APIs
WebAPIRequestRequest
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { return response.blob(); }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in our fetch request with init example (see fetch request init live) we do the same thing except that we pass in an init object when we invoke fetch(): var myimage = document.queryselector('img'); var myheaders = new headers(); myheaders.append('content-type', 'image/jp...
Request.clone() - Web APIs
WebAPIRequestclone
return value a request object, which is an exact copy of the request that clone() was called on.
Request.context - Web APIs
WebAPIRequestcontext
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 context in a variable: var myrequest = new request('flowers.jpg'); var mycontext = myrequest.context; // returns the empty string by 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; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification.
Request.headers - Web APIs
WebAPIRequestheaders
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'); // returns 'image/jpeg' specifications specification status comment fetchthe definition of 'headers' in that specification.
Request.integrity - Web APIs
WebAPIRequestintegrity
if an integrity has not been specified, the property returns ''.
Request.mode - Web APIs
WebAPIRequestmode
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
ResizeObserver.disconnect() - Web APIs
return value void.
ResizeObserver.observe() - Web APIs
return value void.
ResizeObserver.unobserve() - Web APIs
return value void.
ResizeObserverEntry.borderBoxSize - Web APIs
the borderboxsize read-only property of the resizeobserverentry interface returns an array containing the new border box size of the observed element when the callback is run.
ResizeObserverEntry.contentBoxSize - Web APIs
the contentboxsize read-only property of the resizeobserverentry interface returns an array containing the new content box size of the observed element when the callback is run.
ResizeObserverEntry.target - Web APIs
the target read-only property of the resizeobserverentry interface returns a reference to the element or svgelement that is being observed.
Response.headers - Web APIs
WebAPIResponseheaders
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification.
Response.ok - Web APIs
WebAPIResponseok
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification.
Response.status - Web APIs
WebAPIResponsestatus
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification.
Response.statusText - Web APIs
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.statustext); // returns "ok" if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'statustext' in that specification.
Response.type - Web APIs
WebAPIResponsetype
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification.
Response.url - Web APIs
WebAPIResponseurl
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification.
SVGAElement.target - Web APIs
the svgaelement.target read-only property of svgaelement returns an svganimatedstring object that specifies the portion of a target window, frame, pane into which a document is to be opened when a link is activated.
SVGAltGlyphElement.glyphRef - Web APIs
syntax string = myglyph.glyphref; myglyph.glyphref = string; value the return value is a glyph identifier, the value of which depends on the format of the given font.
SVGDocument - Web APIs
referrer domstring returns the uri of the page that linked to this page.
SVGGeometryElement.isPointInFill() - Web APIs
return value a boolean indicating whether the given point is within the fill or not.
SVGGeometryElement.isPointInStroke() - Web APIs
return value a boolean indicating whether the given point is within the stroke or not.
SVGGeometryElement.pathLength - Web APIs
the svggeometryelement.pathlength property reflects the pathlength attribute and returns the total length of the path, in user units.
SVGImageElement.height - Web APIs
the height read-only property of the svgimageelement interface returns an svganimatedlength corresponding to the height attribute of the given <image> element.
SVGImageElement.preserveAspectRatio - Web APIs
the preserveaspectratio read-only property of the svgimageelement interface returns an svganimatedpreserveaspectratio corresponding to the preserveaspectratio attribute of the given <image> element.
SVGImageElement.width - Web APIs
the width read-only property of the svgimageelement interface returns an svganimatedlength corresponding to the width attribute of the given <image> element.
SVGImageElement.x - Web APIs
WebAPISVGImageElementx
the x read-only property of the svgimageelement interface returns an svganimatedlength corresponding to the x attribute of the given <image> element.
SVGImageElement.y - Web APIs
WebAPISVGImageElementy
the y read-only property of the svgimageelement interface returns an svganimatedlength corresponding to the y attribute of the given <image> element.
SVGLength - Web APIs
WebAPISVGLength
methods name & arguments return description newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object.
SVGPathElement.pathLength - Web APIs
the svgpathelement.pathlength property reflects the pathlength attribute and returns the total length of the path, in user units.
SVGTests - Web APIs
WebAPISVGTests
methods svgtests.hasextension() read only returns true if the browser supports the given extension, specified by a uri.
SVGTransform - Web APIs
methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation.
SVGURIReference - Web APIs
on getting href, an svganimatedstring object is returned that reflects the href attribute, and if the element is defined to support the deprecated xlink:href attribute, additionally reflects that deprecated attribute.
Screen.availHeight - Web APIs
the read-only screen interface's availheight property returns the height, in css pixels, of the space available for web content on the screen.
Screen.availTop - Web APIs
WebAPIScreenavailTop
syntax let availtop = window.screen.availtop; 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 returns 0.
Screen.availWidth - Web APIs
WebAPIScreenavailWidth
the screen.availwidth property returns the amount of horizontal space (in pixels) available to the window.
Screen.left - Web APIs
WebAPIScreenleft
returns the distance in pixels from the left side of the main screen to the left side of the current screen.
Screen.mozEnabled - Web APIs
WebAPIScreenmozEnabled
setting it to false will turn off the screen.
Screen.top - Web APIs
WebAPIScreentop
returns the distance in pixels from the top side of the current screen.
Screen.unlockOrientation() - Web APIs
syntax var unlocked = window.screen.unlockorientation(); return value returns true if the orientation was successfully unlocked or false if the orientation couldn't be unlocked.
ScreenOrientation.angle - Web APIs
the angle read-only property of the screenorientation interface returns the document's current orientation angle.
ScreenOrientation.lock() - Web APIs
one of the following: "any" "natural" "landscape" "portrait" "portrait-primary" "portrait-secondary" "landscape-primary" "landscape-secondary" return value a promise.
ScreenOrientation.type - Web APIs
the type read-only property of the screenorientation interface returns the document's current orientation type, one of "portrait-primary", "portrait-secondary", "landscape-primary", or "landscape-secondary".
ScreenOrientation.unlock() - Web APIs
return value void.
Screen Capture API - Web APIs
to start capturing video from the screen, you call getdisplaymedia() on the instance of media navigator.mediadevices: capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); the promise returned by getdisplaymedia() resolves to a mediastream which streams the captured media.
ScriptProcessorNode.bufferSize - Web APIs
the buffersize property of the scriptprocessornode interface returns an integer representing both the input and output buffer size, in sample-frames.
ScriptProcessorNode - Web APIs
scriptprocessornode.buffersize read only returns an integer representing both the input and output buffer size.
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
return value a securitypolicyviolationevent object instance.
Selection.anchorNode - Web APIs
the selection.anchornode read-only property returns the node in which the selection begins.
Selection.focusNode - Web APIs
the selection.focusnode read-only property returns the node in which the selection ends.
Selection.rangeCount - Web APIs
the selection.rangecount read-only property returns the number of ranges in the selection.
Selection.removeRange() - Web APIs
return value undefined examples /* programmaticaly, more than one range can be selected.
Selection.setBaseAndExtent() - Web APIs
return value void.
Sensor.activated - Web APIs
WebAPISensoractivated
the activated read-only property of the sensor interface returns a boolean indicating whether the sensor is active.
Sensor.hasReading - Web APIs
WebAPISensorhasReading
the hasreading read-only property of the sensor interface returns a boolean indicating whether the sensor has a reading.
Sensor.start() - Web APIs
WebAPISensorstart
return value undefined specifications specification status comment generic sensor apithe definition of 'start' in that specification.
Sensor.stop() - Web APIs
WebAPISensorstop
return value undefined example // tbd specifications specification status comment generic sensor apithe definition of 'stop' in that specification.
Sensor.timestamp - Web APIs
WebAPISensortimestamp
the timestamp read-only property of the sensor interface returns the time stamp of the latest sensor reading.
SensorErrorEvent.error - Web APIs
the error read-only property of the sensorerrorevent interface returns the domexception object passed in the event's contructor.
SensorErrorEvent - Web APIs
properties sensorerrorevent.error read only returns the domexception object passed in the event's contructor.
ServiceWorker.onstatechange - Web APIs
the code listens for any change in the serviceworker.state and returns its value.
ServiceWorker.scriptURL - Web APIs
returns the serviceworker serialized script url defined as part of serviceworkerregistration.
ServiceWorkerContainer.ready - Web APIs
it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an active worker.
ServiceWorkerContainer.register() - Web APIs
return value a promise that resolves with a serviceworkerregistration object.
ServiceWorkerContainer.startMessages() - Web APIs
return value undefined.
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) { return caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: globalscope.onactivate = function(event) { ...
ServiceWorkerGlobalScope.caches - Web APIs
the caches read-only property of the serviceworkerglobalscope interface returns the cachestorage object associated with the service worker.
ServiceWorkerGlobalScope.clients - Web APIs
the clients read-only property of the serviceworkerglobalscope interface returns the clients object associated with the service worker.
ServiceWorkerGlobalScope: contentdelete event - Web APIs
self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return 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) { return 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) { return 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 => { return 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) { return 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) return client.focus(); } if (clients.openwindow) return 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')) { return; } 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...
ServiceWorkerGlobalScope.registration - Web APIs
the registration read-only property of the serviceworkerglobalscope interface returns a reference to the serviceworkerregistration object, which represents the service worker's registration.
ServiceWorkerMessageEvent.data - Web APIs
the data read-only property of the serviceworkermessageevent interface returns the event's data.
ServiceWorkerMessageEvent.origin - Web APIs
the origin read-only property of the serviceworkermessageevent interface returns the origin of the service worker's environment settings object.
ServiceWorkerMessageEvent.ports - Web APIs
the ports read-only property of the serviceworkermessageevent interface returns an array of messageport objects connected with the message channel the message is being sent through.
ServiceWorkerMessageEvent.source - Web APIs
the source read-only property of the serviceworkermessageevent returns a reference to the serviceworker object of the associated service worker that sent the message.
ServiceWorkerRegistration.active - Web APIs
the active property of the serviceworkerregistration interface returns a service worker whose serviceworker.state is activated.
ServiceWorkerRegistration.index - Web APIs
the index read-only property of the serviceworkerregistration interface returns a reference to the contentindex interface, which allows for indexing of offline content.
ServiceWorkerRegistration.installing - Web APIs
the installing property of the serviceworkerregistration interface returns a service worker whose serviceworker.state is installing.
ServiceWorkerRegistration.navigationPreload - Web APIs
the navigationpreload read-only property of the serviceworkerregistration interface returns the navigationpreloadmanager associated with the current service worker registration.
ServiceWorkerRegistration.periodicSync - Web APIs
the periodicsync read-only property of the serviceworkerregistration interface returns a reference to the periodicsyncmanager interface, which manages periodic background synchronization processes.
ServiceWorkerRegistration.pushManager - Web APIs
the pushmanager property of the serviceworkerregistration interface returns a reference to the pushmanager interface for managing push subscriptions; this includes support for subscribing, getting an active subscription, and accessing push permission status.
ServiceWorkerRegistration.scope - Web APIs
the scope read-only property of the serviceworkerregistration interface returns a unique identifier for a service worker registration.
ServiceWorkerRegistration.showNotification() - Web APIs
return value a promise that resolves to undefined.
ServiceWorkerRegistration.sync - Web APIs
the sync property of the serviceworkerregistration interface returns a reference to the syncmanager interface, which manages background synchronization processes.
ServiceWorkerRegistration.update() - Web APIs
return value a promise that resolves with a serviceworkerregistration object.
ServiceWorkerRegistration.waiting - Web APIs
the waiting property of the serviceworkerregistration interface returns a service worker whose serviceworker.state is installed.
Service Worker API - Web APIs
navigator.serviceworker returns a serviceworkercontainer object, which provides access to registration, removal, upgrade, and communication with the serviceworker objects for the associated document.
ShadowRoot.delegatesFocus - Web APIs
the delegatesfocus read-only property of the shadowroot interface returns a boolean that indicates whether delegatesfocus was set when the shadow was attached (see element.attachshadow()).
ShadowRoot.innerHTML - Web APIs
the innerhtml property of the shadowroot interface sets or returns a reference to the dom tree inside the shadowroot.
ShadowRoot.mode - Web APIs
WebAPIShadowRootmode
examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; // another way to check whether the shadow root is open; it will return null if not if(shadow) { // if it is open, close it to stop people stealing our secrets!
SharedWorker() - Web APIs
return value the created worker.
SharedWorker.port - Web APIs
WebAPISharedWorkerport
the port property of the sharedworker interface returns a messageport object used to communicate and control the shared worker.
SharedWorker - Web APIs
sharedworker.port read only returns a messageport object used to communicate with and control the shared worker.
Slottable: assignedSlot - Web APIs
the assignedslot read-only property of the slottable interface returns an htmlslotelement representing the <slot> element the node is inserted in.
Slottable - Web APIs
WebAPISlottable
properties slottable.assignedslot read only returns the <slot> the node is inserted in.
SourceBuffer.abort() - Web APIs
return value undefined.
SourceBuffer.appendBuffer() - Web APIs
return value undefined.
SourceBuffer.appendStream() - Web APIs
return value undefined.
SourceBuffer.audioTracks - Web APIs
the audiotracks read-only property of the sourcebuffer interface returns a list of the audio tracks currently contained inside the sourcebuffer.
SourceBuffer.buffered - Web APIs
the buffered read-only property of the sourcebuffer interface returns the time ranges that are currently buffered in the sourcebuffer as a normalized timeranges object.
SourceBuffer.changeType() - Web APIs
return value undefined.
SourceBuffer.remove() - Web APIs
return value undefined.
SourceBuffer.textTracks - Web APIs
the texttracks read-only property of the sourcebuffer interface returns a list of the text tracks currently contained inside the sourcebuffer.
SourceBuffer.videoTracks - Web APIs
the videotracks read-only property of the sourcebuffer interface returns a list of the video tracks currently contained inside the sourcebuffer.
SourceBufferList.length - Web APIs
the length read-only property of the sourcebufferlist interface returns the number of sourcebuffer objects in the list.
SourceBufferList - Web APIs
x="151" y="1" width="160" 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">sourcebufferlist</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties sourcebufferlist.length read only returns the number of sourcebuffer objects in the list.
SpeechGrammarList.addFromString() - Web APIs
syntax speechgrammarlistinstance.addfromstring(string,weight); returns void.
SpeechGrammarList.addFromURI() - Web APIs
syntax speechgrammarlistinstance.addfromuri(src,weight); returns void.
SpeechGrammarList.item() - Web APIs
syntax var myfirstgrammar = speechgrammarlistinstance[0]; returns a speechgrammar object.
SpeechGrammarList - Web APIs
properties speechgrammarlist.length read only returns the number of speechgrammar objects contained in the speechgrammarlist.
SpeechRecognition.continuous - Web APIs
the continuous property of the speechrecognition interface controls whether continuous results are returned for each recognition, or only a single result.
SpeechRecognition.grammars - Web APIs
the grammars property of the speechrecognition interface returns and sets a collection of speechgrammar objects that represent the grammars that will be understood by the current speechrecognition.
SpeechRecognition.lang - Web APIs
the lang property of the speechrecognition interface returns and sets the language of the current speechrecognition.
SpeechRecognition.maxAlternatives - Web APIs
syntax var mymaxalternativenumber = myspeechrecognition.maxalternatives; myspeechrecognition.maxalternatives = 2; value a number representing the maximum returned alternatives for each result.
SpeechRecognition: nomatch event - Web APIs
the nomatch event of the web speech api is fired when the speech recognition service returns a final result with no significant recognition.
SpeechRecognition: result event - Web APIs
the result event of the web speech api is fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app bubbles no cancelable no interface speechrecognitionevent event handler property onresult examples this code is excerpted from our speech color changer example.
SpeechRecognition.start() - Web APIs
return value void.
SpeechRecognitionError.error - Web APIs
the error read-only property of the speechrecognitionerror interface returns the type of error raised.
SpeechRecognitionError.message - Web APIs
the message read-only property of the speechrecognitionerror interface returns a message describing the error in more detail.
SpeechRecognitionErrorEvent.error - Web APIs
the error read-only property of the speechrecognitionerrorevent interface returns the type of error raised.
SpeechRecognitionErrorEvent.message - Web APIs
the message read-only property of the speechrecognitionerrorevent interface returns a message describing the error in more detail.
SpeechSynthesis.cancel() - Web APIs
syntax speechsynthesisinstance.cancel(); returns void.
SpeechSynthesis.pause() - Web APIs
syntax speechsynthesisinstance.pause(); returns void.
SpeechSynthesis.resume() - Web APIs
syntax speechsynthesisinstance.resume(); returns void.
SpeechSynthesis.speak() - Web APIs
syntax speechsynthesisinstance.speak(utterance); returns void.
SpeechSynthesis: voiceschanged event - Web APIs
the voiceschanged event of the web speech api is fired when the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices() method has changed (when the voiceschanged event fires.) bubbles no cancelable no interface event event handler property onvoiceschanged examples this could be used to repopulate a list of voices that the user can choose between when the event fires.
SpeechSynthesisErrorEvent.error - Web APIs
the error property of the speechsynthesiserrorevent interface returns an error code indicating what has gone wrong with a speech synthesis attempt.
SpeechSynthesisErrorEvent - Web APIs
speechsynthesiserrorevent.error read only returns an error code indicating what has gone wrong with a speech synthesis attempt.
SpeechSynthesisEvent.charIndex - Web APIs
the charindex read-only property of the speechsynthesisutterance interface returns the index position of the character in the speechsynthesisutterance.text that was being spoken when the event was triggered.
SpeechSynthesisEvent.elapsedTime - Web APIs
the elapsedtime read-only property of the speechsynthesisutterance interface returns the elapsed time in seconds after the speechsynthesisutterance.text started being spoken that the event was triggered at.
SpeechSynthesisEvent.name - Web APIs
the name read-only property of the speechsynthesisutterance interface returns 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 - Web APIs
the utterance read-only property of the speechsynthesisutterance interface returns the speechsynthesisutterance instance that the event was triggered on.
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
the speechsynthesisutterance() constructor of the speechsynthesisutterance interface returns a new speechsynthesisutterance object instance.
SpeechSynthesisUtterance.voice - Web APIs
this should be set to one of the speechsynthesisvoice objects returned by speechsynthesis.getvoices().
SpeechSynthesisUtterance - Web APIs
language, pitch and volume.) constructor speechsynthesisutterance.speechsynthesisutterance() returns a new speechsynthesisutterance object instance.
SpeechSynthesisVoice.default - Web APIs
the default read-only property of the speechsynthesisvoice interface returns a boolean indicating whether the voice is the default voice for the current app (true), or not (false.) note: for some devices, it might be the default voice for the voice's language.
SpeechSynthesisVoice.lang - Web APIs
the lang read-only property of the speechsynthesisvoice interface returns a bcp 47 language tag indicating the language of the voice.
SpeechSynthesisVoice.localService - Web APIs
the localservice read-only property of the speechsynthesisvoice interface returns a boolean indicating whether the voice is supplied by a local speech synthesizer service (true), or a remote speech synthesizer service (false.) this property is provided to allow differentiation in the case that some voice options are provided by a remote service; it is possible that remote voices might have extra latency, bandwidth or cost associated with them, so such distinction may be useful.
SpeechSynthesisVoice.name - Web APIs
the name read-only property of the speechsynthesisvoice interface returns a human-readable name that represents the voice.
StaticRange.StaticRange() - Web APIs
return value a new staticrange object initialized with the values given in the rangespec object.
StaticRange.collapsed - Web APIs
the collapsed read-only property of the staticrange interface returns true if the range's start position and end position are the same.
StaticRange.endContainer - Web APIs
the endcontainer property of the staticrange interface returns the end node for the range.
StaticRange.endOffset - Web APIs
the endoffset property of the staticrange interface returns the offset into the end node of the range's end position.
StaticRange.startContainer - Web APIs
the read-only startcontainer property of the staticrange interface returns the start node for the range.
StaticRange.startOffset - Web APIs
the read-only startoffset property of the staticrange interface returns the offset into the start node of the range's start position.
StaticRange.toRange() - Web APIs
return value a new range object.
StereoPannerNode.StereoPannerNode() - Web APIs
return value a new stereopannernode object instance.
Storage.clear() - Web APIs
WebAPIStorageclear
syntax storage.clear(); return value undefined.
Storage.removeItem() - Web APIs
return value undefined.
Storage.setItem() - Web APIs
WebAPIStoragesetItem
return value undefined.
StorageEstimate - Web APIs
the estimate() method returns an object that conforms to this dictionary when its promise resolves.
StorageQuota.supportedTypes - Web APIs
the supportedtypes read-only property of the storagequota interface returns a list of the available storage types.
Storage API - Web APIs
to determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate() method, which returns a promise that, when resolved, receives a storageestimate that contains these figures.
StylePropertyMap.append() - Web APIs
return value undefined.
StylePropertyMap.clear() - Web APIs
return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'clear()' in that specification.
StylePropertyMap.delete() - Web APIs
return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'delete()' in that specification.
StylePropertyMap.set() - Web APIs
return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'set()' in that specification.
StylePropertyMapReadOnly.forEach() - Web APIs
return value undefined.
StylePropertyMapReadOnly.has() - Web APIs
return value a boolean.
StylePropertyMapReadOnly.size - Web APIs
the size read-only property of the stylepropertymapreadonly interface returns an unsinged long integer containing the size of the stylepropertymapreadonly object.
StyleSheet.title - Web APIs
WebAPIStyleSheettitle
the title property of the stylesheet interface returns the advisory title of the current style sheet.
StyleSheetList - Web APIs
examples get document stylesheet objects with for loop for (let i = 0; i < document.stylesheets.length; i++) { let stylesheet = document.stylesheets[i]; } get all css rules for the document using array methods const allcss = [...document.stylesheets] .map(stylesheet => { try { return [...stylesheet.cssrules] .map(rule => rule.csstext) .join(''); } catch (e) { console.log('access to stylesheet %s is denied.
SubmitEvent - Web APIs
constructor submitevent() creates and returns a new submitevent object whose type and other options are configured as specified.
SubtleCrypto.generateKey() - Web APIs
return value result is a promise that fulfills with a cryptokey (for symmetric algorithms) or a cryptokeypair (for public-key algorithms).
SyncEvent.lastChance - Web APIs
the syncevent.lastchance read-only property of the syncevent interface returns true if the user agent will not make further synchronization attempts after the current attempt.
registration - Web APIs
the registration read-only property of the syncevent interface returns a reference to a syncregistration object.
SyncEvent.tag - Web APIs
WebAPISyncEventtag
the syncevent.tag read-only property of the syncevent interface returns the developer-defined identifier for this syncevent.
TaskAttributionTiming.containerId - Web APIs
the containerid readonly property of the taskattributiontiming interface returns the container's id attribute.
TaskAttributionTiming.containerName - Web APIs
the containername readonly property of the taskattributiontiming interface returns the container's name attribute.
TaskAttributionTiming.containerSrc - Web APIs
the containersrc readonly property of the taskattributiontiming interface returns the container's src attribute.
TaskAttributionTiming.containerType - Web APIs
the containertype readonly property of the taskattributiontiming interface returns the type of frame container, one of iframe, embed, or object.
Text() - Web APIs
WebAPITextText
the text() constructor returns a newly created text object with the optional domstring given in parameter as its textual content.
HTMLSlotElement.assignedSlot - Web APIs
WebAPITextassignedSlot
the assignedslot property of the text interface returns the htmlslotelement object associated with the element.
Text.isElementContentWhitespace - Web APIs
the text.iselementcontentwhitespace read-only property returns a boolean flag indicating whether or not the text node's content consists solely of whitespace.
TextDecoder() - Web APIs
the textdecoder() constructor returns a newly created textdecoder object for the encoding specified in parameter.
TextDecoder.prototype.decode() - Web APIs
the textdecoder.prototype.decode() method returns a domstring containing the text, given in parameters, decoded with the specific method for that textdecoder object.
TextDecoder.prototype.encoding - Web APIs
the textdecoder.prototype.encoding read-only property returns a domstring containing the name of the decoding algorithm used by the specific decoder.
TextEncoder() - Web APIs
the textencoder() constructor returns a newly created utf-8 textencoder object.
TextEncoder.encoding - Web APIs
the textencoder.encoding read-only property returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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'); // returns 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 returns the number of entries in the texttracklist, each of which is a texttrack representing one track in the media element.
TimeRanges.length - Web APIs
WebAPITimeRangeslength
the timeranges.length read-only property returns the number of ranges in the object.
TouchEvent.altKey - Web APIs
WebAPITouchEventaltKey
syntax var altenabled = touchevent.altkey; return value altenabled true if the alt key is enabled for this event; and false if the alt is not enabled.
TouchEvent.changedTouches - Web APIs
syntax var changes = touchevent.changedtouches; return value changes a touchlist whose touch objects include all the touch points that contributed to this touch event.
TouchEvent.ctrlKey - Web APIs
syntax var ctrlenabled = touchevent.ctrlkey; return value ctrlenabled true if the control key is enabled for this event; and false if the control is not enabled.
TouchEvent.metaKey - Web APIs
syntax var metaenabled = touchevent.metakey; return value metaenabled true if the meta key is enabled for this event; and false if the meta is not enabled.
TouchEvent.shiftKey - Web APIs
syntax var shiftenabled = touchevent.shiftkey; return value shiftenabled true if the shift key is enabled for this event; and false if the shift key is not enabled.
TouchEvent.touches - Web APIs
syntax var touches = touchevent.touches; return value touches a touchlist listing all the touch objects for touch points that are still in contact with the touch surface, regardless of whether or not they've changed or what their target element was at touchstart time.
TouchList.length - Web APIs
WebAPITouchListlength
syntax var numtouches = touchlist.length; return value numtouches the number of touch points in touchlist.
TrackDefault.TrackDefault() - Web APIs
the trackdefault() constructor of the trackdefault interface constructs and returns a new trackdefault object.
TrackDefault.byteStreamTrackID - Web APIs
the bytestreamtrackid read-only property of the trackdefault interface returns the id of the specific track that the sourcebuffer should apply to.
TrackDefault.kinds - Web APIs
the kinds read-only property of the trackdefault interface returns default kinds for an associated sourcebuffer to use when an initialization segment does not contain label information for a new track.
TrackDefault.label - Web APIs
the label read-only property of the trackdefault interface returns the default label for an associated sourcebuffer to use when an initialization segment does not contain label information for a new track.
TrackDefault.language - Web APIs
the language read-only property of the trackdefault interface returns a default language for an associated sourcebuffer to use when an initialization segment does not contain language information for a new track.
TrackDefault.type - Web APIs
WebAPITrackDefaulttype
the type read-only property of the trackdefault interface returns the type of track that this sourcebuffer's media segment data relates to (i.e.
TrackDefaultList.TrackDefaultList() - Web APIs
the trackdefaultlist() constructor of the trackdefaultlist interface constructs and returns a new trackdefaultlist object.
TrackDefaultList.length - Web APIs
the length read-only property of the trackdefaultlist interface returns the number of trackdefault objects in the list.
TransitionEvent() - Web APIs
the transitionevent() constructor returns a newly created transitionevent, representing an event in relation with an transition.
TreeWalker.currentNode - Web APIs
syntax node = treewalker.currentnode; treewalker.currentnode = node; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.currentnode; // the root element as it is the first element!
UIEvent.pageX - Web APIs
WebAPIUIEventpageX
the non-standard, read-only uievent property pagex returns the horizontal coordinate of the event relative to the whole document.
UIEvent.view - Web APIs
WebAPIUIEventview
the uievent.view read-only property returns the windowproxy object from which the event was generated.
URL() - Web APIs
WebAPIURLURL
the url() constructor returns a newly created url object representing the url defined by the parameters.
URL.createObjectURL() - Web APIs
return value a domstring containing an object url that can be used to reference the contents of the specified source object.
URL.searchParams - Web APIs
WebAPIURLsearchParams
the searchparams readonly property of the url interface returns a urlsearchparams object allowing access to the get decoded query arguments contained in the url.
URLSearchParams.append() - Web APIs
return value void.
URLSearchParams.delete() - Web APIs
return value void examples let url = new url('https://example.com?foo=1&bar=2&foo=3'); let params = new urlsearchparams(url.search.slice(1)); // delete the foo parameter.
URLSearchParams.forEach() - Web APIs
return value void.
URLUtilsReadOnly.origin - Web APIs
syntax string = object.origin; examples // on this page, returns the origin var result = self.location.origin; // returns:'https://developer.mozilla.org:443' specifications specification status comment urlthe definition of 'urlutilsreadonly.origin' in that specification.
URL API - Web APIs
WebAPIURL API
after executing the code snippet above, the value returned by addr.href is https://someguy@mysite.com/login.
USBConfiguration.configurationName - Web APIs
the configurationname read-only property of the usbconfiguration interface returns the name provided by the device to describe this configuration.
USBConfiguration.interfaces - Web APIs
the interfaces read-only property of the usbconfiguration interface returns an array containing instances of the usbinterface describing each interface supported by this configuration.
USBDevice.configuration - Web APIs
the configuration read only property of the usbdevice interface returns a usbconfiguration object for the currently selected interface for a paired usb device.
USBIsochronousOutTransferResult - Web APIs
properties usbisochronousouttransferresult.packetsread only returns an array of usbisochronousouttransferpacket objects containing the result of each request to send a packet to the device.
USVString - Web APIs
WebAPIUSVString
usvstring maps to a string when returned 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 return 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.
VTTRegion - Web APIs
WebAPIVTTRegion
constructor vttregion() returns a newly created vttregion object.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
the read-only droppedvideoframes property of the videoplaybackquality interface returns 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.totalFrameDelay - Web APIs
the videoplaybackquality.totalframedelay read-only property returns a double containing the sum of the frame delay since the creation of the associated htmlvideoelement.
VideoPlaybackQuality.totalVideoFrames - Web APIs
the videoplaybackquality interface's totalvideoframes read-only property returns the total number of video frames that have been displayed or dropped since the media was loaded.
VideoPlaybackQuality - Web APIs
a videoplaybackquality object is returned by the htmlvideoelement.getvideoplaybackquality() method and contains metrics that can be used to determine the playback quality of a video.
Videotrack.language - Web APIs
the read-only videotrack property language returns a string identifying the language used in the video track.
VideoTrack.sourceBuffer - Web APIs
the read-only videotrack property sourcebuffer returns 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 returns the number of entries in the videotracklist, each of which is a videotrack representing one video track in the media element.
VideoTrackList.selectedIndex - Web APIs
the read-only videotracklist property selectedindex returns the index of the currently selected track, if any, or -1 otherwise.
VisualViewport.height - Web APIs
the height read-only property of the visualviewport interface returns the height of the visual viewport, in css pixels.
VisualViewport.offsetTop - Web APIs
the offsettop read-only property of the visualviewport interface returns 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 returns 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 returns 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 returns 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 returns the pinch-zoom scaling factor applied to the visual viewport.
VisualViewport.width - Web APIs
the width read-only property of the visualviewport interface returns the width of the visual viewport, in css pixels.
Visual Viewport API - Web APIs
let pendingupdate = false; function viewporthandler(event) { if (pendingupdate) return; 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_compressed_texture_astc - Web APIs
ext.getsupportedprofiles() returns an array of strings containing the names of the astc profiles supported by the implementation.
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 returned at all, if the performance would be dramatically slow.
WEBGL_debug_shaders - Web APIs
methods webgl_debug_shaders.gettranslatedshadersource() returns the translated shader source.
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 return 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 returning a draw buffer.
WakeLock - Web APIs
WebAPIWakeLock
methods request requests a wakelocksentinel object, which returns a promise that resolves with a wakelocksentinel object.
WaveShaperNode.WaveShaperNode() - Web APIs
return value a new waveshapernode object instance.
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) ); } return 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) ); } return curve; }; ...
WaveShaperNode - 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) ); } return curve; }; ...
WebGL2RenderingContext.beginQuery() - Web APIs
return value none.
WebGL2RenderingContext.beginTransformFeedback() - Web APIs
possible values: gl.points gl.lines gl.triangles return value none.
WebGL2RenderingContext.bindBufferBase() - Web APIs
return value none.
WebGL2RenderingContext.bindBufferRange() - Web APIs
return value none.
WebGL2RenderingContext.bindSampler() - Web APIs
return value none.
WebGL2RenderingContext.bindTransformFeedback() - Web APIs
return value none.
WebGL2RenderingContext.bindVertexArray() - Web APIs
return value none.
WebGL2RenderingContext.blitFramebuffer() - Web APIs
possible values: gl.nearest gl.linear return value none.
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
return value none.
WebGL2RenderingContext.clientWaitSync() - Web APIs
return value a glenum indicating the sync object's status.
WebGL2RenderingContext.compressedTexSubImage3D() - Web APIs
return value none.
WebGL2RenderingContext.copyBufferSubData() - Web APIs
return value none.
WebGL2RenderingContext.copyTexSubImage3D() - Web APIs
return value none.
WebGL2RenderingContext.createQuery() - Web APIs
return value a webglquery object.
WebGL2RenderingContext.createSampler() - Web APIs
return value a webglsampler object.
WebGL2RenderingContext.createTransformFeedback() - Web APIs
return value a webgltransformfeedback object.
WebGL2RenderingContext.createVertexArray() - Web APIs
return value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data.
WebGL2RenderingContext.deleteQuery() - Web APIs
return value none.
WebGL2RenderingContext.deleteSampler() - Web APIs
return value none.
WebGL2RenderingContext.deleteSync() - Web APIs
return value none.
WebGL2RenderingContext.deleteTransformFeedback() - Web APIs
return value none.
WebGL2RenderingContext.deleteVertexArray() - Web APIs
return value none.
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
return value none.
WebGL2RenderingContext.drawBuffers() - Web APIs
return value none.
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
return value none.
WebGL2RenderingContext.drawRangeElements() - Web APIs
return value none.
WebGL2RenderingContext.endQuery() - Web APIs
return value none.
WebGL2RenderingContext.endTransformFeedback() - Web APIs
return value none.
WebGL2RenderingContext.fenceSync() - Web APIs
return value a webglsync object.
WebGL2RenderingContext.framebufferTextureLayer() - Web APIs
return value none.
WebGL2RenderingContext.getActiveUniformBlockName() - Web APIs
return value a domstring indicating the active uniform block name.
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
return value a gluint indicating the uniform block index.
WebGL2RenderingContext.getUniformIndices() - Web APIs
return value an array of gluint containing the uniform indices.
WebGL2RenderingContext.invalidateFramebuffer() - Web APIs
return value none.
WebGL2RenderingContext.invalidateSubFramebuffer() - Web APIs
return value none.
WebGL2RenderingContext.pauseTransformFeedback() - Web APIs
return value none.
WebGL2RenderingContext.readBuffer() - Web APIs
return value none.
WebGL2RenderingContext.resumeTransformFeedback() - Web APIs
return value none.
WebGL2RenderingContext.samplerParameter[if]() - Web APIs
return value none.
WebGL2RenderingContext.texImage3D() - Web APIs
return value none.
WebGL2RenderingContext.texStorage2D() - Web APIs
return value none.
WebGL2RenderingContext.texStorage3D() - Web APIs
return value none.
WebGL2RenderingContext.texSubImage3D() - Web APIs
return value none.
WebGL2RenderingContext.transformFeedbackVaryings() - Web APIs
return value none.
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
return value none.
WebGL2RenderingContext.uniformBlockBinding() - Web APIs
return value none.
WebGL2RenderingContext.uniformMatrix[234]x[234]fv() - Web APIs
return value none.
WebGL2RenderingContext.vertexAttribDivisor() - Web APIs
return value none.
WebGL2RenderingContext.vertexAttribI4[u]i[v]() - Web APIs
return value none.
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
return value none.
WebGLActiveInfo.name - Web APIs
the read-only webglactiveinfo.name property represents the name of the requested data returned by calling the getactiveattrib() or getactiveuniform() methods.
WebGLActiveInfo.size - Web APIs
the read-only webglactiveinfo.size property is a number representing the size of the requested data returned by calling the getactiveattrib() or getactiveuniform() methods.
WebGLActiveInfo.type - Web APIs
the read-only webglactiveinfo.type property represents the type of the requested data returned by calling the getactiveattrib() or getactiveuniform() methods.
WebGLRenderingContext.bindAttribLocation() - Web APIs
return value none.
WebGLRenderingContext.bindBuffer() - Web APIs
return value none.
WebGLRenderingContext.bindFramebuffer() - Web APIs
return value none.
WebGLRenderingContext.bindRenderbuffer() - Web APIs
return value none.
WebGLRenderingContext.bindTexture() - Web APIs
return value none.
WebGLRenderingContext.bufferData() - Web APIs
return value none.
WebGLRenderingContext.bufferSubData() - Web APIs
return value none.
WebGLRenderingContext.canvas - Web APIs
syntax gl.canvas; return value either a htmlcanvaselement or offscreencanvas object or null.
WebGLRenderingContext.clear() - Web APIs
possible values are: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit return value none.
WebGLRenderingContext.clearDepth() - Web APIs
return value none.
WebGLRenderingContext.clearStencil() - Web APIs
return value none.
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
return value none.
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
return value none.
WebGLRenderingContext.copyTexImage2D() - Web APIs
return value none.
WebGLRenderingContext.copyTexSubImage2D() - Web APIs
return value none.
WebGLRenderingContext.createBuffer() - Web APIs
return value a webglbuffer storing data such as vertices or colors.
WebGLRenderingContext.createFramebuffer() - Web APIs
return value a webglframebuffer object.
WebGLRenderingContext.createProgram() - Web APIs
return value a webglprogram object that is a combination of two compiled webglshaders consisting of a vertex shader and a fragment shader (both written in glsl).
WebGLRenderingContext.createRenderbuffer() - Web APIs
return value a webglrenderbuffer object that stores data such an image, or can be source or target of an rendering operation.
WebGLRenderingContext.createTexture() - Web APIs
return value a webgltexture object to which images can be bound to.
WebGLRenderingContext.cullFace() - Web APIs
possible values are: gl.front gl.back gl.front_and_back return value none.
WebGLRenderingContext.deleteBuffer() - Web APIs
return value none.
WebGLRenderingContext.deleteFramebuffer() - Web APIs
return value none.
WebGLRenderingContext.deleteProgram() - Web APIs
return value none.
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
return value none.
WebGLRenderingContext.deleteShader() - Web APIs
return value none.
WebGLRenderingContext.deleteTexture() - Web APIs
return value none.
WebGLRenderingContext.depthFunc() - Web APIs
e depth buffer value) gl.lequal (pass if the incoming value is less than or equal to the depth buffer value) gl.greater (pass if the incoming value is greater than the depth buffer value) gl.notequal (pass if the incoming value is not equal to the depth buffer value) gl.gequal (pass if the incoming value is greater than or equal to the depth buffer value) gl.always (always pass) return value none.
WebGLRenderingContext.disable() - Web APIs
return value none.
WebGLRenderingContext.drawArrays() - Web APIs
return value none.
WebGLRenderingContext.drawElements() - Web APIs
return value none.
WebGLRenderingContext.enable() - Web APIs
return value none.
WebGLRenderingContext.finish() - Web APIs
return value none.
WebGLRenderingContext.flush() - Web APIs
return value none.
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
return value none.
WebGLRenderingContext.framebufferTexture2D() - Web APIs
return value none.
WebGLRenderingContext.frontFace() - Web APIs
return value none.
WebGLRenderingContext.generateMipmap() - Web APIs
return value none.
WebGLRenderingContext.getExtension() - Web APIs
return value a webgl extension object, or null if name does not match (case-insensitive) to one of the strings in webglrenderingcontext.getsupportedextensions.
WebGLRenderingContext.hint() - Web APIs
return value none.
WebGLRenderingContext.isEnabled() - Web APIs
return value a glboolean indicating if the capability cap is enabled (true), or not (false).
WebGLRenderingContext.linkProgram() - Web APIs
return value none.
WebGLRenderingContext.makeXRCompatible() - Web APIs
return value a promise which successfully resolves once the webgl context is ready to be used for rendering webxr content.
WebGLRenderingContext.pixelStorei() - Web APIs
return value none.
WebGLRenderingContext.polygonOffset() - Web APIs
return value none.
WebGLRenderingContext.readPixels() - Web APIs
return value none.
WebGLRenderingContext.renderbufferStorage() - Web APIs
return value none.
WebGLRenderingContext.sampleCoverage() - Web APIs
return value none.
WebGLRenderingContext.shaderSource() - Web APIs
return value none.
WebGLRenderingContext.stencilFunc() - Web APIs
return value none.
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
return value none.
WebGLRenderingContext.stencilMask() - Web APIs
return value none.
WebGLRenderingContext.stencilMaskSeparate() - Web APIs
return value none.
WebGLRenderingContext.stencilOp() - Web APIs
return value none.
WebGLRenderingContext.stencilOpSeparate() - Web APIs
return value none.
WebGLRenderingContext.texImage2D() - Web APIs
return value none.
WebGLRenderingContext.texParameter[fi]() - Web APIs
return value none.
WebGLRenderingContext.texSubImage2D() - Web APIs
return value none.
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
return value none.
WebGLRenderingContext.uniformMatrix[234]fv() - Web APIs
return value undefined examples gl.uniformmatrix2fv(loc, false, [2,1, 2,2]); specifications specification status comment webgl 1.0the definition of 'uniformmatrix' in that specification.
WebGLRenderingContext.useProgram() - Web APIs
return value none.
WebGLRenderingContext.validateProgram() - Web APIs
return value none.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
return value none.
WebGLRenderingContext.vertexAttribPointer() - Web APIs
return value none.
WebGLShader - Web APIs
\n\n' + info; } return shader; } see webglprogram for information on attaching the shaders.
WebGLShaderPrecisionFormat.precision - Web APIs
the read-only webglshaderprecisionformat.precision property returns the number of bits of precision that can be represented.
WebGLShaderPrecisionFormat.rangeMax - Web APIs
the read-only webglshaderprecisionformat.rangemax property returns the base 2 log of the absolute value of the maximum value that can be represented.
WebGLShaderPrecisionFormat.rangeMin - Web APIs
the read-only webglshaderprecisionformat.rangemin property returns the base 2 log of the absolute value of the minimum value that can be represented.
Basic scissoring - Web APIs
" + "your browser or device may not support webgl."; return; } 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."; return; } 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); return { 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
return { 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); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color.
WebRTC coding guide - Web APIs
once you have an overall understanding of what webrtc does and how it works, your mind likely turns to implementation.
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 returned on foot, and so forth, until the webrtc peer connection is open.
WebSocket() - Web APIs
the websocket() constructor returns a new websocket object.
WebSocket.binaryType - Web APIs
the websocket.binarytype property returns the type of binary data being transmitted by the connection.
WebSocket.bufferedAmount - Web APIs
the websocket.bufferedamount read-only property returns the number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
WebSocket.extensions - Web APIs
the websocket.extensions read-only property returns the extensions selected by the server.
WebSocket.protocol - Web APIs
the websocket.protocol read-only property returns 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.
WebSocket.readyState - Web APIs
the websocket.readystate read-only property returns the current state of the websocket connection.
WebSocket.send() - Web APIs
WebAPIWebSocketsend
note: gecko's implementation of the send() method differs somewhat from the specification in gecko 6.0; gecko returns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this is corrected in gecko 8.0.
WebSocket.url - Web APIs
WebAPIWebSocketurl
the websocket.url read-only property returns the absolute url of the websocket as resolved by the constructor.
WebSocket - Web APIs
WebAPIWebSocket
constructor websocket(url[, protocols]) returns a newly created websocket object.
Writing WebSocket client applications - Web APIs
var examplesocket = new websocket("wss://www.example.com/socketserver", "protocolone"); on return, examplesocket.readystate is connecting.
Writing a WebSocket server in C# - Web APIs
methods: start() system.net.sockets.tcpclient accepttcpclient() waits for a tcp connection, accepts it and returns it as a tcpclient object.
Writing WebSocket servers - Web APIs
to get it, concatenate the client's sec-websocket-key and the string "258eafa5-e914-47da-95ca-c5ab0dc85b11" together (it's a "magic string"), take the sha-1 hash of the result, and return the base64 encoding of that hash.
WebXR application life cycle - Web APIs
if the promise returned by requestsession() resolves, use the new xrsession to manage the webxr session for the duration of the webxr experience.
Keyframe Formats - Web APIs
this is the canonical format returned by the getkeyframes() method.
Using the Web Animations API - Web APIs
we can, in fact, do so by referencing alicechange’s animation.effect property, which returns an object containing all the details of the effect(s) active on alice: alicechange.currenttime = alicechange.effect.getcomputedtiming().duration / 2; effect lets us access the animation’s keyframes and timing properties — alicechange.effect.getcomputedtiming() points to alice’s timing object (which is of type computedeffecttiming) — this contains her computedeffecttiming.duration.
Controlling multiple parameters with ConstantSourceNode - Web APIs
once all three oscillators have been created, they're started by calling each one's constantsourcenode.start() method in turn, and playing is set to true to track that the tones are playing.
Visualizations with Web Audio API - Web APIs
we return the analysernode.frequencybincount value, which is half the fft, then call uint8array() with the frequencybincount as its length argument — this is how many data points we will be collecting, for that fft size.
Web Bluetooth API - Web APIs
interfaces bluetooth returns a promise to a bluetoothdevice object with the specified options.
WheelEvent() - Web APIs
the wheelevent() constructor returns a newly created wheelevent object.
WheelEvent.deltaMode - Web APIs
the wheelevent.deltamode read-only property returns an unsigned long representing the unit of the delta values scroll amount.
Window.applicationCache - Web APIs
returns a reference to the application cache object for the window.
window.cancelAnimationFrame() - Web APIs
syntax window.cancelanimationframe(requestid); parameters requestid the id value returned by the call to window.requestanimationframe() that requested the callback.
Window.clearImmediate() - Web APIs
syntax window.clearimmediate( immediateid ) where immediateid is a id returned by window.setimmediate.
Window.close() - Web APIs
WebAPIWindowclose
note also that close() has no effect when called on window objects returned by htmliframe​element​.content​window.
Window.console - Web APIs
WebAPIWindowconsole
the window.console property returns a reference to the console object, which provides methods for logging information to the browser's console.
Window.controllers - Web APIs
the controllers property of the window interface returns the xul controllers of the chrome window.
Window.customElements - Web APIs
the customelements read-only property of the window interface returns a reference to the customelementregistry object, which can be used to register new custom elements and get information about previously registered custom elements.
Window.dialogArguments - Web APIs
the dialogarguments property returns the parameters that were passed into the window.showmodaldialog() method.
Window.directories - Web APIs
summary returned the window personalbar toolbar object.
Window.document - Web APIs
WebAPIWindowdocument
window.document returns a reference to the document contained in the window.
Window.external - Web APIs
WebAPIWindowexternal
the external property of the window api returns an instance of the external interface, which was intended to contain functions related to adding external search providers to the browser.
Window.find() - Web APIs
WebAPIWindowfind
returns true if the string is found; otherwise, false.
Window.focus() - Web APIs
WebAPIWindowfocus
it may fail due to user settings and the window isn't guaranteed to be frontmost before this method returns.
Window.forward() - Web APIs
WebAPIWindowforward
syntax window.forward(); parameters none return value undefined.
Window.frameElement - Web APIs
the window.frameelement property returns the element (such as <iframe> or <object>) in which the window is embedded.
Window.fullScreen - Web APIs
WebAPIWindowfullScreen
return value isinfullscreen a boolean.
Window.history - Web APIs
WebAPIWindowhistory
the window.history read-only property returns a reference to the history object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).
Window.home() - Web APIs
WebAPIWindowhome
the window.home() method returns the window to the home page.
Window.length - Web APIs
WebAPIWindowlength
returns the number of frames (either <frame> or <iframe> elements) in the window.
Window.locationbar - Web APIs
returns the locationbar object, whose visibility can be checked.
Window.menubar - Web APIs
WebAPIWindowmenubar
the window.menubar property returns the menubar object, whose visibility can be checked.
Window.mozAnimationStartTime - Web APIs
returns the time, in milliseconds since the epoch, at which animations started now should be considered to have started.
Window.mozPaintCount - Web APIs
returns the number of times the current document has been painted to the screen in this window.
Window.orientation - Web APIs
summary returns the orientation in degrees (in 90-degree increments) of the viewport relative to the device's natural orientation.
Window.outerHeight - Web APIs
the window.outerheight read-only property returns the height in pixels of the whole browser window, including any sidebar, window chrome, and window-resizing borders/handles.
Window.outerWidth - Web APIs
WebAPIWindowouterWidth
window.outerwidth read-only property returns the width of the outside of the browser window.
Window: pageshow event - Web APIs
this includes: initially loading the page navigating to the page from another page in the same window or tab restoring a frozen page on mobile oses returning to the page using the browser's forward or back buttons during the initial page load, the pageshow event fires after the load event.
Window.performance - Web APIs
the window interface's performance property returns a performance object, which can be used to gather performance information about the current document.
Window.personalbar - Web APIs
returns the personalbar object, whose visibility can be toggled in the window.
Window: popstate event - Web APIs
if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute.
Window.print() - Web APIs
WebAPIWindowprint
however in more recent versions of safari, it may return immediately.
window.requestIdleCallback() - Web APIs
syntax var handle = window.requestidlecallback(callback[, options]) return value an id which can be used to cancel the callback by passing it into the window.cancelidlecallback() method.
Window: resize event - Web APIs
returned by document.defaultview).
Window.screen - Web APIs
WebAPIWindowscreen
the window property screen returns a reference to the screen object associated with the window.
Window.scrollMaxX - Web APIs
WebAPIWindowscrollMaxX
the window.scrollmaxx read-only property returns the maximum number of pixels that the document can be scrolled horizontally.
Window.scrollMaxY - Web APIs
WebAPIWindowscrollMaxY
the window.scrollmaxy read-only property returns the maximum number of pixels that the document can be scrolled vertically.
Window.scrollbars - Web APIs
WebAPIWindowscrollbars
the window.scrollbars property returns the scrollbars object, whose visibility can be checked.
Window.self - Web APIs
WebAPIWindowself
the window.self read-only property returns the window itself, as a windowproxy.
Window.showModalDialog() - Web APIs
syntax returnval = window.showmodaldialog(uri[, arguments][, options]); returnval holds the returnvalue property as set by the document specified by uri.
Window.speechSynthesis - Web APIs
the speechsynthesis read-only property of the window object returns a speechsynthesis object, which is the entry point into using web speech api speech synthesis functionality.
Window.statusbar - Web APIs
WebAPIWindowstatusbar
the window.statusbar property returns the statusbar object, whose visibility can be toggled in the window.
Window.toolbar - Web APIs
WebAPIWindowtoolbar
the window.toolbar property returns the toolbar object, whose visibility can be toggled in the window.
Window.visualViewport - Web APIs
the visualviewport read-only property of the window interface returns a visualviewport object representing the visual viewport for a given window.
Window.window - Web APIs
WebAPIWindowwindow
thus, the following expressions all return 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) return client.focus(); } } } if (clients.openwindow) return 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') return client.focus(); } } } if (clients.openwindow) { return clients.openwindow('/'); } })); }); specifications specification status comment service workersthe definition of 'visibilitystate' in that specification.
WindowClient - Web APIs
e(); // 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) { client.focus(); break; } } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment service workersthe definition of 'windowclient' in that specification.
WindowOrWorkerGlobalScope.atob() - Web APIs
return value an ascii string containing decoded data from encodeddata.
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
this id was returned by the corresponding call to settimeout().
WindowOrWorkerGlobalScope.crossOriginIsolated - Web APIs
the crossoriginisolated read-only property of the windoworworkerglobalscope interface returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call.
WindowOrWorkerGlobalScope.isSecureContext - Web APIs
the issecurecontext read-only property of the windoworworkerglobalscope interface returns a boolean indicating whether the current context is secure (true) or not (false).
Worker.prototype.postMessage() - Web APIs
returns void.
Worker.terminate() - Web APIs
WebAPIWorkerterminate
returns void.
WorkerGlobalScope.dump() - Web APIs
returns void.
WorkerGlobalScope.importScripts() - Web APIs
return value none.
WorkerGlobalScope.self - Web APIs
the self read-only property of the workerglobalscope interface returns a reference to the workerglobalscope itself.
WorkerNavigator.connection - Web APIs
the workernavigator.connection read-only property returns a networkinformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered.
WorkerNavigator.locks - Web APIs
the locks read-only property of the workernavigator interface returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
WorkerNavigator.permissions - Web APIs
the workernavigator.permissions read-only property returns a permissions object that can be used to query and update permission status of apis covered by the permissions api.
WritableStream.abort() - Web APIs
return value a promise, which fulfills with the value given in the reason parameter.
WritableStreamDefaultWriter.closed - Web APIs
the closed read-only property of the writablestreamdefaultwriter interface returns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors.
WritableStreamDefaultWriter.ready - Web APIs
the ready read-only property of the writablestreamdefaultwriter interface returns 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.
WritableStreamDefaultWriter.releaseLock() - Web APIs
return value undefined.
XDomainRequest.responseText - Web APIs
returns the response body of an xdomainrequest as a string.
XDomainRequest - Web APIs
syntax var xdr = new xdomainrequest(); returns 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); return 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() - Web APIs
return value a new xmlhttprequest object.
XMLHttpRequest.abort() - Web APIs
return 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(); return 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(); return 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(); return 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(); return 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(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest.open() - Web APIs
if this value is false, the send() method does not return until the response is received.
XMLHttpRequest.overrideMimeType() - Web APIs
return value undefined.
XMLHttpRequest: progress event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest.readyState - Web APIs
the xmlhttprequest.readystate property returns the state an xmlhttprequest client is in.
XMLHttpRequest.response - Web APIs
the xmlhttprequest response property returns the response's body content as an arraybuffer, blob, document, javascript object, or domstring, depending on the value of the request's responsetype property.
XMLHttpRequest.responseText - Web APIs
the read-only xmlhttprequest property responsetext returns the text received from a server following a request being sent.
XMLHttpRequest.responseType - Web APIs
if the server returns data that is not compatible with the responsetype that was set, the value of response will be null.
XMLHttpRequest.responseXML - Web APIs
the xmlhttprequest.responsexml read-only property returns a document containing the html or xml retrieved by the request; or null if the request was unsuccessful, has not yet been sent, or if the data can't be parsed as xml or html.
XMLHttpRequest.sendAsBinary() - Web APIs
return value undefined.
XMLHttpRequest.setRequestHeader() - Web APIs
return value undefined.
XMLHttpRequest.status - Web APIs
the read-only xmlhttprequest.status property returns the numerical http status code of the xmlhttprequest's response.
XMLHttpRequest.statusText - Web APIs
the read-only xmlhttprequest.statustext property returns a domstring containing the response's status message as returned by the http server.
XMLHttpRequest.upload - Web APIs
the xmlhttprequest upload property returns an xmlhttprequestupload object that can be observed to monitor an upload's progress.
XMLHttpRequestEventTarget - Web APIs
xmlhttprequesteventtarget.onload contains the function to call when an http request returns after successfully fetching content and the load event is received by this object.
XMLHttpRequestResponseType - Web APIs
accessing response during a progress event returns the data received so far.
XMLSerializer.serializeToString() - Web APIs
return value a domstring containing the xml representation of the specified dom tree.
XPathEvaluator.createExpression() - Web APIs
return value a xpathexpression representing the compiled form of the xpath expression.
XPathEvaluator.createNSResolver() - Web APIs
return value an xpathnsresolver object which resolves namespaces with respect to the definitions in scope for a specified node.
XPathEvaluator - Web APIs
xpathevaluator.evaluate() evaluates an xpath expression string and returns a result of the specified type if possible.
XPathException.code - Web APIs
the code read-only property of the xpathexception interface returns a short that contains one of the error code constants.
XPathExpression - Web APIs
this interface is a compiled xpath expression that can be evaluated on a document or specific node to return information from its dom tree.
XPathNSResolver.lookupNamespaceURI() - Web APIs
return value a domstring representing the associated namespace uri or null if none is found.
XPathResult.resultType - Web APIs
syntax var resulttype = result.resulttype; return value an integer value representing the type of the result, as defined by the type constants.
XPathResult.snapshotLength - Web APIs
syntax var snapshotlength = result.snapshotlength; return value an integer value representing the number of nodes in the result snapshot.
XRFrame.session - Web APIs
WebAPIXRFramesession
an xrframe object's read-only session property returns the xrsession object that generated the frame.
XRInputSource.profiles - Web APIs
the read-only xrinputsource property profiles returns an array of strings, each describing a configuration profile for the input source.
XRInputSourceArray.forEach() - Web APIs
return value undefined.
XRInputSourceArray.length - Web APIs
the read-only length property returns an integer value indicating the number of items in the input source list represented by the xrinputsourcearray object.
XRInputSourceEvent - Web APIs
constructor xrinputsourceevent() creates and returns a new xrinputsourceevent object whose properties match those provided in the eventinitdict dictionary provided.
XRInputSourcesChangeEvent - Web APIs
constructor xrinputsourceschangeevent() creates and returns a new xrinputsourceschangeevent object configured as indicated by the given xrinputsourceschangeeventinit object.
XRPermissionDescriptor.requiredFeatures - Web APIs
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 returned object.
XRPermissionStatus.granted - Web APIs
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 returned object.
XRPermissionStatus - Web APIs
the xrpermissionstatus interface defines the object returned by calling navigator.permissions.query() for the xr permission name; it indicates whether or not the app or site has permission to use webxr, an may be monitored over time for changes to that permissions tate.
XRPose.transform - Web APIs
WebAPIXRPosetransform
this is the same pose that's returned by the frame's getpose() method.
XRReferenceSpaceEvent() - Web APIs
return value a new xrreferencespaceevent object, initialized as defined by the input parameters.
XRReferenceSpaceEvent - Web APIs
constructor xrreferencespaceevent() returns a new xrreferencespaceevent with the specified type and configured using the values in the given xrreferencespaceeventinit dictionary.
XRRenderState.depthFar - Web APIs
the depthfar read-only property of the xrrenderstate interface returns the distance in meters of the far clip plane from the viewer.
XRRenderState.depthNear - Web APIs
the depthnear read-only property of the xrrenderstate interface returns the distance in meters of the near clip plane from the viewer.
XRRenderState.inlineVerticalFieldOfView - Web APIs
the read-only inlineverticalfieldofview property of the xrrenderstate interface returns the default vertical field of view for "inline" sessions and null for all immersive sessions.
XRRigidTransform.orientation - Web APIs
as a unit quaternion, the length of the returned quaternion is always 1.0 meters.
XRSession.onsqueezeend - Web APIs
if heldobject has an object reference, that object is passed to a function called cancelobjectdrag(), which would be written to return the object to its original position.
XRSession.renderState - Web APIs
the read-only renderstate property of an xrsession object indicates the returns a xrrenderstate object describing how the user's environment which should be rendered.
XRSession.requestAnimationFrame() - Web APIs
return value an integer value which serves as a unique, non-zero id or handle you may pass to cancelanimationframe() if you need to remove the pending animation frame request.
XRSessionEvent - Web APIs
constructor xrsessionevent() creates and returns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available.
XRView.eye - Web APIs
WebAPIXRVieweye
updateinjury() returns true if the eye is still injured or false if the eye has been restored to health by the function,.
XRView.transform - Web APIs
WebAPIXRViewtransform
to convert the "camera focused" transform matrix into an "object focused" transform, we use the transform's inverse, thus taking the matrix returned by view.transform.inverse.matrix.
XRWebGLLayer.antialias - Web APIs
when the webxr compositor is enabled, this value corresponds to the value of the antialias property on the object returned by the webgl context's getcontentattributes() method.
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 returned by xrwebgllayer.ignoredepthvalues.
XRWebGLLayerInit - Web APIs
the static xrwebgllayer function xrwebgllayer.getnativeframebufferscalefactor() returns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution.
msCachingEnabled - Web APIs
return value type: boolean.
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: return; } }; 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 return 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 return 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: timer role - Accessibility
all aspects of interaction, including returning to the regular web content on other parts of the page, must be handled.
ARIA: application role - Accessibility
all aspects of interaction, including returning to the regular web content on other parts of the page, must be handled.
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 returns 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">saturn</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 &amp; delivery</a></li> <li><a href="#">returns</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: rowgroup role - Accessibility
each row, in turn, contains child cells.
ARIA: button role - Accessibility
if the button closes a dialog, focus should returns 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="return listitemclick(event);" onkeydown="return listitemkeyevent(event);" onkeypress="return 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); // returns 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 returns true state_system_ checked if checked property of dom element returns 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 returns true n/a "select" event_object_ statechange when state ...
Web accessibility for seizures and physical reactions - Accessibility
developmental & experimental features mdn navigator​.donottrack from the documentation: "returns the user's do-not-track setting.
Keyboard - Accessibility
in such a case, focusing the nested document is the only way of returning assistive technology to a non-interactive state (often called "browse mode").
Perceivable - Accessibility
don't make it look/sound like content, and provide a control to turn it off.
-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.
::selection - CSS: Cascading Style Sheets
it returned in pseudo-elements level 4.
:active - CSS: Cascading Style Sheets
WebCSS:active
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.
:nth-child() - CSS: Cascading Style Sheets
the first one to be returned as a result of the formula is 0 [=5x0], resulting in a no-match, since the elements are indexed from 1, whereas n starts from 0.
:nth-last-child() - CSS: Cascading Style Sheets
in this example, list items turn red when there are at least three of them in a given list.
:scope - CSS: Cascading Style Sheets
WebCSS:scope
javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.call(selected, function (element) { return '#' + 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
WebCSS:visited
although these styles can be change the appearance of colors to the end user, the window.getcomputedstyle method will lie and always return the value of the non-:visited color.
@media - CSS: Cascading Style Sheets
WebCSS@media
because of this potential, a browser may opt to fudge the returned values in some manner in order to prevent them from being used to precisely identify a computer.
Coordinate systems - CSS: Cascading Style Sheets
note also the effect of scrolling the example horizontally upon the values returned and how the value of clientx doesn't change.
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
values: see the flex reference for values and default spec: https://drafts.csswg.org/css-flexbox/#flex-property @mixin flex($fg: 1, $fs: 0, $fb: auto) { // set a variable to be used by box-flex properties $fg-boxflex: $fg; // box-flex only supports a flex-grow value so lets grab the // first item in the list and just return that.
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
you can try removing the display: contents line to see it return.
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
returning to the source if at any time in the design process you find yourself using grid to relocate the position of an element, consider whether you should return to your document and make a change to the logical order too.
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
i can turn my <ul> into a grid container with three column tracks.
Consistent list indentation - CSS: Cascading Style Sheets
as it turns out, nobody seems to have used the first option.
Descendant combinator - CSS: Cascading Style Sheets
/* list items that are descendants of the "my-things" list */ ul.my-things li { margin: 2em; } the descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage return, form feed, new line, and tab characters — between two selectors in the absence of another combinator.
Center an element - CSS: Cascading Style Sheets
in the future we may be able to center elements without needing to turn the parent into a flex container, as the box alignment properties used here are specified to apply to block layout too.
Column layouts - CSS: Cascading Style Sheets
a continuous thread of content — multi-column layout if you create columns using multi-column layout your text will remain as a continuous stream filling each column in turn.
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
example this example has an annoying animation unless you turn on reduce motion in your accessibility preferences.
Privacy and the :visited selector - CSS: Cascading Style Sheets
little white lies to preserve users' privacy, firefox and other browsers will lie to web applications under certain circumstances: the window.getcomputedstyle method, and similar functions such as element.queryselector, will always return values indicating that a user has never visited any of the links on a page.
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
tationtext-overflowtext-renderingtext-shadowtext-transformtext-underline-offsettext-underline-position<time><time-percentage><timing-function>top@top-centertouch-actiontransformtransform-box<transform-function>transform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functiontranslatetranslate()translate3d()translatex()translatey()translatez()turnuunicode-bidiunicode-range (@font-face)unset<url>url()user-zoom (@viewport)v:validvar()vertical-alignvh@viewportviewport-fit (@viewport)visibility:visitedvmaxvminvwwwhite-spacewidowswidthwidth (@viewport)will-changeword-breakword-spacingword-wrapwriting-modexxzz-indexzoom (@viewport)others--* selectors the following are the various selectors, which allow styles to be conditional based on variou...
Shorthand properties - CSS: Cascading Style Sheets
effectively, this "turns on inheritance".
Specificity - CSS: Cascading Style Sheets
b) overriding high specificity #someelement p { color: blue; } p.awesome { color: red; } how do you make awesome paragraphs always turn red, even ones inside #someelement?
Viewport concepts - CSS: Cascading Style Sheets
the values returned for the outerwidth and outerheight depend on the browser: firefox reports the new value in css pixels, but chrome returns the length in the default pixel size.
Visual formatting model - CSS: Cascading Style Sheets
grid layout behaves in the same way as the flexbox example above, turning strings of text into a grid item with an anonymous box.
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-return-to-realtime-button div{ color: black; -moz-appearance: media-return-to-realtime-button; -webkit-appearance: media-return-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 returns a new color value.
box-flex-group - CSS: Cascading Style Sheets
each flex group is examined in turn and space is removed according to the ratio of the flexibility of each element.
break-inside - CSS: Cascading Style Sheets
thus, the break-before value has precedence over the break-after value, which in turn has precedence over the break-inside value.
calc() - CSS: Cascading Style Sheets
WebCSScalc
note: the chrome browser currently won’t accept some values returned by calc() when an integer is expected.
color - CSS: Cascading Style Sheets
WebCSScolor
allows alpha values in rgb() and hsl(), turning rgba() and hsla() into (deprecated) aliases for them.
content - CSS: Cascading Style Sheets
WebCSScontent
if there is no attribute x, an empty string is returned.
<easing-function> - CSS: Cascading Style Sheets
this causes the animation to go farther than the final state, and then return.
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(.5turn) /* 180deg rotation */ hue-rotate(405deg) /* same as 45deg rotation */ specifications specification status filter effects module level 1the definition of 'hue-rotate()' in that specification.
filter - CSS: Cascading Style Sheets
WebCSSfilter
if the parameter for any function is invalid, the function returns none.
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
this is because the inner <span>'s font-size is 1.6em which is relative to its parent's font-size, which is in turn relative to its parent's font-size.
font - CSS: Cascading Style Sheets
WebCSSfont
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"); return 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; return oradio[i].value; ...
<length> - CSS: Cascading Style Sheets
WebCSSlength
300px, 50%, 30vw) to set the width of a result bar that will appear below it once you've pressed return.
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(.25turn, 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: .5turn; 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.
Resolved value - CSS: Cascading Style Sheets
the resolved value of a css property is the value returned by getcomputedstyle().
rotate - CSS: Cascading Style Sheets
WebCSSrotate
syntax /* keyword values */ rotate: none; /* angle value */ rotate: 90deg; rotate: 0.25turn; rotate: 1.57rad; /* x, y, or z axis name plus angle */ rotate: x 90deg; rotate: y 0.25turn; 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
WebCSSsymbols
[ <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 returns 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') { return; } 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.
url() - CSS: Cascading Style Sheets
WebCSSurl()
css values and units level 3 returned to the narrower, initial definition.
<url> - CSS: Cascading Style Sheets
WebCSSurl
to alleviate the confusion, css level 3 returned to the narrower, initial definition.
Used value - CSS: Cascading Style Sheets
note: the getcomputedstyle() dom api returns the resolved value, which may either be the computed value or the used value, depending on the property.
Math (math) - EXSLT
WebEXSLTmath
math:highest()math:highest() returns the node in the specified node-set with the highest value (where the highest value calculated using math:max()).math:lowest()math:lowest() returns the node in the specified node-set with the lowest value (where the lowest value calculated using math:min()).math:max()math:max() returns the maximum value of a node-set.math:min()math:min() returns the minimum value of a node-set.
regexp:replace() - EXSLT
WebEXSLTregexpreplace
returns the revised version of the string.
regexp:test() - EXSLT
WebEXSLTregexptest
returns true if the specified regexp matches the test string.
Regular expressions (regexp) - EXSLT
WebEXSLTregexp
regexp:match()regexp:match() performs regular expression matching on a string, returning the submatches found as a result.regexp:replace()regexp:replace() replaces the portions of a string that match a given regular expression with the contents of another string.regexp:test()regexp:test() tests to see whether a string matches a specified regular expression.
set:has-same-node() - EXSLT
returns true if the two node-sets have any nodes in common; otherwise false.
Strings (str) - EXSLT
WebEXSLTstr
str:concat()str:concat() returns 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, returning 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, returning a node-set containing the resulting strings.
Ajax - Developer guides
WebGuideAJAX
file objects may be obtained from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement.
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) { return !!desc && (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer = new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); ...
Overview of events and handlers - Developer guides
the function, in turn, would perform whatever action was chosen by the programmer, in this case to open an html alert dialog.
Using device orientation with 3D transforms - Developer guides
1 : -1 ) * math.atan2( -rm10, rm00 ); } return { alpha: -ea[0] * to_deg - 180, beta: -ea[1] * to_deg, gamma: ea[2] * to_deg }; } ...
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 return 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.
HTML attribute: minlength - HTML: Hypertext Markup Language
the input will fail constraint validation if the length of the text value of the field is less than minlength utf-16 code units long, with validitystate.tooshort returning true.
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
browser support firefox 21 includes an implementation of dash for html5 webm video which is turned off by default.
Date and time formats used in HTML - HTML: Hypertext Markup Language
for <input>, the values of type that return 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.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
this can be used, in turn, for styling or scripting purposes.
<br>: The Line Break element - HTML: Hypertext Markup Language
WebHTMLElementbr
the html <br> element produces a line break in text (carriage-return).
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
it has been in orbit for over 20 years, scanning the sky and returning 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
WebHTMLElementinputbutton
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) { return 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
WebHTMLElementinputcheckbox
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="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
we create a new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text.
<input type="datetime-local"> - HTML: Hypertext Markup Language
browsers that don't support datetime-local return text, since that's what datetime-local falls back to.
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
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 returned to know which database record to update with modified information.
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
browsers that don't support type month will return text, since that's what month falls back to when not supported.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
note: checkboxes are similar to radio buttons, but with an important distinction: radio buttons are designed for selecting one value out of a set, whereas checkboxes let you turn individual values on and off.
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
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 returned 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
WebHTMLElementinputtime
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 return text, because the time type falls back to type text.
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
non-supporting browsers will return text, because the week type falls back to type text.
<isindex> - HTML: Hypertext Markup Language
WebHTMLElementisindex
when sent, the server would return a list of pages matching the query.
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementnextid
so then the nextid value is z30 when it's returned modified: <html> <head> <title> ...
<noscript> - HTML: Hypertext Markup Language
WebHTMLElementnoscript
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.
<ol>: The Ordered List element - HTML: Hypertext Markup Language
WebHTMLElementol
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>.
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.
inputmode - HTML: Hypertext Markup Language
for instance, the return/submit key may be labeled "search", along with possible other optimizations.
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.
x-ms-format-detection - HTML: Hypertext Markup Language
none format detection is turned off.
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 returns 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 returns null).
Preloading content with rel="preload" - HTML: Hypertext Markup Language
the basics you most commonly use <link> to load a css file to style your page with: <link rel="stylesheet" href="styles/main.css"> here however, we will use a rel value of preload, which turns <link> into a preloader for any resource we want.
Using the application cache - HTML: Hypertext Markup Language
newlines may be represented by line feed (u+000a), carriage return (u+000d), or carriage return and line feed both.
Identifying resources on the Web - HTTP
the web server can use those parameters to do extra stuff before returning the resource to the user.
MIME types (IANA media types) - HTTP
examples include multipart/form-data (for data produced using the formdata api) and multipart/byteranges (defined in rfc 7233: 5.4.1 and used with http's 206 "partial content" response returned when the fetched data is only part of the content, such as is delivered using the range header).
Reason: CORS request did not succeed - HTTP
one scenario might be an http service being developed that panicked without returning any data.
Reason: CORS disabled - HTTP
WebHTTPCORSErrorsCORSDisabled
when this happens, the user needs to turn cors back on in their browser.
Content Security Policy (CSP) - HTTP
WebHTTPCSP
to enable csp, you need to configure your web server to return the content-security-policy http header.
HTTP conditional requests - HTTP
the more flexible one makes use of if-unmodified-since and if-match and the server returns 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 returns a specific representation to the client.
Using Feature Policy - HTTP
to turn on the enforcement of all the best practices, specify the policy as below.
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 returned with the resource, the response is ignored by the browser and not returned 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 returning 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 return network errors, as the urls provided do not match prefetch-src's source list: <link rel="prefetch" src="https://example.org/"></link> <link rel="prerender" src="https://example.org/"></link> specification specification status comment content security policy level 3the definition of 'prefetch-src' in that specification.
Content-Type - HTTP
in responses, a content-type header tells the client what the content type of the returned content actually is.
Feature-Policy: autoplay - HTTP
when this policy is enabled and there were no user gestures, the promise returned by htmlmediaelement.play() will reject with a domexception.
Feature-Policy: camera - HTTP
when this policy is enabled, the promise returned by mediadevices.getusermedia() will reject with a notallowederror.
Feature-Policy: encrypted-media - HTTP
when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception.
Feature-Policy: fullscreen - HTTP
when this policy is enabled, the returned promise rejects with a typeerror.
Feature-Policy: microphone - HTTP
when this policy is enabled, the promise returned by mediadevices.getusermedia() will reject with a notallowederror.
Feature-Policy: midi - HTTP
when this policy is enabled, the promise returned 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 return 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 return http status code 304 (not modified).
Location - HTTP
WebHTTPHeadersLocation
location is a header associated with the response, while content-location is associated with the entity returned.
Server-Timing - HTTP
consider to control which metrics are returned 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 returns 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
WebHTTPMethodsHEAD
the http head method requests the headers that would be returned 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 returned 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)) return "direct"; else return "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 return 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.
HTTP range requests - HTTP
it indicates the part(s) of a document that the server should return.
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; return 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 returning 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
WebHTTPStatus201
the new resource is effectively created before this response is sent back and the new resource is returned 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
WebHTTPStatus406
if a server returns 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
WebHTTPStatus413
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 return a retry-after header field.
418 I'm a teapot - HTTP
WebHTTPStatus418
a combined coffee/tea pot that is temporarily out of coffee should instead return 503.
501 Not Implemented - HTTP
WebHTTPStatus501
the only methods that servers are required to support (and therefore that must not return 501) are get and head.
HTTP
WebHTTP
the client then returns 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 returns 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.
Keyed collections - JavaScript
you can use a for...of loop to return an array of [key, value] for each iteration.
Character classes - JavaScript
\r matches a carriage return.
Deprecated and obsolete features - JavaScript
object property description __count__ returns the number of enumerable properties directly on a user-defined object.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
in non-strict code, the operation returns false.
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(); return (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; }; }; json.stringify(circularreference, getcircularreplacer()); // {"otherdata":123} ...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
in non-strict code, the operation just returns false.
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
the source map specification changed the syntax due to a conflict with ie whenever it was found in the page after //@cc_on was interpreted to turn on conditional compilation in the ie jscript engine.
SyntaxError: missing formal parameter - JavaScript
all these function declarations fail, as they are providing values for their parameters: function square(3) { return number * number; }; // syntaxerror: missing formal parameter function greet("howdy") { return 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) { return 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 returns 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]); } return 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 returns 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).
Array.prototype.length - JavaScript
the length property of an object which is an instance of type array sets or returns the number of elements in that array.
ArrayBuffer() constructor - JavaScript
return value a new arraybuffer object of the specified size.
ArrayBuffer.prototype.byteLength - JavaScript
this property returns 0 if this arraybuffer has been detached.
ArrayBuffer.isView() - JavaScript
return value true if the given argument is one of the arraybuffer views; otherwise, false.
AsyncFunction - JavaScript
examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a = new asyncfunction('a', 'b', 'return await resolveafter2seconds(a) + await resolveafter2seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds });...
BigInt() constructor - JavaScript
the bigint() constructor returns a value of type bigint.
BigInt.asIntN() - JavaScript
returns the value of bigint modulo 2width as a signed integer.
BigInt.asUintN() - JavaScript
returns the value of bigint modulo 2width as an unsigned integer.
DataView.prototype.byteLength - JavaScript
if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be returned.
DataView.prototype.getBigInt64() - JavaScript
return value a bigint.
DataView.prototype.getBigUint64() - JavaScript
return value a bigint.
DataView.prototype.getFloat32() - JavaScript
return value a signed 32-bit float number.
DataView.prototype.getFloat64() - JavaScript
return value a signed 64-bit float number.
DataView.prototype.getInt16() - JavaScript
return value a signed 16-bit integer number.
DataView.prototype.getInt32() - JavaScript
return value a signed 32-bit integer number.
DataView.prototype.getInt8() - JavaScript
return value a signed 8-bit integer number.
DataView.prototype.getUint16() - JavaScript
return value an unsigned 16-bit integer number.
DataView.prototype.getUint32() - JavaScript
return value an unsigned 32-bit integer number.
DataView.prototype.getUint8() - JavaScript
return value an unsigned 8-bit integer number.
DataView.prototype.setBigInt64() - JavaScript
return value undefined.
DataView.prototype.setBigUint64() - JavaScript
return value undefined.
DataView.prototype.setFloat32() - JavaScript
return value undefined.
DataView.prototype.setFloat64() - JavaScript
return value undefined.
DataView.prototype.setInt16() - JavaScript
return value undefined.
DataView.prototype.setInt32() - JavaScript
return value undefined.
DataView.prototype.setInt8() - JavaScript
return value undefined.
DataView.prototype.setUint16() - JavaScript
return value undefined.
DataView.prototype.setUint32() - JavaScript
return value undefined.
DataView.prototype.setUint8() - JavaScript
return value undefined.
Date.prototype.setDate() - JavaScript
return value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date (the date object is also changed in place).
Date.prototype.setMilliseconds() - JavaScript
return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date.
Date.prototype.setTime() - JavaScript
return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date (effectively, the value of the argument).
Date.prototype.setUTCDate() - JavaScript
return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date.
Date.prototype.setUTCMilliseconds() - JavaScript
return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date.
Date.prototype.setYear() - JavaScript
return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date.
Error() constructor - JavaScript
examples function call or new construction when error is used like a function -- without new, it will return an error object.
Error.prototype.fileName - JavaScript
if called from a debugger context, the firefox developer tools for example, "debugger eval code" is returned.
Error.prototype.name - JavaScript
examples throwing a custom error var e = new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would return 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification.
FinalizationRegistry.prototype.register() - JavaScript
return value undefined.
FinalizationRegistry.prototype.unregister() - JavaScript
return value undefined.
Function() constructor - JavaScript
// example can be run directly in your javascript console // create a function that takes two arguments, and returns the sum of those arguments const adder = new function('a', 'b', 'return a + b'); // call the function adder(2, 6); // 8 the arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".
Function.prototype.call() - JavaScript
return value the result of calling the function with the specified this value and arguments.
Function.name - JavaScript
examples function statement name the name property returns the name of a function statement.
InternalError - JavaScript
function loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // 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) return; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion for more information, see internalerror: too much recursion.
Intl.Collator.prototype.compare() - JavaScript
description the compare getter function returns a number indicating how string1 and string2 compare to each other according to the sort order of this collator object: a negative value if string1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal.
Intl.DateTimeFormat.prototype.format() - JavaScript
(2012, 08), new date(2012, 11), new date(2012, 03)]; var options = { year: 'numeric', month: 'long' }; var datetimeformat = new intl.datetimeformat('pt-br', options); var formatted = a.map(datetimeformat.format); console.log(formatted.join('; ')); // → "setembro de 2012; dezembro de 2012; abril de 2012" avoid comparing formatted date values to static values most of the time, the formatting returned by format() is consistent.
Intl.DisplayNames() constructor - JavaScript
"code" "none" examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Intl.Locale.prototype.caseFirst - JavaScript
the intl.locale.prototype.casefirst property is an accessor property that returns whether case is taken into account for the locale's collation rules.
Intl.Locale.prototype.collation - JavaScript
the intl.locale.prototype.collation property is an accessor property that returns the collation type for the locale, which is used to order strings according to the locale's rules.
Intl.Locale.prototype.hourCycle - JavaScript
the intl.locale.prototype.hourcycle property is an accessor property that returns the time keeping format convention used by the locale.
Intl.Locale.prototype.minimize() - JavaScript
syntax locale.minimize() return value a locale instance whose basename property returns the result of the remove likely subtags algorithm executed against locale.basename.
Intl.Locale.prototype.numberingSystem - JavaScript
the intl.locale.prototype.numberingsystem property is an accessor property that returns the numeral system used by the locale.
Intl.Locale.prototype.numeric - JavaScript
the intl.locale.prototype.numeric property is an accessor property that returns whether the locale has special collation handling for numeric characters.
Intl.Locale.prototype.region - JavaScript
the intl.locale.prototype.region property is an accessor property that returns the region of the world (usually a country) associated with the locale.
Intl.Locale.prototype.script - JavaScript
the intl.locale.prototype.script property is an accessor property which returns the script used for writing the particular language used in the locale.
Intl.PluralRules() constructor - JavaScript
examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Intl.RelativeTimeFormat.prototype.format() - JavaScript
description the function returned by the format getter formats a value and a unit into a string according to the locale and formatting options of this intl.relativetimeformat object.
Intl - JavaScript
static methods intl.getcanonicallocales() returns canonical locale names.
Map.prototype[@@iterator]() - JavaScript
syntax mymap[symbol.iterator] return value the map iterator function, which is the entries() function by default.
Map.prototype.clear() - JavaScript
syntax mymap.clear(); return value undefined.
Map.prototype.size - JavaScript
the size accessor property returns the number of elements in a map object.
Math.E - JavaScript
examples using math.e the following function returns e: function getnapier() { return math.e; } getnapier(); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.e' in that specification.
Math.LN10 - JavaScript
examples using math.ln10 the following function returns the natural log of 10: function getnatlog10() { return math.ln10; } getnatlog10(); // 2.302585092994046 specifications specification ecmascript (ecma-262)the definition of 'math.ln10' in that specification.
Math.LN2 - JavaScript
examples using math.ln2 the following function returns the natural log of 2: function getnatlog2() { return math.ln2; } getnatlog2(); // 0.6931471805599453 specifications specification ecmascript (ecma-262)the definition of 'math.ln2' in that specification.
Math.LOG10E - JavaScript
examples using math.log10e the following function returns the base 10 logarithm of e: function getlog10e() { return math.log10e; } getlog10e(); // 0.4342944819032518 specifications specification ecmascript (ecma-262)the definition of 'math.log10e' in that specification.
Math.LOG2E - JavaScript
examples using math.log2e the following function returns the base 2 logarithm of e: function getlog2e() { return math.log2e; } getlog2e(); // 1.4426950408889634 specifications specification ecmascript (ecma-262)the definition of 'math.log2e' in that specification.
Math.PI - JavaScript
function calculatecircumference(radius) { return math.pi * (radius + radius); } calculatecircumference(1); // 6.283185307179586 specifications specification ecmascript (ecma-262)the definition of 'math.pi' in that specification.
Math.SQRT1_2 - JavaScript
examples using math.sqrt1_2 the following function returns 1 over the square root of 2: function getroot1_2() { return math.sqrt1_2; } getroot1_2(); // 0.7071067811865476 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt1_2' in that specification.
Math.SQRT2 - JavaScript
examples using math.sqrt2 the following function returns the square root of 2: function getroot2() { return math.sqrt2; } getroot2(); // 1.4142135623730951 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt2' in that specification.
Number.MAX_SAFE_INTEGER - JavaScript
polyfill if (!number.max_safe_integer) { number.max_safe_integer = 9007199254740991; // math.pow(2, 53) - 1; } examples return value of max_safe_integer number.max_safe_integer; // 9007199254740991 numbers higher than safe integer this returns 2 because in floating points, the value is actually the decimal trailing "1" except for in subnormal precision cases such as zero.
Number.NaN - JavaScript
property attributes of number.nan writable no enumerable no configurable no examples checking whether values are numeric function sanitise(x) { if (isnan(x)) { return number.nan; } return x; } testing against nan see testing against nan on the nan page.
Object.prototype.__defineSetter__() - JavaScript
return value undefined.
Object.prototype.isPrototypeOf() - JavaScript
return value a boolean indicating whether the calling object lies in the prototype chain of the specified object.
Object.prototype.__proto__ - JavaScript
(that is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the instance was created.) the __proto__ setter allows the [[prototype]] of an object to be mutated.
Reflect.apply() - JavaScript
return value the result of calling the given target function with the specified this value and arguments.
Reflect.construct() - JavaScript
return value a new instance of target (or newtarget, if present), initialized by target as a constructor with the given argumentslist.
Reflect.isExtensible() - JavaScript
return value a boolean indicating whether or not the target is extensible.
Reflect.preventExtensions() - JavaScript
return value a boolean indicating whether or not the target was successfully set to prevent extensions.
Reflect.set() - JavaScript
return value a boolean indicating whether or not setting the property was successful.
RegExp.prototype.dotAll - JavaScript
the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp).
RegExp.$1-$9 - JavaScript
you can access all parenthesized substrings through the returned array's indexes.
Set.prototype[@@iterator]() - JavaScript
syntax myset[symbol.iterator] return value the set iterator function, which is the values() function by default.
Set() constructor - JavaScript
return value a new set object.
Set.prototype.add() - JavaScript
return value the set object.
Set.prototype.clear() - JavaScript
syntax myset.clear(); return value undefined.
Set.prototype.size - JavaScript
the size accessor property returns the number of (unique) elements in a set object.
Planned changes to shared memory - JavaScript
to avoid having to check whether postmessage() throws, self.crossoriginisolated is being standardized (a getter that returns a boolean; true if the headers are set), available in window and worker contexts.
SharedArrayBuffer() constructor - JavaScript
return value a new sharedarraybuffer object of the specified size.
SharedArrayBuffer - JavaScript
instance methods sharedarraybuffer.prototype.slice(begin, end) returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive.
String.prototype.anchor() - JavaScript
return value a string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag description don't use this method.
String.prototype.big() - JavaScript
syntax str.big() return value a string containing a <big> html element.
String.prototype.blink() - JavaScript
syntax str.blink() return value a string containing a <blink> html element.
String.prototype.bold() - JavaScript
syntax str.bold() return value a string containing a <b> html element.
String.prototype.fixed() - JavaScript
syntax str.fixed() return value a string representing a <tt> html element.
String.prototype.fontcolor() - JavaScript
return value a string containing a <font> html element.
String.prototype.fontsize() - JavaScript
return value a string containing a <font> html element.
String.prototype.italics() - JavaScript
syntax str.italics() return value a string containing a <i> html element.
String.raw() - JavaScript
return value the raw string form of a given template string.
String.prototype.small() - JavaScript
syntax str.small() return value a string containing a <small> html element.
String.prototype.strike() - JavaScript
syntax str.strike() return value a string containing a <strike> html element.
String.prototype.sub() - JavaScript
syntax str.sub() return value a string containing a <sub> html element.
String.prototype.sup() - JavaScript
syntax str.sup() return value a string containing a <sup> html element.
Symbol() constructor - JavaScript
the symbol() constructor returns a value of type symbol, but is incomplete as a constructor because it does not support the syntax "new symbol()" and it is not intended to be subclassed.
Symbol.prototype.description - JavaScript
the read-only description property is a string returning the optional description of symbol objects.
Symbol.hasInstance - JavaScript
property attributes of symbol.hasinstance writable no enumerable no configurable no examples custom instanceof behavior you could implement your custom instanceof behavior like this, for example: class myarray { static [symbol.hasinstance](instance) { return array.isarray(instance) } } console.log([] instanceof myarray); // true function myarray() { } object.defineproperty(myarray, symbol.hasinstance, { value: function(instance) { return array.isarray(instance); } }); console.log([] instanceof myarray); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.hasinstance' in that specification.
Symbol.keyFor() - JavaScript
return value a string representing the key for the given symbol if one is found on the global registry; otherwise, undefined.
Symbol.replace - JavaScript
property attributes of symbol.replace writable no enumerable no configurable no examples using symbol.replace class customreplacer { constructor(value) { this.value = value; } [symbol.replace](string) { return string.replace(this.value, '#!@?'); } } console.log('football'.replace(new customreplacer('foo'))); // expected output: "#!@?tball" specifications specification ecmascript (ecma-262)the definition of 'symbol.replace' in that specification.
Symbol.split - JavaScript
property attributes of symbol.split writable no enumerable no configurable no examples custom reverse split class reversesplit { [symbol.split](string) { const array = string.split(' '); return array.reverse(); } } console.log('another one bites the dust'.split(new reversesplit())); // expected output: [ "dust", "the", "bites", "one", "another" ] specifications specification ecmascript (ecma-262)the definition of 'symbol.split' in that specification.
Symbol.toPrimitive - JavaScript
var obj2 = { [symbol.toprimitive](hint) { if (hint == 'number') { return 10; } if (hint == 'string') { return 'hello'; } return true; } }; console.log(+obj2); // 10 -- hint is "number" console.log(`${obj2}`); // "hello" -- hint is "string" console.log(obj2 + ''); // "true" -- hint is "default" specifications specification ecmascript (ecma-262)the definition of 'symbol.toprimitive' in that specification.
TypedArray.prototype[@@iterator]() - JavaScript
syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default.
TypedArray.prototype.byteLength - JavaScript
if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned.
TypedArray.prototype.copyWithin() - JavaScript
return value the modified array.
TypedArray.prototype.fill() - JavaScript
return value the modified array.
TypedArray.prototype.join() - JavaScript
return value a string with all array elements joined.
TypedArray.prototype.length - JavaScript
if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned.
TypedArray.of() - JavaScript
return value a new typedarray instance.
TypedArray.prototype.reverse() - JavaScript
syntax typedarray.reverse(); return value the reversed array.
WeakMap.prototype.set() - JavaScript
return value the weakmap object.
WeakSet.prototype.add() - JavaScript
return value the weakset object.
WebAssembly.CompileError() constructor - JavaScript
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); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.Global() constructor - JavaScript
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 returns the new value).
WebAssembly.Instance.prototype.exports - JavaScript
the exports readonly property of the webassembly.instance object prototype returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript.
WebAssembly.Instance - JavaScript
instance properties instance.prototype.exports returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript.
WebAssembly.LinkError() constructor - JavaScript
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); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that specification.
WebAssembly.Memory.prototype.buffer - JavaScript
the buffer prototype property of the webassembly.memory object returns the buffer contained in the memory.
WebAssembly.Module() constructor - JavaScript
examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specif...
WebAssembly.RuntimeError() constructor - JavaScript
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); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly.runtimeerror constructor' in that specification.
WebAssembly.Table() constructor - JavaScript
the table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation).
WebAssembly.Table.prototype.get() - JavaScript
return value a function reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function.
WebAssembly.Table.prototype.grow() - JavaScript
return value the previous length of the table.
WebAssembly.Table.prototype.length - JavaScript
the length prototype property of the webassembly.table object returns the length of the table, i.e.
WebAssembly.compile() - JavaScript
return value a promise that resolves to a webassembly.module object representing the compiled module.
WebAssembly.compileStreaming() - JavaScript
return value a promise that resolves to a webassembly.module object representing the compiled module.
decodeURI() - JavaScript
return value a new string representing the unencoded version of the given encoded uniform resource identifier (uri).
escape() - JavaScript
return value a new string in which certain characters have been escaped.
unescape() - JavaScript
return value a new string in which certain characters have been unescaped.
Bitwise AND (&) - JavaScript
the bitwise and operator (&) returns a 1 in each bit position for which the corresponding bits of both operands are 1s.
Bitwise OR (|) - JavaScript
the bitwise or operator (|) returns a 1 in each bit position for which the corresponding bits of either or both operands are 1s.
Bitwise XOR (^) - JavaScript
the bitwise xor operator (^) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s.
Exponentiation (**) - JavaScript
the exponentiation operator (**) returns the result of raising the first operand to the power of the second operand.
Greater than (>) - JavaScript
the greater than operator (>) returns true if the left operand is greater than the right operand, and false otherwise.
Greater than or equal (>=) - JavaScript
the greater than or equal operator (>=) returns true if the left operand is greater than or equal to the right operand, and false otherwise.
Inequality (!=) - JavaScript
the inequality operator (!=) checks whether its two operands are not equal, returning a boolean result.
Less than or equal (<=) - JavaScript
the less than or equal operator (<=) returns true if the left operand is less than or equal to 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; return 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 (%) returns 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 () { return constructor.apply(this, args); }; if (typeof constructor.prototype === "object") { partial.prototype = object.create(constructor.prototype); } return 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...
Strict inequality (!==) - JavaScript
the strict inequality operator (!==) checks whether its two operands are not equal, returning a boolean result.
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){ return 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 returns a reference to the constructor or function.
import.meta - JavaScript
console.log(import.meta); // { url: "file:///home/user/my-module.js" } it returns 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() { return this.someproperty; }; thing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing = new thing(); console.log(thing); // thing {someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variables can be created with var, but thos...
Statements and declarations - JavaScript
return specifies the value to be returned by a function.
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 return class iterations do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript expressions and operators.
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 return 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); return 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.
Media container formats (file types) - Web media technologies
it's based entirely on free and open technologies and primarily uses codecs that are in turn free and open, although some products support other codecs in webm containers as well.
Optimizing startup performance - Web Performance
if you need to decode asset files (for example, decoding jpeg files and turning them into raw texture data for later use by webgl), that's great to do in workers.
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 return.
Introduction to progressive web apps - Progressive web apps (PWAs)
presenting a trusted website with a good performance is a consequence of using these enhancements; this in turn means building web apps which follow better practices.
Media - Progressive web apps (PWAs)
make the headings turn blue when the mouse pointer is over them.
class - SVG: Scalable Vector Graphics
WebSVGAttributeclass
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 return" (u+000d), and "form-feed" (u+000c).
d - SVG: Scalable Vector Graphics
WebSVGAttributed
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.
text-decoration - SVG: Scalable Vector Graphics
candidate recommendation mainly refers to the definition in css text decoration 3 turning the property into a shorthand for text-decoration-line and text-decoration-style.
text-rendering - SVG: Scalable Vector Graphics
this option will sometimes cause some user agents to turn off text anti-aliasing.
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 return" (u+000d), and "form-feed" (u+000c).
<feComponentTransfer> - SVG: Scalable Vector Graphics
the colors are modified by changing each channel (r, g, b, and a) to the result of what the children <fefuncr>, <fefuncb>, <fefuncg>, and <fefunca> return.
<script> - SVG: Scalable Vector Graphics
WebSVGElementscript
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') return `#${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
WebSVGScripting
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 returns the xmldocument representing the element's embedded svg or null if the element doesn't represent an svg document.
SVG and CSS - SVG: Scalable Vector Graphics
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.
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
it's adapted from jp fiset's comment in bug 303581 which in turn was adapted from jeff schiller's comment in bug 303581.
Certificate Transparency - Web security
implementation when certificates are submitted to a ct log, a signed certificate timestamp (sct) is generated and returned.
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 return a network error indicating that fetching of that script or stylesheet failed.
Transport Layer Security - Web security
from version 74 onwards, firefox will return a secure connection failed error when connecting to servers using the older tls versions (bug 1606734).
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 returns null.
string - XPath
returns a string notes if the object is a node-set, the string value of the first node in the set is returned.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
xsltprocessor.transformtodocument() returns a full xml document while xsltprocessor.transformtofragment() returns a document fragment that can be easily added to an existing document.
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, // return type null, // argument types null // arguments ); }); this illustrates how ccall() is used to call the exported function.
WebAssembly Concepts - WebAssembly
it’s very easy to modify the emscripten output and turn it into whatever web app you require.
Compiling from Rust to WebAssembly - WebAssembly
it has three main parts; let's talk about them in turn.
WebAssembly
webassembly.instantiatestreaming() the webassembly.instantiatestreaming() function is the primary api for compiling and instantiating webassembly code, returning both a module and its first instance.