Search completed in 1.67 seconds.
JSVAL_TRUE
jsval constants that represent the javascript values
true and false.
... syntax jsval_
true jsval_false description jsval_
true and jsval_false are jsval constants that represent the javascript boolean values,
true and false.
... they are equivalent to boolean_to_jsval(
true) and boolean_to_jsval(false), respectively.
...And 3 more matches
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
reason reason: expected ‘
true’ in cors header ‘access-control-allow-credentials’ what went wrong?
... the cors request requires that the server permit the use of credentials, but the server's access-control-allow-credentials header's value isn't set to
true to enable their use.
... if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to
true.
... to eliminate this error by changing the server's configuration, adjust the server's configuration to set the access-control-allow-credentials header's value to
true.
JS::TrueHandleValue
this article covers features introduced in spidermonkey 38 the js::value that represents the javascript value
true.
... syntax const js::handlevalue js::
truehandlevalue; const js::handlevalue js::falsehandlevalue; description js::
truehandlevalue and js::falsehandlevalue are js::handlevalue constants that represent the javascript values
true and false.
... see also mxr id search for js::
truehandlevalue mxr id search for js::falsehandlevalue js::nullhandlevalue js::undefinedhandlevalue bug 959787 ...
JS::TrueValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value
true.
... syntax js::value js::
truevalue() description js::
truevalue creates a js::value that represents the javascript value
true.
... see also mxr id search for js::
truevalue js::value js::booleanvalue js::falsevalue ...
NS ENSURE TRUE
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; } ...
true - XPath
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.
Index - Web APIs
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.
...this property is only used if the loop property is
true.
...And 125 more matches
Index
if so, int_fits_in_jsval returns
true, and i can be cast to jsval by calling int_to_jsval(i).
... 61 js::propertyspecnameequalsid jsapi reference, reference, référence(2), spidermonkey js::propertyspecnameequalsid determines if the given jspropertyspec::name or jsfunctionspec::name value equals the given jsid, and returns
true if so.
... 62 js::propertyspecnameissymbol jsapi reference, reference, référence(2), spidermonkey 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.
...And 65 more matches
jspage - Archive of obsolete content
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","substring","tolowercase","touppercase","val...
...ueof"]}; 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=new array(a);while(a--){c[a]=b[a];}return...
...ndow.activexobject)?false:((window.xmlhttprequest)?((document.queryselectorall)?6:5):4);},webkit:function(){return(navigator.taintenabled)?false:((browser.features.xpath)?((browser.features.query)?525:420):419); },gecko:function(){return(!document.getboxobjectfor&&window.mozinnerscreenx==null)?false:((document.getelementsbyclassname)?19:18);}}},browser||{});browser.platform[browser.platform.name]=
true; browser.detect=function(){for(var b in this.engines){var a=this.engines[b]();if(a){this.engine={name:b,version:a};this.engine[b]=this.engine[b+a]=
true; break;}}return{name:b,version:a};};browser.detect();browser.request=function(){return $try(function(){return new xmlhttprequest();},function(){return new activexobject("msxml2.xmlhttp"); },function(){return new activexobject("microsoft.xmlhttp");...
...And 38 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
alwaysopenpopup obsolete since gecko 1.9.1 type: boolean note: applies to: thunderbird and seamonkeyif
true, the autocomplete popup will be displayed even when there are no matches.
... autofill obsolete since gecko 1.9.1 type: boolean note: applies to: thunderbird and seamonkeyif set to
true, the best match will be filled into the textbox as the user types.
... autofillaftermatch obsolete since gecko 1.9.1 type: boolean if set to
true, the entire text of the best match will be displayed at the end of the input.
...And 30 more matches
lang/type - Archive of obsolete content
globals functions isundefined(value) returns
true if value is undefined, false otherwise.
... let { isundefined } = require('sdk/lang/type'); var foo; isundefined(foo); //
true isundefined(0); // false parameters value : mixed the variable to check.
... isnull(value) returns
true if value is null, false otherwise.
...And 27 more matches
nsIDOMWindowUtils
true if it's open, otherwise false.
... ismozafterpaintpending boolean returns
true if a mozafterpaint event has been queued but not yet fired.
... paintingsuppressed boolean
true if painting is currently suppressed for this window; otherwise false.
...And 26 more matches
Color picker tool - CSS: Cascading Style Sheets
le */ .resize-handle { width: 10px; height: 10px; background: url('https://mdn.mozillademos.org/files/6083/resize.png') center center no-repeat; position: absolute; bottom: 0; right: 0; } [data-resize='both']:hover { cursor: nw-resize !important; } [data-resize='width']:hover { cursor: w-resize !important; } [data-resize='height']:hover { cursor: n-resize !important; } [data-hidden='
true'] { display: none; } [data-collapsed='
true'] { height: 0 !important; } .block { display: table; } /** * container */ #container { width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; display: table; } /** * picker zone */ #picker { padding: 10px; width: 980px; } .ui-color-picker { padding: 3px 5px; float: left; border-color:...
... 30px; overflow: hidden; position: relative; float: left; transition: all 0.2s; } #picker-samples .sample { width: 40px; height: 40px; margin: 5px; border: 1px solid #ddd; position: absolute; float: left; transition: all 0.2s; } #picker-samples .sample:hover { cursor: pointer; border-color: #bbb; transform: scale(1.15); border-radius: 3px; } #picker-samples .sample[data-active='
true'] { border-color: #999; } #picker-samples .sample[data-active='
true']:after { content: ""; position: absolute; background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat; width: 100%; height: 12px; top: -12px; z-index: 2; } #picker-samples #add-icon { width: 100%; height: 100%; position: relative; box-shadow: inset 0px 0px 2px 0px #ddd; } #picker-samples ...
...r: 1px solid #ddd; display: table; float: left; } #controls .icon:hover { cursor: pointer; } #controls .picker-icon { background-image: url('https://mdn.mozillademos.org/files/6081/picker.png'); } #controls #void-sample { margin-right: 10px; background-image: url('https://mdn.mozillademos.org/files/6087/void.png'); background-position: center left; } #controls #void-sample[data-active='
true'] { border-color: #ccc; background-position: center right; } #controls .switch { width: 106px; padding: 1px; border: 1px solid #ccc; font-size: 14px; text-align: center; line-height: 24px; overflow: hidden; float: left; } #controls .switch:hover { cursor: pointer; } #controls .switch > * { width: 50%; padding: 2px 0; background-color: #eee; float: left; } #controls .switch [dat...
...And 26 more matches
Proxy Auto-Configuration (PAC) file - HTTP
description
true if and only if there is no domain name in the hostname (no dots).
... examples isplainhostname("www.mozilla.org") // false isplainhostname("www") //
true dnsdomainis() syntax dnsdomainis(host, domain) parameters host is the hostname from the url.
... description returns
true if and only if the domain of hostname matches.
...And 25 more matches
Expressions and operators - JavaScript
var foo = ['one', 'two', 'three']; // without destructuring var one = foo[0]; var two = foo[1]; var three = foo[2]; // with destructuring var [one, two, three] = foo; comparison operators a comparison operator compares its operands and returns a logical value based on whether the comparison is
true.
...the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator description examples returning
true equal (==) returns
true if the operands are equal.
... 3 == var1 "3" == var1 3 == '3' not equal (!=) returns
true if the operands are not equal.
...And 25 more matches
JXON - Archive of obsolete content
|*| 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 = 0; nitem < oxmlparent.ch...
...|*| 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) { if (oxmlparent.haschildnodes()) { var scollectedtxt = ""; for (var onode, sprop, vcontent, nitem = 0; nitem < oxmlparent.childnodes.length; nitem++)...
...which do not contain other element nodes, text nodes, cdatasection nodes or attr nodes) have the default value
true (see the code considerations).
...And 22 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
linear-gradient generator html content <div id="container"> <div id="gradient-container" data-alpha="
true"> </div> <div id="controls"> <div class="section"> <div class="title"> active point </div> <div class="property"> <div class="ui-input-slider" data-topic="point-position" data-info="position" data-unit="px" data-min="-1000" data-value="0" data-max="1000" data-sensivity="5"></div> <div id="delete-point" class="button"> delete point </div> </div> <div class="ui-color-picker" data-topic="picker"></div> </div> <div class="section"> <div class="title"> active axis </div> ...
...ding: 0 0.3em; border: 1px solid #3490d2; border-color: #208b20; background: #666; background-color: #eef1f5; color: #000; position: absolute; top: 100%; left: 0; z-index: 100; overflow: hidden; transition: all 0.3s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-dropdown-list:hover { overflow: auto; } .ui-dropdown-list[data-hidden='
true'] { height: 0 !important; opacity: 0; visibility: hidden; } .ui-dropdown[data-position='left'] .ui-dropdown-list { left: -100%; top: 0; } .ui-dropdown[data-position='right'] .ui-dropdown-list { left: 100%; top: 0; } .ui-dropdown-list > div { width: 80%; height: 1.6em; margin: 0.3em 0; padding: 0.3em 10%; line-height: 1.6em; } .ui-dropdown-list > div:hover { background: #3490d2; ...
...color:#fff; border-radius: 2px; cursor: pointer; } /* * color picker tool */ body { width: 100%; height: 100%; margin: 0 auto; font-family: "segoe ui", arial, helvetica, sans-serif; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } body[data-dragging="
true"] { } /** * resize handle */ .resize-handle { width: 10px; height: 10px; background: url("images/resize.png") center center no-repeat; position: absolute; bottom: 0; right: 0; } [data-resize='both']:hover { cursor: nw-resize !important; } [data-resize='width']:hover { cursor: w-resize !important; } [data-resize='height']:hover { cursor: n-resize !important; } /** * main container */ #container { width: 1000px; height: 100%; display: table; margin: 0 auto; }...
...And 21 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
r *dbdir, certname *subject, const char *subjectstr, const char *certreqfilename) { prbool validationfailed = pr_false; if (!subject) { pr_fprintf(pr_stderr, "%s -g -d %s -s: improperly formatted name: \"%s\"\n", progname, dbdir, subjectstr); validationfailed = pr_
true; } if (!certreqfilename) { pr_fprintf(pr_stderr, "%s -g -d %s -s %s -r: certificate request file name not found\n", progname, dbdir, subjectstr); validationfailed = pr_
true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-g -d <dbdirpath> -s <subject> -r <csr> \n"); exit(-1);...
...st char *certreqfilename, const char *issuernamestr, const char *serialnumberstr, prbool selfsign) { prbool validationfailed = pr_false; if (!nicknamestr) { pr_fprintf(pr_stderr, "%s -a -d %s -n : nick name is missing\n", progname, dbdir); validationfailed = pr_
true; } if (!truststr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t: trust flag is missing\n", progname, dbdir, nicknamestr); validationfailed = pr_
true; } if (!certfilename) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c: certificate file name not found\n", progname, dbdir, nicknamestr, truststr, serialnumber...
...str, certreqfilename); validationfailed = pr_
true; } if (pr_access(certfilename, pr_access_exists) == pr_failure) { if (!certreqfilename) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c %s -r: certificate file or certificate request file is not found\n", progname, dbdir, nicknamestr, truststr, certfilename); validationfailed = pr_
true; } if (!selfsign && !issuernamestr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c %s -r %s -u : issuer name is missing\n", progname, dbdir, nicknamestr, truststr, certfilename, certreqfilename); validationfailed = pr_
true; } if (!serialnumberstr) { pr_fprintf(pr_stderr, "%s -a -d...
...And 20 more matches
sslfnc.html
an application that wishes to do sumultaneous reads and writes should set this to pr_
true.
...if set to pr_
true, it will; otherwise, it will not.
... factory setting is on (pr_
true).
...And 20 more matches
Box-shadow generator - CSS: Cascading Style Sheets
</div> </div> <div id="element_properties" class="category"> <div class="title"> class element properties </div> <div class="group"> <div class="group property"> <div class="ui-slider-name"> border </div> <div class="ui-checkbox" data-topic='border-state' data-state="
true"></div> </div> <div id="z-index" class="slidergroup"> <div class="ui-slider-name"> z-index </div> <div class="ui-slider-btn-set" data-topic="z-index" data-type="sub"></div> <div class="ui-slider" data-topic="z-index" data-min="-10" data-max="10" data-step="1"...
...ition: absolute; top: 2px; } #output .button { width: 90px; height: 22px; margin: 0 5px 0 0; text-align: center; line-height: 20px; font-size: 14px; color: #fff; background-color: #999; border-top-left-radius: 3px; border-top-right-radius: 3px; bottom: -5px; float:left; } #output .button:hover { color: #fff; background-color: #666; cursor: pointer; } #output .menu [data-active="
true"] { color: #777; background-color: #fff; border: 1px solid #ccc; border-bottom: none; } #output .menu [data-topic="before"] { left: 100px; } #output .menu [data-topic="after"] { left: 200px; } #output .output { width: 480px; margin: 10px; padding: 10px; overflow: hidden; color: #555; font-size: 14px; border: 1px dashed #ccc; border-radius: 3px; display: none; -moz-box-sizing: ...
...value : (min + max) / 2 | 0; this.snap = snap === "
true" ?
...And 20 more matches
Making decisions in your code — conditionals - Learn web development
else syntax basic if...else syntax looks like the following in pseudocode: if (condition) { code to run if condition is
true } else { run some other code instead } here we've got: the keyword if followed by some parentheses.
...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.
...And 19 more matches
Shell global objects
srunonce use the isrunonce compiler option (default: false) noscriptrval use the no-script-rval compiler option (default: false) filename filename for error messages 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.
... sourceislazy if present and
true, indicates that, after compilation, script source should not be cached by the js engine and should be lazily loaded from the embedding as-needed.
... loadbytecode if
true, and if the source is a cacheentryobject, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual.
...And 19 more matches
Client-side form validation - Learn web development
when an element is valid, the following things are
true: the element matches the :valid css pseudo-class, which lets you apply a specific style to valid elements.
... when an element is invalid, the following things are
true: the element matches the :invalid css pseudo-class, and sometimes other ui pseudo-classes (e.g., :out-of-range) depending on the error, which lets you apply a specific style to invalid elements.
...you can find full details of all the available properties in the validitystate reference page; below is listed a few of the more common ones: patternmismatch: returns
true if the value does not match the specified pattern, and false if it does match.
...And 18 more matches
sample2
1); } /* * validate the options used for generate csr command */ static void validategeneratecsrcommand(const char *progname, const char *dbdir, certname *subject, const char *subjectstr, const char *certreqfilename) { prbool validationfailed = pr_false; if (!subject) { pr_fprintf(pr_stderr, "%s -g -d %s -s: improperly formatted name: \"%s\"\n", progname, dbdir, subjectstr); validationfailed = pr_
true; } if (!certreqfilename) { pr_fprintf(pr_stderr, "%s -g -d %s -s %s -r: certificate request file name not found\n", progname, dbdir, subjectstr); validationfailed = pr_
true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-g -d <dbdirpath> -s <subject> -r <csr> \n"); exit(-1); } } /* * validate the options used for add cert to db command */ static void validateaddcertt...
...odbcommand(const char *progname, const char *dbdir, const char *nicknamestr, const char *truststr, const char *certfilename, const char *certreqfilename, const char *issuernamestr, const char *serialnumberstr, prbool selfsign) { prbool validationfailed = pr_false; if (!nicknamestr) { pr_fprintf(pr_stderr, "%s -a -d %s -n : nick name is missing\n", progname, dbdir); validationfailed = pr_
true; } if (!truststr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t: trust flag is missing\n", progname, dbdir, nicknamestr); validationfailed = pr_
true; } if (!certfilename) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c: certificate file name not found\n", progname, dbdir, nicknamestr, truststr, serialnumberstr, certreqfilename); validationfailed = pr_
true; } if (pr_access(certfilename, pr_access_exists...
...) == pr_failure) { if (!certreqfilename) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c %s -r: certificate file or certificate request file is not found\n", progname, dbdir, nicknamestr, truststr, certfilename); validationfailed = pr_
true; } if (!selfsign && !issuernamestr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c %s -r %s -u : issuer name is missing\n", progname, dbdir, nicknamestr, truststr, certfilename, certreqfilename); validationfailed = pr_
true; } if (!serialnumberstr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c %s -r %s -u %s -m : serial number is missing\n", progname, dbdir, nicknamestr, truststr, certfilename, certreqfilename, issuernamestr); validationfailed = pr_
true; } } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, " -a -d <dbdir...
...And 18 more matches
ValidityState - Web APIs
properties for each of these boolean properties, a value of
true indicates that the specified reason validation may have failed is
true, with the exception of the valid property, which is
true if the element's value obeys all constraints.
... badinput read only a boolean that is
true if the user has provided input that the browser is unable to convert.
... patternmismatch read only a boolean that is
true if the value does not match the specified pattern, and false if it does match.
...And 18 more matches
JavaScript Daemons Management - Archive of obsolete content
wner = daemon.context; daemon.prototype.task = null; daemon.prototype.rate = 100; daemon.prototype.length = infinity; daemon.prototype.reversals = 0; daemon.prototype.onstart = null; daemon.prototype.onstop = null; /* these properties should be read-only after the creation of the daemon */ daemon.prototype.session = -1; daemon.prototype.index = 0; daemon.prototype.paused =
true; daemon.prototype.backw =
true; /* system required daemon global object methods */ daemon.forcecall = function (odmn) { odmn.index += odmn.backw ?
... -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).
...isfinite(this.length) && this.index < 1 : this.index + 1 > this.length; }; daemon.prototype.synchronize = function () { if (this.paused) { return; } clearinterval(this.session); this.session = setinterval(daemon.forcecall, this.rate, this); }; daemon.prototype.pause = function () { clearinterval(this.session); this.paused =
true; }; /* system not required daemon instances methods */ /** * basic user interface.
...And 17 more matches
CustomizableUI.jsm
when a customizable toolbar's xbl binding is constructed (generally, that is when a <toolbar customizable="
true"/> node is appended to the document and isn't invisible), the binding will call into customizableui and register the toolbar's node as being one of the concrete instances of its area.
...in order to register such a toolbar, set the 'overflowable' property to
true, and provide the id of the anchor in the 'anchor' property.
...anode is the dom node changed, anextnode the dom node (if any) before which a widget will be inserted, acontainer the actual dom container (could be an overflow panel in case of an overflowable toolbar), and awasremoval is
true iff the action about to happen is the removal of the dom node.
...And 17 more matches
OS.File for the main thread
y exists: 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", nooverwrite:
true}); // buffer "file.txt.tmp".
... example: rename a file you have to use os.file.move to rename a file: let promise = os.file.move("oldname.txt", "newname.txt", {nooverwrite:
true}); here's a working example which renames test.txt to testrenamed.txt if the file is located in directory c:\jean\ var promise = os.file.move(os.path.join('c:', 'jean', 'test.txt'), os.path.join('c:', 'jean', 'testrenamed.txt')); promise.then( function() { console.log('rename successful') }, function(arejectreason) { console.log('rename failed, arejectreason = ', arejectreason) } ) the nooverwrite
true is important, as default is false which means if a file in the directory exists already with the same name it will no longer be there after this "renam...
... return promise.resolve(
true); // loop end.
...And 17 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
completedefaultindex new in thunderbird 3 requires seamonkey 2.0 type: boolean if
true, the best match value will be filled into the textbox as the user types.
... completeselectedindex type: boolean if
true, the text in the text field will be autocompleted as the user selects from the popup list.
... disableautocomplete new in thunderbird 3requires seamonkey 2.0 type: boolean if
true, the autocomplete behavior will be disabled.
...And 16 more matches
Theme changes in Firefox 2 - Archive of obsolete content
browser.css the following styles used in firefox 1.5 themes are no longer used in firefox 2 and should be removed from your theme: #bookmarks-button:active #copy-button:active #cut-button:active #downloads-button:active #forward-button[buttondown="
true"] #history-button:active #home-button:active #mail-button #mail-button:active #mail-button[disabled="
true"] #mail-button[open="
true"] #new-tab-button:active #new-tab-button[checked="
true"] #new-window-button:active #new-window-button[checked="
true"] #paste-button:active #print-button:active #reload-button:active #stop-button:active .messagebutton .messageimage .messagetext brows...
...kmarks-button:active toolbar[iconsize="small"] #copy-button:active toolbar[iconsize="small"] #cut-button:active toolbar[iconsize="small"] #downloads-button:active toolbar[iconsize="small"] #history-button:active toolbar[iconsize="small"] #home-button:active toolbar[iconsize="small"] #mail-button toolbar[iconsize="small"] #mail-button:active toolbar[iconsize="small"] #mail-button[disabled="
true"] toolbar[iconsize="small"] #mail-button[open="
true"] toolbar[iconsize="small"] #new-tab-button:active toolbar[iconsize="small"] #new-window-button:active toolbar[iconsize="small"] #paste-button:active toolbar[iconsize="small"] #print-button:active toolbar[iconsize="small"] #reload-button:active toolbar[iconsize="small"] #stop-button:active toolbar[mode="icons"] .toolbarbutton-text toolb...
...n > .toolbarbutton-text toolbar[mode="text"] .toolbarbutton-icon the following styles need to be added to your theme to be compatible with firefox 2: #back-button .toolbarbutton-menubutton-dropmarker #back-button:hover #back-button:hover .toolbarbutton-menubutton-dropmarker #back-button:hover:active #back-button:hover:active .toolbarbutton-menubutton-dropmarker #back-button[buttondown="
true"] > .toolbarbutton-menubutton-dropmarker #back-button[buttonover="
true"] #back-button[buttonover="
true"] > .toolbarbutton-menubutton-dropmarker #back-button[disabled="
true"] .toolbarbutton-menubutton-dropmarker #back-button[open="
true"] #bookmarks-button:hover #bookmarks-button:hover:active #bookmarks-button[checked="
true"] #copy-button:hover #copy-button:hover:active #cut-button:hover ...
...And 16 more matches
nsIHTMLEditor
n astring aattribute, in astring avalue); void setdocumenttitle(in astring atitle); void setinlineproperty(in nsiatom aproperty, in astring aattribute, in astring avalue); void setparagraphformat(in astring aparagraphformat); void updatebaseurl(); attributes attribute type description iscssenabled boolean a boolean which is
true is the htmleditor has been instantiated with css knowledge and if the css pref is currently checked.
...if aiscreatedhidden is
true, the class "hidden" is added to the created element.
... void getalignment( out boolean amixed, out short aalign ); parameters amixed
true if there is more than one type of list item, or if there is some list and non-list.
...And 16 more matches
MediaTrackSupportedConstraints - Web APIs
autogaincontrol a boolean whose value is
true if the autogaincontrol constraint is supported in the current environment.
... width a boolean value whose value is
true if the width constraint is supported in the current environment.
... height a boolean value whose value is
true if the height constraint is supported in the current environment.
...And 16 more matches
source-editor.jsm
n(number astart, number aend); breakpoint management void addbreakpoint(number alineindex, [optional] string acondition); array getbreakpoints(); boolean removebreakpoint(number alineindex); properties attribute type description dirty boolean set this value to false whenever you save the text; the editor will update it to
true when the content is changed.
... ignorecase boolean
true if the search was case sensitive; otherwise false.
... readonly boolean set this value to
true to make the editor read only, thereby preventing the user from making changes.
...And 15 more matches
Image file type and format guide - Web media technologies
true color 8 and 16 each pixel is represented by three d-bit values indicating the level of the red, green, and blue color components.
...
true color with alpha 8 and 16 each pixel is comprised of four d-pixel color components: red, green, blue, and the alpha sample indicating how opaque the pixel is.
...
true color 8 and 16 each pixel is represented by three values representing the red, green, and blue color components; each is d bits.
...And 15 more matches
Bytecode Descriptions
false,
true stack: ⇒
true/false push a boolean constant.
...push
true if obj has a property with the key id.
...there's a shell-only option, newglobal({clonesingletons:
true}), that makes this instruction do a deep copy of the object.
...And 14 more matches
Places utilities for JavaScript
the all take in the same argument and return a boolean
true or false, so i'm just going to list them all in one lump: boolean nodeisfolder(anode) determines whether or not a resultnode is a bookmark folder or not.
... return type return
true if the node is a folder, false otherwise.
... parameters folderid the folder to open [optional] excludeitems
true to hide all items (individual bookmarks).
...And 13 more matches
WebIDL bindings
nullable strings are represented by the same types as non-nullable ones, but the string will return
true for domstringisnull().
... nullable utf8strings are represented by the same types as non-nullable ones, but the string will return
true for isvoid().
... nullable bytestring are represented by the same types as non-nullable ones, but the string will return
true for isvoid().
...And 13 more matches
@font-feature-values - CSS: Cascading Style Sheets
noedge no support nofirefox full support 34 full support 34 full support 24disabled disabled from version 24: this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
... nochrome android no support nofirefox android full support 34 full support 34 full support 24disabled disabled from version 24: this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
... noedge no support nofirefox full support 34 full support 34 full support 24disabled disabled from version 24: this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
...And 13 more matches
textbox - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... focused type: boolean this attribute is
true if the element is focused.
... hidespinbuttons type: boolean if
true, the number box does not have arrow buttons next to it to allow the user to adjust the value.
...And 12 more matches
nsITreeView
return value
true if a drop is allowed at the current location; otherwise false.
... before
true to test drop before.
... return value
true if a drop event can occur.
...And 12 more matches
Debugger.Object - Firefox Developer Tools
callable
true if the referent is a callable object (such as a function or a function proxy); false otherwise.
... isboundfunction if the referent is a debuggee function, returns
true if the referent is a bound function; false otherwise.
... isarrowfunction if the referent is a debuggee function, returns
true if the referent is an arrow function; false otherwise.
...And 12 more matches
BasicCardResponse - Web APIs
rtedtypes: ['credit', 'debit'] } }]; var details = { total: {label: 'donation', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected:
true } ] }; var options = {requestshipping:
true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
...ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true) and the dom.payments.request.supportedregions preference (needs to be set to a comma-delineated list of one or more 2-character iso country codes indicating the countries in which to support payments (for example, us,ca.).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true) and the dom.payments.request.supportedregions preference (needs to be set to a comma-delineated list of one or more 2-character iso country codes indicating the countries in which to support payments (for example, us,ca.).
...And 12 more matches
Border-image generator - CSS: Cascading Style Sheets
dding: 0 0.3em; border: 3px solid #3490d2; border-color: #208b20; background: #666; background-color: #eef1f5; color: #000; position: absolute; top: 2em; left: 0; z-index: 100; overflow: hidden; transition: all 0.3s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-dropdown-list:hover { overflow: auto; } .ui-dropdown-list[data-hidden='
true'] { height: 0 !important; opacity: 0; visibility: hidden; } .ui-dropdown[data-position='left'] .ui-dropdown-list { left: -100%; top: 0; } .ui-dropdown[data-position='right'] .ui-dropdown-list { left: 100%; top: 0; } .ui-dropdown-list > div { width: 100%; height: 1.6em; margin: 0.3em 0; padding: 0.3em; line-height: 1em; -moz-box-sizing: border-box; -webkit-box-sizing: border-box;...
...kit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } body[data-move='x'] { cursor: w-resize !important; } body[data-move='y'] { cursor: s-resize !important; } #container { width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } [data-draggable='
true']:hover { cursor: move; } [data-draggable='
true']:hover > * { cursor: default; } /******************************************************************************/ /******************************************************************************/ /* * border image picker */ #gallery { box-shadow: 0 0 3px 0 #bababa; } #image-gallery { width: 600px; height: 100px; margin: 0 auto; transi...
...tion: margin 0.4s; } #image-gallery .image { height: 80px; float: left; margin: 10px; opacity: 0.5; background-color: #fff; box-shadow: 0px 0px 3px 1px #bababa; } #image-gallery .image[selected="
true"] { box-shadow: 0px 0px 3px 1px #3bba52; opacity: 1; } #image-gallery .image:hover { cursor: pointer; box-shadow: 0px 0px 3px 1px #30ace5; opacity: 1; } #image-gallery[data-collapsed='
true'] { margin-top: -100px; } /* load menu */ #load-actions { margin: 10px 0; } #toggle-gallery { width: 30px; height: 25px; margin: 10px; color: #fff; background-image: url('https://mdn.mozillademos.org/files/6005/arrow-up-white.png'); background-repeat: no-repeat; background-position: top 4px center; background-color: #888888 !important; border-radius: 2px; float: left; } #toggle-g...
...And 12 more matches
Tree View Details - Archive of obsolete content
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 iscontainer method should return
true if a row is a container and might contain children.
... the iscontainerempty method should return
true if a row is an empty container, for instance, a directory with no files in it.
...And 11 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
put the following content into your moreactions.svelte file: <script> import { createeventdispatcher } from 'svelte' const dispatch = createeventdispatcher() let completed =
true const checkall = () => { dispatch('checkall', completed) completed = !completed } const removecompleted = () => dispatch('removecompleted') </script> <div class="btn-group"> <button type="button" class="btn btn__primary" on:click={checkall}>{completed ?
... you'll notice that the array is successfully updated every time you press the button (the todo objects' completed properties are toggled between
true and false), but svelte is not aware of that.
...and that makes sense, because otherwise svelte would be aware of the inner workings of the foreach() method; the same would therefore be
true for any method attached to any object or array.
...And 11 more matches
nsIPromptService
return value
true for ok, false for cancel see also the confirm_example.
... return value
true for ok, false for cancel confirmex() puts up a dialog with up to 3 buttons and an optional, labeled checkbox.
... return value
true for ok, false for cancel promptusernameandpassword() shows a dialog with an edit field, a password field, and an optional, labeled checkbox.
...And 11 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 11 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
etenv("user") != "") { // *nix settings var env_user = getenv("user"); var env_home = getenv("home"); } else { // windows settings var env_user = getenv("username"); var env_home = getenv("homepath"); } var env_mozdebug= getenv("mozilla_debug"); // var env_user = prompt("indiquez votre login", toto); // 2) lock general preferences //ldap address book lockpref("ldap_2.prefs_migrated",
true); lockpref("ldap_2.servers.ldapint.auth.savepassword",
true); lockpref("ldap_2.servers.ldapint.description", "ldap int"); lockpref("ldap_2.servers.ldapint.filename", "abook-1.mab"); lockpref("ldap_2.servers.ldapint.uri", "ldap://ldap1.int-evry.fr:389/ou=people,dc=int-evry,dc=fr??sub"); lockpref("ldap_2.servers.history.filename", "history.mab"); lockpref("ldap_2.servers.history.replication.lastcha...
...draft_folder", "imap://" + env_user + "@imap-int.int-evry.fr/drafts"); lockpref("mail.identity.id1.drafts_folder_picker_mode", "0"); lockpref("mail.identity.id1.fcc_folder", "imap://" + env_user + "@imap-int.int-evry.fr/sent"); lockpref("mail.identity.id1.fcc_folder_picker_mode", "0"); lockpref("mail.identity.id1.organization", "int evry france"); lockpref("mail.identity.id1.overrideglobal_pref",
true); lockpref("mail.identity.id1.reply_to", ""); //imap lockpref("mail.server.server2.hostname", "imap-int.int-evry.fr"); lockpref("mail.server.server2.issecure",
true); lockpref("mail.server.server2.login_at_startup",
true); lockpref("mail.server.server2.max_cached_connections", 5); //lockpref("mail.server.server2.name", "jehan.procaccia@int-evry.fr"); lockpref("mail.server.server2.type", "imap");...
... lockpref("mail.server.server2.username", env_user); //smtp lockpref("mail.identity.id1.smtpserver", "smtp1"); lockpref("mail.identity.id1.stationery_folder", "imap://" + env_user + "@imap-int.int-evry.fr/templates"); lockpref("mail.identity.id1.tmpl_folder_picker_mode", "0"); lockpref("mail.identity.id1.valid",
true); //smtp general lockpref("mail.smtp.defaultserver", "smtp1"); lockpref("mail.smtpserver.smtp1.auth_method", 0); lockpref("mail.smtpserver.smtp1.hostname", "smtp-int.int-evry.fr"); lockpref("mail.smtpserver.smtp1.port", 25); lockpref("mail.smtpserver.smtp1.try_ssl", 0); lockpref("mail.smtpserver.smtp1.username", ""); lockpref("mail.smtpservers", "smtp1"); lockpref("mail.startup.enabledmailcheckonce",
true); lockpref("mailnews.quotingprefs.version", 1); lockpref("mailnews.ui.thre...
...And 10 more matches
Browser Feature Detection - Archive of obsolete content
dom 1 html 100% 100% 100% 100% / 100% 100% / 100% dom css 1 100% 100% 100% 100% / 100% 96% / 96% dom css 2 100% 98% 67% 71% / 83% 38% / 42% test results cross reference dom core level 1 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 document.createelement()
true true true document.createdocumentfragment()
true true true document.createtextnode()
true true true document.createcomment()
true true true document.createcd...
...atasection()
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 document.createelement()
true true true document.createdocumentfragment()
true true true docu...
...ment.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
true false false document.getelementsbytagname()
true true true document.importnode()
true false
true document.createelementns()
true false
true document.createattributens()
true false
true document.getelementsbytagnamens()
true false
true document.getelementbyid()
true true true dom level 1 html support for pr...
...And 10 more matches
nsIFile
return value
true if infile is a descendant of this nsifile.
... return value
true if "infile" is equivalent to this nsifile.
... return value
true if the file or directory exists.
...And 10 more matches
tab - Archive of obsolete content
afterselected type: boolean this is set to
true if the tab is immediately after the currently selected tab.
... beforeselected type: boolean this is set to
true if the tab is immediately before the currently selected tab.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
...And 9 more matches
tree - Archive of obsolete content
eeitem> <treerow> <treecell label="mel@whereever.com"/> <treecell label="let's do lunch"/> </treerow> </treeitem> </treechildren> </tree> a tree with several columns and nested items <tree id="mytree" flex="1" hidecolumnpicker="false" seltype="single" class="tree" rows="5"> <treecols id="mytree2-treecols"> <treecol id="mytree2-treecol0" primary="
true" flex="2" label="column a" persist="width" ordinal="1"/> <splitter class="tree-splitter" ordinal="2"/> <treecol id="mytree2-treecol1" flex="1" label="column b" persist="width" ordinal="3"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="1"/> <treecell label="a"/> </treerow> </treeitem> <!-- make sure t...
...o set container="
true" --> <treeitem container="
true" open="
true"> <treerow> <treecell label="2"/> <treecell label="b"/> </treerow> <treechildren> <treeitem> <treerow> <treecell label="2a"/> <treecell label="ba"/> </treerow> </treeitem> </treechildren> </treeitem> </treechildren> </tree> attributes disabled type: boolean indicates whether the element is disabled or not.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
...And 9 more matches
Enc Dec MAC Output Public Key as CSR
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 (!ke...
...(type, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(type, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_
true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop return...
... this may take a few moments...\n\n"); privkey = pk11_generatekeypair(slot, mechanism, params, pubkeyp, pr_
true /*isperm*/, pr_
true /*issensitive*/, pwdata); cleanup: return privkey; } /* * extract the public key request from csr */ seckeypublickey * extractpublickeyfromcertrequest(const char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsucces...
...And 9 more matches
Encrypt Decrypt_MAC_Using Token
*/ 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.
...&ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_
true); } return ctx; } /* * common encryption and decryption code.
...And 9 more matches
nsIDocShell
defaults to
true.
...default is
true, which lets content control the window.
...docshells are active if this is
true, which is the default state.
...And 9 more matches
EventTarget.addEventListener() - Web APIs
if
true, the listener would be automatically removed when invoked.
... passive a boolean that, if
true, indicates that the function specified by listener will never call preventdefault().
...if
true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and
true for regular web pages).
...And 9 more matches
Control flow and error handling - JavaScript
conditional statements a conditional statement is a set of commands that executes if a specified condition is
true.
... if...else statement use the if statement to execute a statement if a logical condition is
true.
... an if statement looks like this: if (condition) { statement_1; } else { statement_2; } here, the condition can be any expression that evaluates to
true or false.
...And 9 more matches
<mo> - MathML
allowed values are
true or false.
... allowed values are
true or false.
... largeop specifies whether the operator should be drawn larger than normal when displaystyle="
true" is set.
...And 9 more matches
preference - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... instantapply type: boolean if
true, the preference will be changed as soon as the user interface is modified.
... inverted type: boolean for boolean preferences, if this attribute is set to
true, it indicates that the value of the preference is the reverse of the user interface element attached to it.
...And 8 more matches
treecol - Archive of obsolete content
<tree flex="1" editable="
true"> <treecols> <treecol label="active" type="checkbox" editable="
true"/> <treecol label="name" flex="1" /> </treecols> <treechildren> <treeitem> <treerow> <treecell value="
true"/> <treecell label="alice"/> </treerow> </treeitem> <treeitem> <treerow> <treecell value="false"/> <treecell label="bob"/> </treerow> </...
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } cycler type: boolean if
true, then the column is a cycler column.
... dragging type: boolean this attribute will be set to
true if the column is being dragged.
...And 8 more matches
WAI-ARIA basics - Learn web development
as an example, aria-required="
true" specifies that a form input needs to be filled in to be valid, whereas aria-labelledby="label" allows you to put an id on an element, then reference it as being the label for anything else on the page, including multiple elements, which is not possible using <label for="input">.
... states — special properties that define the current conditions of elements, such as aria-disabled="
true", which specifies to a screenreader that a form input is currently disabled.
...update your <section> tag again, like so: <section aria-live="assertive" aria-atomic="
true"> the aria-atomic="
true" attribute tells screenreaders to read out the entire element contents as one atomic unit, not just the bits that were updated.
...And 8 more matches
Displaying Places information using views
<tree type="places" place="place:terms=mozilla&onlybookmarked=1&querytype=1"> <treecols> <treecol id="title" label="my bookmarks" flex="1" primary="
true" /> </treecols> <treechildren /> </tree> the next example does the same as the last but uses javascript to set the tree's place attribute: var histserv = cc["@mozilla.org/browser/nav-history-service;1"].
... getservice(ci.nsinavhistoryservice); var query = histserv.getnewquery(); query.searchterms = "mozilla"; query.onlybookmarked =
true; var opts = histserv.getnewqueryoptions(); opts.querytype = opts.query_type_bookmarks; var uri = histserv.queriestoquerystring([query], 1, opts); var tree = document.getelementbyid("mytree"); tree.place = uri; these two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property.
...the treechildren element should be empty: <tree type="places"> <treecols> <treecol id="title" flex="1" primary="
true" /> <treecol id="url" flex="1" /> </treecols> <treechildren /> </tree> the tree view is implemented in browser/components/places/content/tree.xml.
...And 8 more matches
Mozilla DOM Hacking Guide
the first one is the window.location object (the same holds
true for document.location, actually).
...once called, init() sets sisinitialized to
true, to remember that the initialization has been performed.
... static print32 getarrayindexfromid(jscontext *cx, jsval id, prbool *aisnumber = nsnull): if the js value is an integer, then *aisnumber is
true, and the integer is returned.
...And 8 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; } ...
... */ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setint32(23); return
true; returning a floating-point number // javascript return 3.14159; /* jsapi */ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setdouble(3.14159); exception handling throw the most common idiom is to create a new error object and throw that.
...r example: foo(); bar(); } catch (exc) { // do error-handling stuff here } /* jsapi */ /* try some stuff here; for example: */ if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto catch_block; /* instead of returning false */ if (!js_callfunctionname(cx, global, "bar", 0, null, &r)) goto catch_block; /* instead of returning false */ return
true; catch_block: js::rootedvalue exc(cx); if (!js_getpendingexception(cx, &exc)) return false; js_clearpendingexception(cx); /* do error-handling stuff here */ return
true; finally // javascript try { foo(); bar(); } finally { cleanup(); } if your c/c++ cleanup code doesn't call back into the jsapi, this is straightforward: /* jsapi */ bool success = f...
...And 8 more matches
JS::CompileOptions
versionset bool
true if version is set.
... utf8 bool
true if the character set of the source code is utf-8.
... compileandgo bool
true if the code is going to be evaluated soon after the compile (e.g., false for function constructor and event handler).
...And 8 more matches
Starting WebLock
in short, to register the weblock component as an xpcom-startup observer, do the following: char* previous = nsnull; rv = catman->addcategoryentry("xpcom-startup", "weblock", weblock_contractid, pr_
true, // persist category pr_
true, // replace existing &previous); if (previous) nsmemory::free(previous); // free the memory the replaced value might have used the unregistration, which should occur in the unregistration callback, looks like this: rv = catman->deletecategoryentry("xpcom-startup", "webl...
...ock", pr_
true); // persist a complete code listing for registering weblock as a startup observer follows: #define mozilla_strict_api #include "nsigenericfactory.h" #include "nscomptr.h" #include "nsxpcom.h" #include "nsiservicemanager.h" #include "nsicategorymanager.h" #include "nsmemory.h" #include "nsiobserver.h" #include "nsembedstring.h" #define weblock_cid \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xad, 0x10, 0x5e, 0xab, 0x25, 0xb3, 0x22, 0xaa}} #define weblock_contractid "@dougt/weblock" class weblock: public nsiobserver { public: weblock(); virtual ~weblock(); ns_decl_isupports ns_decl_nsiobserver }; weblock::weblock() { ns_init_isupports(); } weblock::~weblock() { } ns_impl_isupports1(weblock, nsiobserver); ns_imethodimp ...
...ymanager_contractid, ns_get_iid(nsicategorymanager), getter_addrefs(catman)); if (ns_failed(rv)) return rv; char* previous = nsnull; rv = catman->addcategoryentry("xpcom-startup", "weblock", weblock_contractid, pr_
true, pr_
true, &previous); if (previous) nsmemory::free(previous); return rv; } static ns_method weblockunregistration(nsicomponentmanager *acompmgr, nsifile *apath, const char *registrylocation, const nsmodulecom...
...And 8 more matches
nsITextInputProcessor
true if it has composition.
...when this is specified, defaultprevented attribute of dispatching keyboard events
true.
... return value returns
true if the instance could create composition.
...And 8 more matches
Debugger - Firefox Developer Tools
it is an accessor property with a getter and setter: assigning to it enables or disables this debugger instance; reading it produces
true if the instance is enabled, or false otherwise.
... this property is initially
true in a freshly created debugger instance.
... setting this flag to
true is intended for uses of subsystems of the debugger api (e.g, debugger.source) for purposes other than step debugging a target javascript program.
...And 8 more matches
Fullscreen API - Web APIs
obsolete properties document.fullscreen a boolean value which is
true if the document has an element currently being displayed in full-screen mode; otherwise, this returns false.
...te name alternate name uses the non-standard name: webkitisfullscreenfirefox full support 64 full support 64 no support 49 — 65disabled disabled from version 49 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to
true).
...alternate name uses the non-standard name: webkitisfullscreenfirefox android full support 64 full support 64 no support 49 — 65disabled disabled from version 49 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to
true).
...And 8 more matches
ARIA Test Cases - Accessibility
at should indicate that it is a toggle button (not a regular button) markup used: role="button" aria-pressed="false" (or
true) notes: results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 pass in non-v-pc-mode, button's state is announced when pressed, or when toggling it to pressed.
... markup used: role="checkbox" aria-checked="
true" or "false" notes: need testcase where aria-checked attribute is removed instead of set to false results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 pass fail (changes not spoken) fail fail voiceover (leopard) n/a n/a - fail window-eyes pass pass fail (unchecked prese...
... markup used: role="checkbox" aria-checked="
true" | "false" | "mixed" notes: results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 partial pass.
...And 8 more matches
ARIA: switch role - Accessibility
<button type="button" role="switch" aria-checked="
true" id="speakerpower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerpower" class="switch">speaker power</label> description the aria switch role is identical to the checkbox role, except instead of being "checked" or "unchecked", it is either "on" and "off." like the checkbox role, the aria-checked attribute is required.
... the two possible values are
true and false.
...a value of
true represents the "on" state; false represents the "off" state; a value of mixed is not supported by the switch role, and is treated as false.
...And 8 more matches
@supports - CSS: Cascading Style Sheets
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 8 more matches
Equality comparisons and sameness - JavaScript
var num = 0; var obj = new string('0'); var str = '0'; console.log(num === num); //
true console.log(obj === obj); //
true console.log(str === str); //
true console.log(num === obj); // false console.log(num === str); // false console.log(obj === str); // false console.log(null === undefined); // false console.log(obj === null); // false console.log(obj === undefined); // false strict equality is almost always the correct comparison operation to use.
...(the only case in which (x !== x) is
true is when x is nan.) loose equality using == loose equality compares two values for equality, after converting both values to a common type.
... the equality comparison is performed as follows for operands of the various types: operand b undefined null number string boolean object operand a undefined
true true false false false false null
true true false false false false number false false a === b a === tonumber(b) a === tonumber(b) a == toprimitive(b) string false false tonumber(a) === b a === b tonumber(a) === tonumber(b) a == toprimitive(b) boolean false false tonumber(a) === b ...
...And 8 more matches
url - Archive of obsolete content
isvaliduri("http://mozilla.org") would return
true, whereas isvaliduri("mozilla.org") would return false.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=
true&visible=yes#top"); console.log(url.scheme); // https userpass the username:password part of the url, null if not present.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=
true&visible=yes#top"); console.log(url.host); // developer.mozilla.org port the port number of the url, null if none was specified.
...And 7 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
var myextension = { mylistener: function(evt) { alert("received from web page: " + evt.target.getattribute("attribute1") + "/" + evt.target.getattribute("attribute2")); } } document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false,
true); // the last value is a mozilla-specific value to indicate untrusted content is allowed to trigger the event.
...trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createelement("myextensiondataelement"); element.setattribute("attribute1", "foobar"); element.setattribute("attribute2", "hello world"); document.documentelement.appendchild(element); var evt = document.createevent("events"); evt.initevent("myextensionevent",
true, false); element.dispatchevent(evt); this code creates an arbitrary element -- <myextensiondataelement/> -- and inserts it into the web page's dom.
...nents.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false,
true); if you need to to pass lots of data, consider using cdata sections instead of the simple attributes on a custom element.
...And 7 more matches
Using microformats - Archive of obsolete content
if provided, this is a javascript object that contains zero or more of the following flags: recurseexternalframes if
true, child frames are included in the search.
... the default is
true.
... showhidden if
true, hidden microformats are added; otherwise they're left out.
...And 7 more matches
Extensions - Archive of obsolete content
for instance, the 'onlink' property is set to
true when a link was context-clicked.
... ontextinput
true if the target is a plain or password type input, a textarea, or an editable area.
... onimage
true if the target is an image.
...And 7 more matches
wizard - Archive of obsolete content
firstpage type: boolean
true if the wizard is on the first page.
... lastpage type: boolean
true if the wizard is on the last page.
... values for window type as found on mxr: http://mxr.mozilla.org/mozilla-release/search?string=windowtype navigator:browser - looks like if window has gbrowser it has this window type devtools:scratchpad - scratchpad windows navigator:view-source - the view source windows properties canadvance type: boolean this property is set to
true if the user can press the next button to go to the next page.
...And 7 more matches
LiveConnect Overview - Archive of obsolete content
however, suppose myfunction is defined in javascript as follows: function myfunction() { try { if (thecondition ==
true) { return "everything's ok"; } else { throw "javascript error occurred"; } } catch (e) { if (canhandle ==
true) { handleit(); } else { throw e; } } } if thecondition is false, the function throws an exception.
... the exception is caught in the javascript code, and if canhandle is
true, javascript handles it.
... other values are converted to
true.
...And 7 more matches
JavaScript basics - Learn web development
let myvariable = 10; boolean this is a
true/false value.
... the words
true and false are special keywords that don't need quote marks.
... let myvariable =
true; array this is a structure that allows you to store multiple values in a single reference.
...And 7 more matches
Encrypt Decrypt MAC Keys As Session Objects
f(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_stde...
...&ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_
true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop return...
...0] = paddinglength; paditem.type = sibuffer; paditem.data = (unsigned char *)pad; paditem.len = sizeof(pad[0]); writetoheaderfile(paditem.data, paditem.len, pad, headerfile); if (rv != secsuccess) { pr_fprintf(pr_stderr, "write pad failure\n"); goto cleanup; } rv = secsuccess; cleanup: if (ctxmac != null) { pk11_destroycontext(ctxmac, pr_
true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_
true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_tru...
...And 7 more matches
Encrypt and decrypt MAC using token
f(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_stde...
...&ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_
true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop return...
...0] = paddinglength; paditem.type = sibuffer; paditem.data = (unsigned char *)pad; paditem.len = sizeof(pad[0]); writetoheaderfile(paditem.data, paditem.len, pad, headerfile); if (rv != secsuccess) { pr_fprintf(pr_stderr, "write pad failure\n"); goto cleanup; } rv = secsuccess; cleanup: if (ctxmac != null) { pk11_destroycontext(ctxmac, pr_
true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_
true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_tru...
...And 7 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
f(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_stde...
...&ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_
true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop return...
...0] = paddinglength; paditem.type = sibuffer; paditem.data = (unsigned char *)pad; paditem.len = sizeof(pad[0]); writetoheaderfile(paditem.data, paditem.len, pad, headerfile); if (rv != secsuccess) { pr_fprintf(pr_stderr, "write pad failure\n"); goto cleanup; } rv = secsuccess; cleanup: if (ctxmac != null) { pk11_destroycontext(ctxmac, pr_
true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_
true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_tru...
...And 7 more matches
nss tech note5
utbuf, &tmp1_outlen, sizeof outbuf, inbuf, inbuflen); s = pk11_digestfinal(enccontext, outbuf+tmp1_outlen, &tmp2_outlen, sizeof outbuf - tmp1_outlen); result_len = tmp1_outlen + tmp2_outlen; <big>destroy the context pk11_destroycontext(enccontext, pr_
true);</big> <big>repeat step 6 any number of times.
... when all done with encrypt/decrypt ops, clean up</big> <big>pk11_freesymkey(symkey); secitem_freeitem(secparam, pr_
true); pk11_freeslot(slot);</big> note: aes encryption, a fixed blocksize of 16 bytes is used.
... = pk11_createdigestcontext(sec_oid_md5); <big>digest the data</big> <big>secstatus s = pk11_digestbegin(digestcontext); s = pk11_digestop(digestcontext, data, sizeof data); s = pk11_digestfinal(digestcontext, digest, &len, sizeof digest); /* now, digest contains the 'digest', and len contains the length of the digest */</big> clean up pk11_destroycontext(digestcontext, pr_
true); you can also look at a sample program illustrating this hash / digest with secret key included include headers #include "nss.h" #include "pk11pub.h" make sure nss is initialized.the simplest init function, in case you don't need a nss database is nss_nodb_init(".") choose a digest mechanism.
...And 7 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>javascript typewriter - mdn example</title> <script> function typewriter (sselector, nrate) { function clean () { clearinterval(nintervid); btyping = false; bstart =
true; ocurrent = null; asheets.length = nidx = 0; } function scroll (osheet, npos, beraseandstop) { if (!osheet.hasownproperty('parts') || amap.length < npos) { return
true; } var orel, bexit = false; if (amap.length === npos) { amap.push(0); } while (amap[npos] < osheet.parts.length) { orel = osheet.parts[amap[npos]]; scroll(orel, npos + 1, beraseandstop) ...
...amap[npos]++ : bexit =
true; if (beraseandstop && (orel.ref.nodetype - 1 | 1) === 3 && orel.ref.nodevalue) { bexit =
true; ocurrent = orel.ref; spart = ocurrent.nodevalue; ocurrent.nodevalue = ''; } osheet.ref.appendchild(orel.ref); if (bexit) { return false; } } amap.length--; return
true; } function typewrite () { if (spart.length === 0 && scroll(asheets[nidx], 0,
true) && nidx++ === asheets.length - 1) { clean(); return; } ocurrent.nodevalue += spart.charat(0); spart = spart.slice(1); } function sheet (onode) { this.ref = onode; if (!onode.haschildnodes()) { return; } this.parts = array.prototype.slice.call(onode.childnodes); for (var nchild = 0; nchild < this.parts.length; nchil...
...d++) { onode.removechild(this.parts[nchild]); this.parts[nchild] = new sheet(this.parts[nchild]); } } var nintervid, ocurrent = null, btyping = false, bstart =
true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (btyping) { return; } if (bstart) { var aitems = document.queryselectorall(sselector); if (aitems.length === 0) { return; } for (var nitem = 0; nitem < aitems.length; nitem++) { asheets.push(new sheet(aitems[nitem])); /* uncomment the following line if you have previously hidden your elements via css: */ // aitems[nitem].style.visibility = "visible"; } bstart = false; } nintervid = setinterval(typewrite, this.rate); btyp...
...And 7 more matches
ARIA: button role - Accessibility
the aria-pressed attribute values of
true or false identify a button as a toggle button.
... a menu button is a button that controls a menu and has an aria-haspopup property attribute set to either menu or
true.
...the values include aria-pressed="false" when a button is not currently pressed, aria-pressed="
true" to indicate a button is currently pressed, and aria-pressed="mixed" if the button is considered to be partially pressed.
...And 7 more matches
Object.defineProperty() - JavaScript
they share the following optional keys (note: the default value is in the case of defining properties using object.defineproperty()): configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
... enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
... writable
true if and only if the value associated with the property may be changed with an assignment operator.
...And 7 more matches
this - JavaScript
// in web browsers, the window object is also the global object: console.log(this === window); //
true a = 37; console.log(window.a); // 37 this.b = "mdn"; console.log(window.b) // "mdn" console.log(b) // "mdn" note: you can always easily get the global object using the global globalthis property, regardless of the current context in which your code is running.
... 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, because f2 was called directly and not as a method or property of an object (e.g.
...in global code, it will be set to the global object: var globalobject = this; var foo = (() => this); console.log(foo() === globalobject); //
true note: if this arg is passed to call, bind, or apply on invocation of an arrow function it will be ignored.
...And 7 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.
... let { has } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; has(a, 'rock'); //
true has(a, 'rush'); // false has(a, 100); //
true parameters array : array the array to search.
... hasany(array, elements) returns
true if the given array contains any of the elements in the elements array, or false otherwise.
...And 6 more matches
window/utils - Archive of obsolete content
getxulwindow(window) returns the nsixulwindow for the given nsidomwindow: var { ci } = require('chrome'); var utils = require('sdk/window/utils'); var active = utils.getmostrecentbrowserwindow(); active instanceof ci.nsixulwindow // => false utils.getxulwindow(active) instanceof ci.nsixulwindow // =>
true parameters window : nsidomwindow returns nsixulwindow getbasewindow(window) returns the nsibasewindow for the given nsidomwindow: var { ci } = require('chrome'); var utils = require('sdk/window/utils'); var active = utils.getmostrecentbrowserwindow(); active instanceof ci.nsibasewindow // => false utils.getbasewindow(active) instanceof ci.nsibasewindow // =>
true parameters window : nsid...
...omwindow returns nsibasewindow gettoplevelwindow(window) returns the toplevel nsidomwindow for the given child nsidomwindow: var { ci } = require('chrome'); var utils = require('sdk/window/utils'); var browserwindow = utils.getmostrecentbrowserwindow(); var window = browserwindow.content; // `window` object for the current webpage utils.gettoplevelwindow(window) == browserwindow // =>
true parameters window : nsidomwindow returns nsidomwindow getwindowdocshell(window) returns the nsidocshell for the tabbrowser element.
... features object map of features to set for the window, defined like this: { width: 10, height: 15, chrome:
true }.
...And 6 more matches
Install Manifests - Archive of obsolete content
examples <em:developer>jane doe</em:developer> <em:developer>koos van der merwe</em:developer> hasembeddedwebextension if present and given the value "
true", this indicates that this add-on contains an embedded webextension.
... <em:hasembeddedwebextension>
true</em:hasembeddedwebextension> homepageurl a link to the add-on's home page - intended for display in the user interface.
... skinnable a
true or false value property that tells the application whether the (complete) theme can be skinned by lightweight themes/personas: examples <em:skinnable>
true</em:skinnable> strictcompatibility a boolean value indicating if the add-on should be enabled when the version of the application is greater than its max version.
...And 6 more matches
Tabbed browser - Archive of obsolete content
inished loading yet) var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); alert(newtabbrowser.contentdocument.body.innerhtml); // better way var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); newtabbrowser.addeventlistener("load", function () { newtabbrowser.contentdocument.body.innerhtml = "<div>hello world</div>"; },
true); (the event target in the onload handler will be a 'tab' xul element).
... xul: <menuitem oncommand="myextension.foo(event)" onclick="checkformiddleclick(this, event)" label="click me"/> js: var myextension = { foo: function(event) { openuilink("http://www.example.com", event, false,
true); } } opening a url in an on demand tab cu.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazyservicegetter(this, "gsessionstore", "@mozilla.org/browser/sessionstore;1", "nsisessionstore"); // create new tab, but don't load the content.
... var url = "https://developer.mozilla.org"; var tab = gbrowser.addtab(null, {relatedtocurrent:
true}); gsessionstore.settabstate(tab, json.stringify({ entries: [ { title: url } ], usertypedvalue: url, usertypedclear: 2, lastaccessed: tab.lastaccessed, index: 1, hidden: false, attributes: {}, image: null })); reusing tabs rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired url--if one is already open.
...And 6 more matches
MenuItems - Archive of obsolete content
<menu label="view" accesskey="v"> <menupopup> <menuitem label="show toolbar" accesskey="t" type="checkbox" checked="
true"/> <menuitem label="show status bar" accesskey="s" type="checkbox"/> </menupopup> </menu> both menuitems are of the checkbox type.
... the first menuitem is checked by default, as indicated by the checked attribute set to the value
true.
... <script> function changetoolbarstate(event) { if (event.target.getattribute("checked") == "
true") showtoolbar(); else hidetoolbar(); } </script> ...
...And 6 more matches
XUL element attributes - Archive of obsolete content
allowevents type: boolean if
true, events are passed to children of the element.
...this attribute, if
true, which is the default, allows a datasource to negate an earlier assertion.
...this attribute, if
true, which is the default, allows a datasource to negate an earlier assertion.
...And 6 more matches
panel - Archive of obsolete content
close type: boolean if the panel has a titlebar, set the panel's close attribute to
true to have a close button appear on the titlebar.
...if it set to
true the rollup event is consumed.
...if
true, the escape key cannot be used to close the panel.
...And 6 more matches
Beginning our React todo list - Learn web development
nput type="text" id="new-todo-input" classname="input input__lg" name="text" autocomplete="off" /> <button type="submit" classname="btn btn__primary btn__lg"> add </button> </form> <div classname="filters btn-group stack-exception"> <button type="button" classname="btn toggle-btn" aria-pressed="
true"> <span classname="visually-hidden">show </span> <span>all</span> <span classname="visually-hidden"> tasks</span> </button> <button type="button" classname="btn toggle-btn" aria-pressed="false"> <span classname="visually-hidden">show </span> <span>active</span> <span classname="visually-hidden"> tasks</span> </but...
...sually-hidden"> tasks</span> </button> </div> <h2 id="list-heading"> 3 tasks remaining </h2> <ul role="list" classname="todo-list stack-large stack-exception" aria-labelledby="list-heading" > <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="vis...
...for example: <button type="button" classname="btn toggle-btn" aria-pressed="
true"> <span classname="visually-hidden">show </span> <span>all</span> <span classname="visually-hidden"> tasks</span> </button> here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed.
...And 6 more matches
Frame script loading and lifetime
the script just writes "foo" to the command line: // chrome script var mm = gbrowser.selectedbrowser.messagemanager; mm.loadframescript('data:,dump("foo\\n")',
true); loadframescript() takes two mandatory parameters: a url that points to the frame script you want to load a boolean flag, allowdelayedload note: if the message manager is a global frame message manager or a window message manager, loadframescript() may load the script multiple times, once in each applicable frame.
... to define the mapping between a chrome:// url and a frame script packaged with an extension, use a "chrome.manifest" file to register a chrome url: // chrome.manifest content my-e10s-extension chrome/content/ // chrome script mm.loadframescript("chrome://my-e10s-extension/content/content.js",
true); allowdelayedload if the message manager is a global frame message manager or a window message manager then: if allowdelayedload is
true, the frame script will be loaded into any new frame, which has opened after the loadframescript() call.
... for example: var mm = window.messagemanager; mm.loadframescript("chrome://my-e10s-extension/content/frame-script.js",
true); the script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards.
...And 6 more matches
IME handling guide
are available if beginnativeinputtransaction() return
true.
... if all merged text changes were caused by composition, imenotification::mtextchangedata::mcausedonlybycomposition is set to
true.
... if at least one text change of the merged text changes was caused by current composition, imenotification::mtextchangedata::mincludingchangesduringcomposition is set to
true.
...And 6 more matches
Download
this property can become
true, then it can be reset to false when a canceled download is restarted.
... this property becomes
true as soon as the cancel() method is called, though the stopped property might remain false until the cancellation request has been processed.
... temporary files or part files may still exist even if they are expected to be deleted, until the stopped property becomes
true.
...And 6 more matches
EncDecMAC using token object - sample 3
_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) { sec...
...t *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_
true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop returned %d\n", rv); goto cleanup; } cleanup: if (...
...intf(pr_stderr, "write mac failure\n"); goto cleanup; } pad[0] = paddinglength; paditem.type = sibuffer; paditem.data = (unsigned char *)pad; paditem.len = sizeof(pad[0]); writetoheaderfile(paditem.data, paditem.len, pad, headerfile); if (rv != secsuccess) { pr_fprintf(pr_stderr, "write pad failure\n"); goto cleanup; } rv = secsuccess; cleanup: if (ctxmac != null) { pk11_destroycontext(ctxmac, pr_
true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_
true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, 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 auth...
...And 6 more matches
Places Developer Guide
foldernode.containeropen =
true; for (var i=0; i < foldernode.childcount; ++i) { var childnode = foldernode.getchild(i); // some item properties.
... if (type == ci.nsinavhistoryresultnode.result_type_uri) { var uri = childnode.uri; } else if (type == ci.nsinavhistoryresultnode.result_type_folder) { childnode.queryinterface(ci.nsinavhistorycontainerresultnode); childnode.containeropen =
true; // now you can iterate over a subfolder's children } } ther available node types are documented in the idl.
...resultcontainernode.containeropen =
true; for (var i=0; i < resultcontainernode.childcount; ++i) { var childnode = resultcontainernode.getchild(i); // accessing properties of matching bookmarks var title = childnode.title; var uri = childnode.uri; } updating bookmark items for all items: setitemtitle(aitemid, atitle) - changes an item's title.
...And 6 more matches
nsIHttpChannel
this attribute is
true by default, though other factors may prevent pipelining.
... requestsucceeded boolean returns
true if the http response code indicates success.
... isnocacheresponse() returns
true if the server sent the equivalent of a "cache-control: no-cache" response header.
...And 6 more matches
Debugger.Object - Firefox Developer Tools
callable
true if the referent is a callable object (such as a function or a function proxy); false otherwise.
...return
true if the property was successfully removed, or if the referent has no such property.
...(this function behaves like the standard object.preventextensions function, except that the object to operate on is implicit and in a different compartment from the caller.) issealed() return
true if the referent is sealed—that is, if it is not extensible, and all its properties have been marked as non-configurable.
...And 6 more matches
DevTools API - Firefox Developer Tools
parameters: force {boolean} - if
true the target is shift-reloaded i.e.
...if
true, the label won't be shown in the tool's tab.
...if
true the colors of the icon will be inverted for the light theme.
...And 6 more matches
BluetoothCharacteristicProperties - Web APIs
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.
... indicateread only returns a boolean that is
true if indications of the characteristic value with acknowledgement is permitted.
...And 6 more matches
MutationObserverInit - Web APIs
properties at a minimum, one of childlist, attributes, and/or characterdata must be
true when you call observe().
... subtree optional set to
true to extend monitoring to the entire subtree of nodes rooted at target.
... childlist optional set to
true to monitor the target node (and, if subtree is
true, its descendants) for the addition of new child nodes or removal of existing child nodes.
...And 6 more matches
SubtleCrypto.wrapKey() - Web APIs
to export a key, it must have cryptokey.extractable set to
true.
...*/ 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.
...*/ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, },
true, ["encrypt", "decrypt"] ) .then((secretkey) => { return wrapcryptokey(secretkey); }) .then((wrappedkey) => { console.log(wrappedkey); }); pkcs #8 wrap this example wraps an rsa private signing key.
...And 6 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
the code looks like this: const xrotationdegreespersecond = 25; const yrotationdegreespersecond = 15; const zrotationdegreespersecond = 35; const enablerotation =
true; const allowmouserotation =
true; const allowkeyboardmotion =
true; const enableforcepolyfill = false; //const session_type = "immersive-vr"; const session_type = "inline"; const mouse_speed = 0.003; xrotationdegreespersecond the number of degrees of rotation to apply around the x axis per second.
... allowmouserotation if
true, you can use the mouse to pitch and yaw the view angle.
... allowkeyboardmotion if
true, the w, a, s, and d keys move the viewer forward, left, backward, and to the right, while the up and down arrow keys move up and down.
...And 6 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().
...list[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.
...channelcount; channelnum++) { let samplecount = input[channelnum].length; for (let i = 0; i < samplecount; i++) { let sample = output[channelnum][i] + input[channelnum][i]; if (sample > 1.0) { sample = 1.0; } else if (sample < -1.0) { sample = -1.0; } output[channelnum][i] = sample; } } }; return
true; } this is similar code to the previous sample in many ways, but only the first output—outputlist[0]—is altered.
...And 6 more matches
Using the aria-hidden attribute - Accessibility
description adding aria-hidden="
true" to an element removes that element and all of its children from the accessibility tree.
... this can improve the experience for assistive technology users by hiding: purely decorative content, such as icons or images duplicated content, such as repeated text offscreen or collapsed content, such as menus according to the fourth rule of aria, aria-hidden="
true" should not be used on a focusable element.
... using aria-hidden="false" will not re-expose the element to assistive technology if any of its parents specify aria-hidden="
true".
...And 6 more matches
Loops and iteration - JavaScript
if the value of conditionexpression is
true, the loop statements execute.
...(if the condition expression is omitted entirely, the condition is assumed to be
true.) the statement executes.
...}) to group those statements.) if condition is
true, the statement executes again.
...And 6 more matches
Array.prototype.every() - JavaScript
return value
true if the callback function returns a truthy value for every array element.
...otherwise, if callback returns a truthy value for all elements, every returns
true.
... caution: calling this method on an empty array will return
true for any condition!
...And 6 more matches
Object.isFrozen() - JavaScript
var vacuouslyfrozen = object.preventextensions({}); object.isfrozen(vacuouslyfrozen); // ===
true // a new object with one property is also extensible, // ergo not frozen.
...delete oneprop.p; object.isfrozen(oneprop); // ===
true // a non-extensible object with a non-writable // but still configurable property is not frozen.
...object.defineproperty(nonwritable, 'e', { configurable: false }); // make non-configurable object.isfrozen(nonwritable); // ===
true // a non-extensible object with a non-configurable // but still writable property also isn't frozen.
...And 6 more matches
Iteration protocols - JavaScript
(this is equivalent to not specifying the done property altogether.) has the value
true if the iterator has completed its sequence.
...can be omitted when done is
true.
...string[symbol.iterator]); // "function" string's default iterator returns the string's code points one by one: let iterator = somestring[symbol.iterator](); console.log(iterator + ''); // "[object string iterator]" console.log(iterator.next()); // { value: "h", done: false } console.log(iterator.next()); // { value: "i", done: false } console.log(iterator.next()); // { value: undefined, done:
true } some built-in constructs—such as the spread syntax—use the same iteration protocol under the hood: console.log([...somestring]); // ["h", "i"] you can redefine the iteration behavior by supplying our own @@iterator: // need to construct a string object explicitly to avoid auto-boxing let somestring = new string('hi'); somestring[symbol.iterator] = function () { return { // this i...
...And 6 more matches
Equality (==) - JavaScript
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.
... if one of the operands is boolean, convert the boolean operand to 1 if it is
true and +0 if it is false.
...And 6 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
autoplay availability as a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is
true: the audio is muted or its volume is set to 0 the user has interacted with the site (by clicking, tapping, pressing keys, etc.) if the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features if the autoplay feature policy is used to grant autoplay s...
...this sets the autoplay property on the element to
true, and when autoplay is
true, the media will automatically begin to play as soon as possible after the following have occurred: the page is allowed to use autoplay functionality the element has been created during page load enough media has been received to begin playback and continue to play through to the end of the media without interruption, assuming there are no dramatic changes in networ...
...this is currently false by default (except in nightly builds, where it's
true by default).
...And 6 more matches
Classes and Inheritance - Archive of obsolete content
to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape = new shape(2, 3); shape instanceof shape; // =>
true shape.x; // => 2 shape.y; // => 3 the keyword new tells javascript that we are performing a constructor call.
...when a function is used in a constructor call, javascript makes the value of this property the prototype of the newly created object: let shape = shape(2, 3); object.getprototypeof(shape) == shape.prototype; // =>
true all instances of a class have the same prototype.
...we can now use the above constructor to create instances of the class circle: let circle = circle(2, 3, 5); circle instanceof circle; // =>
true circle.x; // => 2 circle.y; // => 3 circle.radius; // => 5 inheritance and prototypes there is a problem with the definition of circle in the previous section that we have glossed over thus far.
...And 5 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.
... but in the example below, node.nodename is not guaranteed to be "p" - for example, it won't be "p" if the user context-clicked a link inside a paragraph: var cm = require("sdk/context-menu"); cm.item({ label: "a paragraph", context: cm.selectorcontext("p"), contentscript: 'self.on("context", function (node) {' + ' console.log(node.nodename);' + ' return
true;' + '});' }); the content script is executed for every page that a context menu is shown for.
...And 5 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
true browser.dom.window.dump.enabled (not present in firefox 3.5+) enables use of the dump method for debugging.
...
true javascript.options.showinconsole (present in firefox 3.5+) outputs javascript errors to the error console.
...
true javascript.options.strict (present in firefox 3.5+) enforces strict error output from javascript
true table 1: preferences to set for developing extensions to make these changes, start your development profile, type about:config into firefox’s location bar and open the preferences window; find the preferences listed in table 1 and double-click on them to set them accordingly.
...And 5 more matches
Dehydra Object Reference - Archive of obsolete content
dehydra only sets boolean flags when they are
true.
... for example, a pointer type will have .ispointer ==
true, but a class type will not have an .ispointer property.
...return t();), no container variable is available; in this case, .isreturn will be
true (see function variable).
...And 5 more matches
Elements - Archive of obsolete content
= "http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink"> binding <!entity % binding-content "(resources?,content?,implementation?,handlers?)"> <!element binding %binding-content;> <!attlist binding id id #required extends cdata #implied display cdata #implied inheritstyle
true #implied > the binding element describes a single xbl binding.
...if this attribute is
true, styles from the document will also be applied to the xbl generated anonymous content.
... field <!element field empty> <!attlist field id id #implied name cdata #required readonly (
true|false) #implied > a field is similar to a property, except that it should not have a getter or setter.
...And 5 more matches
Multiple Rules - Archive of obsolete content
here is another example for an xml source: <radiogroup datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <rule> <where subject="?gender" rel="equals" value="male"/> <action> <radio uri="?" label="?name is male"/> </action> </rule> <rule> <action> <radio uri="?" label="?name is female" disabled="
true"/> </action> </rule> </template> </radiogroup> in this example, all male people are matched with the first rule, and a radio button is generated for each one.
...by setting the negate attribute to
true, the condition matches only those that don't match the condition, reversing the results that match.
... <where subject="?title" rel="equals" value="canal"/> <where subject="?title" rel="equals" value="canal" negate="
true"/> you can use the negate attribute with all of the relational operators.
...And 5 more matches
Input Controls - Archive of obsolete content
disabled set to
true to have text entry disabled.
...if you set the multiline attribute to
true, the text entry field will display multiple rows.
... example 2 : source view <textbox multiline="
true" value="this is some text that could wrap onto multiple lines."/> like the html textarea, you can use the rows and cols attributes to set the size.
...And 5 more matches
menulist - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disableautoselect type: boolean if this attribute is
true or omitted, the selected item on the menu will update to match what the user entered in the textbox.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... focused type: boolean this attribute is
true if the element is focused.
...And 5 more matches
tabbrowser - Archive of obsolete content
goforwardgroup, gohome, gotoindex, loadgroup, loadonetab, loadtabs, loaduri, loaduriwithflags, movetabto, pintab, reload, reloadalltabs, reloadtab, reloadwithflags, removealltabsbut, removecurrenttab, removeprogresslistener, removetab, removetabsprogresslistener,replacegroup, selecttabatindex, seticon, showonlythesetabs, stop, unpintab attributes autocompleteenabled type: boolean set to
true to enable autocomplete of fields.
...if this attribute is set to
true or omitted, autoscroll will be enabled or depending on the user preference general.autoscroll.
... cangoback type: boolean this read-only property is
true if there is a page to go back to in the session history and the back button should be enabled.
...And 5 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.
... */ void setvalue(in domstring value); /** * return
true if the instance node is readonly as determined by the mdg.
... */ boolean isreadonly(); /** * return
true if the instance node is relevant as determined by the mdg.
...And 5 more matches
Looping code - Learn web development
a condition, which is a
true/false test to determine whether the loop continues to run, or stops — usually when the counter reaches a certain value.
... an iterator, which generally increments the counter by a small amount on each successive loop, until the condition is no longer
true.
...if he has reached 10 portions (the point where the condition is no longer
true, so the loop exits), he can stop collecting and go home.
...And 5 more matches
Accessibility API cross-reference
a checkbox; aria has two kinds: use checkbox if you need to express 'mixed' state (some of the descendents are
true, some are false), otherwise use switch or (preferred in html) <input type=checkbox>, which are
true/false only.
... marquee the main menu bar below the app's title bar menubar menu_bar menu_bar menubar a menu item menuitem menu_item menu_item menuitem a menuitem with a checkable state whose possible values are
true, false, or mixed.
... n/a n/a aria-details this is for expandable items that are not expanded, such as folded tree branches or accordions collapsed collapsed collapsed aria-expanded=false different from xul's collapsed="
true" attribute which indicates something is hidden this is the default button or menu item default n/a n/a identifies the element that provides an error message for the object.
...And 5 more matches
Using the Browser API
we did this with the following functions: function canmovebwd() { var request = browser.getcangoback(); request.onsuccess = function() { if (request.result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled =
true; console.log("it's not possible to navigate the history backward."); } } } function canmovefwd() { var request = browser.getcangoforward(); request.onsuccess = function() { if (request.result) { fwd.disabled = false; console.log("it's possible to navigate the history forward."); } else { fwd.disabled =
true; console.log("it's not possible to navig...
...if
true is returned, the relevant button is disabled, and if false is returned, the relevant button is enabled.
...for example: function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled =
true; console.log("it's not possible to navigate the history backward."); } }); } implementing the url bar the url bar for our simple browser is a <form> containing a single text <input>.
...And 5 more matches
MathML Torture Test
> </td></tr> <tr> <td>6</td> <td><img src="https://udn.realityripple.com/samples/76/5ce9da68c6.png" width="220" height="138" alt="texbook, 17.5-17.6" /></td> <td> <math display="block"> <mrow> <msub> <mi>a</mi> <mn>0</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="
true" scriptlevel="0"> <msub> <mi>a</mi> <mn>1</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="
true" scriptlevel="0"> <msub> <mi>a</mi> <mn>2</mn> </msub> <mo>+</mo> ...
... <mfrac> <mn>1</mn> <mstyle displaystyle="
true" scriptlevel="0"> <msub> <mi>a</mi> <mn>3</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="
true" scriptlevel="0"> <msub> <mi>a</mi> <mn>4</mn> </msub> </mstyle> </mfrac> </mstyle> </mfrac> </mstyle> </mfrac> </mstyle> </mfrac> </mrow> </math> </td...
... <mo>/</mo> <mn>۲</mn> </mrow> </mfrac> </mrow> </math> </td></tr> <tr> <td>6</td> <td> <math dir="rtl" display="block"> <mrow> <msub> <mi>𞸀</mi> <mn>٠</mn> </msub> <mo>+</mo> <mfrac> <mn>١</mn> <mstyle displaystyle="
true" scriptlevel="0"> <msub> <mi>𞸀</mi> <mn>١</mn> </msub> <mo>+</mo> <mfrac> <mn>١</mn> <mstyle displaystyle="
true" scriptlevel="0"> <msub> <mi>𞸀</mi> <mn>٢</mn> </msub> ...
...And 5 more matches
PKCS11 Implement
true false the device is uninitialized.
...the nss calls c_initpin to initialize the device and set the user pin; if these calls are successful, the key is generated and at that point the cfk_user_pin_initialized flag should change from false to
true.
... false
true this is a general access device that can have a pin set on it.
...And 5 more matches
JS::Value
the data in a js::value can be accessed using these member functions: js type js::value type tests constructor accessors mutators null val.isnull() js::nullvalue() n/a val.setnull() undefined val.isundefined() js::undefinedvalue() n/a val.setundefined() boolean val.isboolean(), val.is
true(), val.isfalse() js::booleanvalue(bool), js::
truevalue(), js::falsevalue() val.toboolean() val.setboolean(bool) number val.isint32(), val.isdouble(), val.isnumber() js::numbervalue(any number type), js::int32value(int32_t), js::doublevalue(double), js::float32value(float) val.toint32(), val.todouble(), val.tonumber() val.setint32(int32_t), val.setnumber(uint32_t), va...
...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.
... val.isobjectornull() returns
true if the value is either an object or undefined.
...And 5 more matches
nsIAutoCompleteInput
completeselectedindex boolean if
true, the text in the text field will be autocompleted as the user selects from the popup list.
... consumerollupevent boolean if
true, the event that rolls up the popup should be consumed by the popup itself.
... disableautocomplete boolean
true if auto-complete is currently disabled; otherwise false.
...And 5 more matches
nsIMsgProtocolInfo
method overview long getdefaultserverport(in boolean issecure); attributes attribute type description candelete boolean
true if an account of this type may be deleted.
... cangetincomingmessages boolean
true if junk ui actions should be enabled for the account type.
... cangetmessages boolean
true if "get messages" ui actions should be enabled for the account type.
...And 5 more matches
nsISelectionController
void wordmove(in boolean forward, in boolean extend); attributes attribute type description caretvisible boolean this is
true if the caret is enabled, visible, and currently blinking.
... this is still
true when the caret is enabled, visible, but in its "off" blink cycle.
... return value
true if visible, false if not.
...And 5 more matches
Web Console remoting - Firefox Developer Tools
startlisteners(listeners, onresponse) the new startlisteners packet: { "to": "conn0.console9", "type": "startlisteners", "listeners": [ "pageerror", "consoleapi", "networkactivity", "fileactivity" ] } the reply is: { "startedlisteners": [ "pageerror", "consoleapi", "networkactivity", "fileactivity" ], "nativeconsoleapi":
true, "from": "conn0.console9" } the reply tells which listeners were started and it includes a flag nativeconsoleapi which tells if the window.console object was overridden by the scripts in the page or not.
... when page navigation starts the following packet is sent from the tab actor: { "from": tabactor, "type": "tabnavigated", "state": "start", "url": newurl, "nativeconsoleapi":
true } the nativeconsoleapi property tells if the window.console object is native or not for the top level window object for the given tab - this is always
true when navigation starts.
... when navigation stops the following packet is sent: { "from": tabactor, "type": "tabnavigated", "state": "stop", "url": newurl, "title": newtitle, "nativeconsoleapi":
true|false } getcachedmessages(types, onresponse) the webconsoleclient.getcachedmessages(types, onresponse) method sends the following packet to the server: { "to": "conn0.console9", "type": "getcachedmessages", "messagetypes": [ "pageerror", "consoleapi" ] } the getcachedmessages packet allows one to retrieve the cached messages from before the web console was open.
...And 5 more matches
Document - Web APIs
document.mozsyntheticdocument returns a boolean that is
true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
... document.fullscreen
true when the document is in full-screen mode.
... document.xmlstandalone obsolete since gecko 10 returns
true if the xml declaration specifies the document to be standalone (e.g., an external part of the dtd affects the document's content), else false.
...And 5 more matches
Using IndexedDB - Web APIs
objectstore.createindex("email", "email", { unique:
true }); // use transaction oncomplete to make sure the objectstore creation is // finished before adding data into it.
...var request = indexeddb.open(dbname, 3); request.onupgradeneeded = function (event) { var db = event.target.result; // create another object store called "names" with the autoincrement flag set as
true.
... var objstore = db.createobjectstore("names", { autoincrement :
true }); // because the "names" object store has the key generator, the key for the name value is generated automatically.
...And 5 more matches
MediaDevices.getUserMedia() - Web APIs
the following requests both audio and video without any specific requirements: { audio:
true, video:
true } if
true is specified for a media type, the resulting stream is required to have that type of track in it.
...the following expresses a preference for 1280x720 camera resolution: { audio:
true, video: { width: 1280, height: 720 } } the browser will try to honour this, but may return other resolutions if an exact match is not available, or the user overrides it.
...the following demands a minimum resolution of 1280x720: { audio:
true, video: { width: { min: 1280 }, height: { min: 720 } } } if no camera exists with this resolution or higher, then the returned promise will be rejected with overconstrainederror, and the user will not be prompted.
...And 5 more matches
Slottable - Web APIs
3edge full support 79firefox full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
...— 59disabled disabled until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
... full support 53firefox android full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
...And 5 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
for types gl.byte and gl.short, normalizes the values to [-1, 1] if
true.
... for types gl.unsigned_byte and gl.unsigned_short, normalizes the values to [0, 1] if
true.
...note the use of
true because webgl expects our data to be in little-endian.
...And 5 more matches
XRWebGLLayerInit - Web APIs
properties alpha optional the frame buffer's color buffer will be established with an alpha channel if the alpha boolean property is
true.
...the default value is
true.
... antialias optional a boolean value which is
true if anti-aliasing is to be used when rendering in the context; otherwise false.
...And 5 more matches
ARIA: tab role - Accessibility
<button role="tab" aria-selected="
true" aria-controls="tabpanel-id" id="tab-id">tab label</button> description an element with the tab role controls the visibility of an associated element with the tabpanel role.
... when working with elements with the tab role, when they are selected or active, they should have their aria-selected attribute set to
true, otherwise it should be set to false.
... when a tab is selected or active, its controlled tabpanel should have its aria-expanded and hidden attributes set to
true, otherwise they should be set to false.
...And 5 more matches
ARIA: listbox role - Accessibility
all selected options have aria-selected set to
true.
... if that's an option element, then that would be the id of the most recently interacted with option, regardless of whether that option has an aria-selected value of
true or not.
... aria-multiselectable include and set to
true if the user can select more than one option.
...And 5 more matches
ARIA: textbox role - Accessibility
to create a multi-line text box which supports line breaks, as in an html <textarea>, set aria-multiline="
true".
... <!-- simple text input field --> <div id="txtboxlabel">enter your five-digit zipcode</div> <div role="textbox" contenteditable="
true" aria-placeholder="5-digit zipcode" aria-labelledby="txtboxlabel"></div> <!-- multi-line text area --> <div id="txtboxmultilinelabel">enter the tags for the article</div> <div role="textbox" contenteditable="
true" aria-multiline="
true" aria-labelledby="txtboxmultilinelabel" aria-required="
true"></div> semantic elements are more concise and require no javascript to support textbox features.
... <label for="txtbox">enter your five-digit zipcode</label> <input type="text" placeholder="5-digit zipcode" id="txtbox"/> <!-- multi-line text area --> <label for="txtboxmultiline">enter the tags for the article</label> <textarea id="txtboxmultiline" required></textarea> where a text field is read-only, indicated this by setting aria-readonly="
true" on the element.
...And 5 more matches
Using media queries - CSS: Cascading Style Sheets
a media query computes to
true when the media type (if specified) matches the device on which a document is being displayed and all media feature expressions compute as
true.
...nevertheless, its contents will not apply unless and until the result of the query changes to
true.
... 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.
...And 5 more matches
Iterators and generators - JavaScript
done this is
true if the last value in the sequence has already been consumed.
...after a terminating value has been yielded additional calls to next() should simply continue to return {done:
true}.
... while it is easy to imagine that all iterators could be expressed as arrays, this is not
true.
...And 5 more matches
Boolean - JavaScript
all other values, including any object, an empty array ([]), or the string "false", create an object with an initial value of
true.
... do not confuse the primitive boolean values
true and false with the
true and false values of the boolean object.
... any object of which the value is not undefined or null, including a boolean object whose value is false, evaluates to
true when passed to a conditional statement.
...And 5 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 objects ...
...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 5 more matches
OpenClose - Archive of obsolete content
the menu element has an open property which may be set to
true to open the menu, or false to close the menu.
... a simple example: somemenu.open =
true; this single line of code will open a menu referenced by the variable 'somemenu'.
...here is a complete example which uses a button to open a menu: <button label="open menu" oncommand="document.getelementbyid('editmenu').open =
true;"/> <menu id="editmenu" label="edit"> <menupopup> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </menu> this technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag.
...And 4 more matches
prefwindow - Archive of obsolete content
a
true value for this preference makes the preference window apply immediately the user choices, without waiting for the dialog to close with ok.
...this one can be safely omitted in xulrunner-based applications but you can override the default behavior (
true for mac os x and false for other platforms) setting it.
...if it is set to
true any changes to settings are supposed to be applied immediately.
...And 4 more matches
window - Archive of obsolete content
"your-lname" value="enter last name:"/> <textbox id="your-lname" value="hernandez"/> </hbox> <hbox> <button oncommand="alert('save!')"> <description>save</description> </button> </hbox> </vbox> </radiogroup> </groupbox> </vbox> </window> attributes accelerated type: booleanset this attribute to
true to allow hardware layer managers to accelerate the window.
... disablechrome type: boolean set this attribute to
true to disable chrome in the window.
... disablefastfindtype: booleanput disablefastfind="
true" on the root element of a xul document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document.
...And 4 more matches
NPClass - Archive of obsolete content
returns
true if the method exists, otherwise returns false.
...returns
true if invocation succeeded or false if an error occurred.
...returns
true if invocation succeeded or false if an error occurred.
...And 4 more matches
NPVariant - Archive of obsolete content
_getstringidentifier() npn_getstringidentifiers() npn_getintidentifier() npn_identifierisstring() npn_utf8fromidentifier() npn_intfromidentifier() macros plugin developers are not expected to directly manipulate or access the members of the npvariant instance, instead, the function npn_releasevariantvalue(), and the following macros are provided: npvariant_is_void() evaluates to
true if v is of type npvarianttype_void.
... npvariant_is_null() evaluates to
true if v is of type npvarianttype_null.
... npvariant_is_boolean() evaluates to
true if v is of type npvarianttype_bool.
...And 4 more matches
XForms Input Element - Archive of obsolete content
analogous widgets are <xhtml:input type="text"/> and <xul:textbox/> specific handling of attributes incremental - if "
true", the bound instance node will be updated on each character typed by the user.
... checkbox most often used when the form author only needs a simple '
true', 'false', '1', or '0' response from the user (xhtml/xul).
... specific handling of attributes incremental - if "
true" or this attribute is omitted from this element, then the instance node will be updated when the user checks or un-checks the checkbox.
...And 4 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
an example of this kind of usage for ie: <!-- ie only code --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="
true" /> </object> in the above example, the classid attribute that goes along with the object element points to a "clsid:" urn followed by the unique identifier of an activex control (in the above example, the string beginning with "d27...").
...here is an example of this usage, once again for the macromedia flash plugin: <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="
true" /> <p>you need flash -- get the latest version from <a href= "http://www.macromedia.com/downloads/">here.</a></p> </object> in the above example, application/x-shockwave-flash is the flash mime type, and will invoke the netscape-specific flash architecture in mozilla-based browsers.
... mime type for flash: <!-- usage will not work as intended --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="
true" /> <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myflashnscp"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="
true" /> <p>you need flash -- get the latest version from <a href="http://www.macromedia.com/downloads/"> here.</a></p> </...
...And 4 more matches
Desktop gamepad controls - Game development
then, if the buttons are available we loop through them; if the pressed property is set to
true, then we add them to the buttonspressed array for later processing.
... next, we'll consider the gamepadbuttonpressedhandler() function: function gamepadbuttonpressedhandler(button) { var press = false; for(var i=0; i<buttonspressed.length; i++) { if(buttonspressed[i] == button) { press =
true; } } 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.
...And 4 more matches
Responsive images - Learn web development
screen widths) and indicates what image size would be best to choose, when certain media conditions are
true — these are the hints we talked about earlier.
... a space the width of the slot the image will fill when the media condition is
true (480px) note: for the slot width, you may provide an absolute length (px, em) or a length relative to the viewport (vw), but not percentages.
... you may have noticed that the last slot width has no media condition (this is the default that is chosen when none of the media conditions are
true).
...And 4 more matches
A first splash into JavaScript - Learn web development
'red'; if(userguess < randomnumber) { loworhi.textcontent = 'last guess was too low!' ; } else if(userguess > randomnumber) { loworhi.textcontent = 'last guess was too high!'; } } guesscount++; guessfield.value = ''; } guesssubmit.addeventlistener('click', checkguess); function setgameover() { guessfield.disabled =
true; guesssubmit.disabled =
true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start new game'; document.body.append(resetbutton); resetbutton.addeventlistener('click', resetgame); } function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for(let i = 0 ; i < resetparas...
...for example, if you want to simply add a new text string to an existing one and return the result, you could do this: name += ' says hello!'; this is equivalent to name = name + ' says hello!'; when we are running
true/false tests (for example inside conditionals — see below) we use comparison operators.
... for example: operator name example === strict equality (is it exactly the same?) 5 === 2 + 4 // false 'chris' === 'bob' // false 5 === 2 + 3 //
true 2 === '2' // false; number versus string !== non-equality (is it not the same?) 5 !== 2 + 4 //
true 'chris' !== 'bob' //
true 5 !== 2 + 3 // false 2 !== '2' //
true; number versus string < less than 6 < 10 //
true 20 < 10 // false > greater than 6 > 10 // false 20 > 10 //
true conditionals returning to our checkguess() function, i think it's safe to say that we don't want it to just spit out a placeholder message.
...And 4 more matches
Creating our first Vue component - Learn web development
the first is a required property, which will have a value of
true.
... your component object should now look like this: <script> export default { props: { label: { required:
true, type: string }, done: { default: false, type: boolean } } }; </script> using registered props with these props defined inside the component object, we can now use these variable values inside our template.
... update the component object like so: export default { props: { label: { required:
true, type: string }, done: { default: false, type: boolean } }, data() { return { isdone: this.done }; } }; vue does a little magic here — it binds all of your props directly to the component instance, so we don’t have to call this.props.done.
...And 4 more matches
How to implement a custom autocomplete search component
* if removefromdb is set to
true, the value should be removed from * persistent storage as well.
... * if removefromdb is set to
true, the value should be removed from * persistent storage as well.
...mgr.unregisterfactorylocation(class_id, alocation); }, getclassobject: function(acompmgr, acid, aiid) { if (!aiid.equals(components.interfaces.nsifactory)) throw components.results.ns_error_not_implemented; if (acid.equals(class_id)) return simpleautocompletesearchfactory; throw components.results.ns_error_no_interface; }, canunload: function(acompmgr) { return
true; } }; // module initialization function nsgetmodule(acompmgr, afilespec) { return simpleautocompletesearchmodule; } starting in gecko 2.0, component registration has been changed, so you need to make the following changes: add an nsgetfactory() function: function nsgetfactory(cid) { if (cid.tostring().touppercase() != class_id.tostring().touppercase()) { throw compone...
...And 4 more matches
Addon
n, in string platformversion) overview of optional methods void uninstall() void canceluninstall() boolean hasresource(in string path) nsiuri getresourceuri(in string path) void getdatadirectory(in datadirectorycallback callback) required properties attribute type description appdisabled read only boolean
true if this add-on cannot be used in the application based on version compatibility, dependencies, and blocklisting.
... foreigninstall read only boolean
true or false depending on whether the add-on is a third party add-on installation or not.
... isactive read only boolean
true if the add-on is currently functional.
...And 4 more matches
AsyncTestUtils extended framework
a function should yield
true or return
true when the asynchronous driver should continue executing without stopping.
... a function that does not return anything (or returns undefined) and is not a generator is treated like a function that returned
true.
... manipulating messages setread(aberead) setread(
true) marks all the messages in the set as read, setread(false) marks them as unread.
...And 4 more matches
Gecko object attributes
applied to: listitem, option exposed in aria: aria-setsize live region attribues atomic
true when the entire region should be presented as a whole, when changes within it are considered important enough to automatically present.
... common widget attributes checkable
true when the widget is known to behave like a checkbox.
... applied to: any widget that accepts input exposed via aria: aria-datatype exposed in xforms: from boud instance node datatype draggable
true when the accessible object can be grabbed.
...And 4 more matches
Index
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.
... 141 ns ensure success xpcom, xpcom_macros macro 142 ns ensure
true xpcom, xpcom_macros macro 143 ns_abort_if_false this was removed in bug 1127201 144 ns_addref xpcom, xpcom_macros macro 145 ns_assertion xpcom, xpcom_macros macro 146 ns_ensure_arg_pointer xpcom, xpcom_macros macro 147 ns_error xpcom, xpcom_macros throws a assertion (ns_assertion) w...
...|
true| if this context should be allowed to run scripts, |false| otherwise.
...And 4 more matches
Components.utils.Sandbox
this parameter is an object with the following optional properties: freshzone if
true creates a new gc region separate from both the calling context's and the sandbox prototype's region.
... passing a content window object, setting wantxrays:
true (default) and using an extended principal provides a clean, isolated execution environment in which javascript code that needs web apis (such as accessing the window's dom) can be executed without interference from untrusted content code.
...default:
true.
...And 4 more matches
nsIEditorSpellCheck
return value returns
true if spell checking can be enabled.
...in spite of the name, this function checks the word you give it, returning
true if the word is misspelled.
...boolean checkcurrentword( in wstring suggestedword ); parameters suggestedword missing description return value
true if the specified word is misspelled; otherwise false.
...And 4 more matches
nsIMessenger
aasfile if
true a file picker is spawned with the option save the message as html, text, or eml.
...if set to
true the attachment is opened inside the message pane which in turn should trigger the helper app dialog.
...if set to
true the attachment is opened inside the message pane which in turn should trigger the helper app dialog.
...And 4 more matches
nsINavHistoryService
nsinavhistoryobserver observer); void runinbatchmode(in nsinavhistorybatchcallback acallback, in nsisupports aclosure); void importhistory(in nsifile file); astring getcharsetforuri(in nsiuri auri); astring setcharsetforuri(in nsiuri auri, in astring acharset); attributes attribute type description hashistoryentries boolean
true if there is any history.
... historydisabled boolean
true if history is disabled.
...this is
true of all images on a page, and the contents of the iframe.
...And 4 more matches
nsIParentalControlsService
in boolean aflag, in nsiuri asource, [optional] in nsifile atarget); boolean requesturioverride(in nsiuri atarget, [optional] in nsiinterfacerequestor awindowcontext); boolean requesturioverrides(in nsiarray atargets, [optional] in nsiinterfacerequestor awindowcontext); attributes attribute type description blockfiledownloadsenabled boolean
true if the current user account's parental controls restrictions include the blocking of all file downloads.
... loggingenabled boolean
true if the current user account has parental controls logging enabled.
... if this is
true, applications should log relevant events using log() method.
...And 4 more matches
nsIZipWriter
inqueue boolean
true if operations are being performed in the background queue, or false if background operations are not in progress.
... aqueue if
true, the operation is queued for later execution.
... aqueue if
true, the operation is queued for later execution.
...And 4 more matches
nsIAbCard/Thunderbird3
ismaillist boolean if ismaillist is
true then maillisturi will contain the uri of the associated mail list.
... maillisturi string if ismaillist is
true then maillisturi will contain the uri of the associated mail list.
...of particular note is that boolean variables are converted to integers as in c/c++ (
true is a non-zero value), so that false will be converted to a string of 0 and not false<code>.
...And 4 more matches
Address Book examples
this is currently
true in the case of ldap, but may be
true in other cases as well.
... formulate a boolean search string (see nsiabcard for built-in property names): var searchquery = "(or(primaryemail,bw,@v)(nickname,bw,@v)(and(ismaillist,=,
true)(notes,bw,@v)))"; searchquery = searchquery.replace(/@v/g, encodeuricomponent("mystr") the search queries use lisp syntax with operators enumerated in nsabquerystringtoexpression.cpp.
... adding a mailing list first create a mailing list object and initialize it: var maillist = components.classes["@mozilla.org/addressbook/directoryproperty;1"] .createinstance(components.interfaces.nsiabdirectory); maillist.ismaillist =
true; now fill in the details you want to store: maillist.dirname = "my mailing list"; maillist.listnickname = "nickname for list"; maillist.description = "list description"; add the cards you want to include in the list: for (let i = 0; i < numcards; i++) maillist.addresslists.appendelement(card[i], false); now save the list: var parentdirectory = ...; // an nsiabdirectory for the parent o...
...And 4 more matches
Using the CSS Painting API - Web APIs
registerpaint('headerhighlight', class { /* define if alphatransparency is allowed alpha is set to
true by default.
... 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.
... 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 included a seco...
...And 4 more matches
Advanced animations - Web APIs
var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2,
true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; ball.draw(); nothing special here, the ball is actually a simple circle and gets drawn with the help of the arc() method.
... var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2,
true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { raf = window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e)...
... <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2,
true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx...
...And 4 more matches
FileSystemDirectoryEntry.getDirectory() - Web APIs
fileerror.path_exists_err the create and exclusive options were both
true, indicating that the directory should be created but must not already exist, but the directory does in fact already exist.
... create optional if this property is
true, and the requested file or directory doesn't exist, the user agent should create it.
... exclusive optional if
true, and the create option is also
true, the file must not exist prior to issuing the call.
...And 4 more matches
FileSystemDirectoryEntry.getFile() - Web APIs
fileerror.path_exists_err the create and exclusive options were both
true, indicating that the file should be created but must not already exist, but the file does in fact already exist.
... create optional if this property is
true, and the requested file or directory doesn't exist, the user agent should create it.
... exclusive optional if
true, and the create option is also
true, the file must not exist prior to issuing the call.
...And 4 more matches
FileSystemFlags - Web APIs
methods which accept an options parameter of this type may specify zero or more of these flags as fields in an object, like this: datadirectoryentry.getdirectory("workspace", { create:
true }, function(entry) { }); here, we see that the create property is provided, with a value of
true, indicating that the directory should be created if it's not already there.
... properties create optional if this property is
true, and the requested file or directory doesn't exist, the user agent should create it.
... exclusive optional if
true, and the create option is also
true, the file must not exist prior to issuing the call.
...And 4 more matches
Drag Operations - Web APIs
to make other html elements draggable, three things must be done: set the draggable="
true" on the element that you wish to make draggable.
... <p draggable="
true" ondragstart="event.datatransfer.setdata('text/plain', 'this text may be dragged')"> this text <strong>may</strong> be dragged.
... </p> the draggable attribute is set to "
true", so this element becomes draggable.
...And 4 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.
... modifier keys on gecko when getmodifierstate() returns
true on gecko?
...event.getmodifierstate("accel") returns
true when at least one of keyboardevent.ctrlkey or keyboardevent.metakey is
true.
...And 4 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.ctrlkey read only returns a boolean that is
true if the ctrl key was active when the key event was generated.
... keyboardevent.iscomposing read only returns a boolean that is
true if the event is fired between after compositionstart and before compositionend.
...And 4 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
const constraints = { audio:
true, video:
true }; const config = { iceservers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfvideo = document.queryselector("video.selfview"); const remotevideo = document.queryselector("video.remoteview"); const signaler = new signalingchannel(); const pc = new rtcpeerconnection(config); this code also gets the <video> elements using the classes "selfview" and "remoteview"; these wil...
... the perfect negotiation logic now we get into the
true perfect negotiation logic, which functions entirely independently from the rest of the application.
... let makingoffer = false; pc.onnegotiationneeded = async () => { try { makingoffer =
true; await pc.setlocaldescription(); signaler.send({ description: pc.localdescription }); } catch(err) { console.error(err); } finally { makingoffer = false; } }; note that setlocaldescription() without arguments automatically creates and sets the appropriate description based on the current signalingstate.
...And 4 more matches
XRWebGLLayer() - Web APIs
the options available are: alpha optional the frame buffer's color buffer will be established with an alpha channel if the alpha boolean property is
true.
...the default value is
true.
... antialias optional a boolean value which is
true if anti-aliasing is to be used when rendering in the context; otherwise false.
...And 4 more matches
Border-radius generator - CSS: Cascading Style Sheets
ction inputslidermanager() { var subscribers = {}; var sliders = []; var inputcomponent = function inputcomponent(obj) { var input = document.createelement('input'); input.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...
...unsubscribe } })(); /** * ui-buttonmanager */ var buttonmanager = (function checkboxmanager() { var subscribers = []; var buttons = []; var checkbox = function checkbox(node) { var topic = node.getattribute('data-topic'); var state = node.getattribute('data-state'); var name = node.getattribute('data-label'); var align = node.getattribute('data-text-on'); state = (state === "
true"); var checkbox = document.createelement("input"); var label = document.createelement("label"); var id = 'checkbox-' + topic; checkbox.id = id; checkbox.setattribute('type', 'checkbox'); checkbox.checked = state; label.setattribute('for', id); if (name) { label.classname = 'text'; if (align) label.classname += ' ' + align; label.textcontent = name; } node.appe...
...var previewmousetracking = (function drag() { var active = false; var lastx = 0; var lasty = 0; var subscribers = []; var init = function init(id) { var elem = getelembyid(id); elem.addeventlistener('mousedown', dragstart, false); document.addeventlistener('mouseup', dragend, false); } var dragstart = function dragstart(e) { if (e.button !== 0) return; active =
true; lastx = e.clientx; lasty = e.clienty; document.addeventlistener('mousemove', mousedrag, false); } var dragend = function dragend(e) { if (e.button !== 0) return; if (active ===
true) { active = false; document.removeeventlistener('mousemove', mousedrag, false); } } var mousedrag = function mousedrag(e) { notify(e.clientx - lastx, e.clienty - lasty); ...
...And 4 more matches
Rich-Text Editing in Mozilla - Developer guides
similarly, setting contenteditable to "
true" allows you to make individual elements of a document editable.
...for it to work in internet explorer, the contenteditable attribute of the body tag needs to be set to "
true".
... figure 2 : first example html: <body contenteditable="
true" onload="load()"> javascript: function load(){ window.document.designmode = "on"; } example 2 the second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed.
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
web fonts (for cross-domain font usage in @font-face within css), so that servers can deploy
truetype fonts that can only be cross-site loaded and used by web sites that are permitted to do so.
...content on foo.example might contain javascript like this: const invocation = new xmlhttprequest(); const url = 'http://bar.other/resources/credentialed-content/'; function callotherdomain() { if (invocation) { invocation.open('get', url,
true); invocation.withcredentials =
true; invocation.onreadystatechange = handler; invocation.send(); } } line 7 shows the flag on xmlhttprequest that has to be set in order to make the invocation with cookies, namely the withcredentials boolean value.
...since this is a simple get request, it is not preflighted, but the browser will reject any response that does not have the access-control-allow-credentials:
true header, and not make the response available to the invoking web content.
...And 4 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
t 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 infinity, -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 spe...
... javascript has a boolean type, with possible values
true and false (both of which are keywords.) any value can be converted to a boolean according to the following rules: false, 0, empty strings (""), nan, null, and undefined all become false.
... all other values become
true.
...And 4 more matches
Grammar and types - JavaScript
in the following code, the variable input is not assigned a value, and the if statement evaluates to
true.
... if (
true) { var x = 5; } console.log(x); // x is 5 this behavior changes when using the let declaration (introduced in ecmascript 2015).
... if (
true) { let y = 5; } console.log(y); // referenceerror: y is not defined variable hoisting another unusual thing about variables in javascript is that you can refer to a variable declared later, without getting an exception.
...And 4 more matches
Array.prototype.some() - JavaScript
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).
... if such an element is found, some() immediately returns
true.
...And 4 more matches
Object.isSealed() - JavaScript
description returns
true if the object is sealed, otherwise false.
...object.preventextensions(empty); object.issealed(empty); // ===
true // the same is not
true of a non-empty object, // unless its properties are all non-configurable.
...object.defineproperty(hasprop, 'fee', { configurable: false }); object.issealed(hasprop); // ===
true // the easiest way to seal an object, of course, // is object.seal.
...And 4 more matches
Comparing Reflect and Object methods - JavaScript
reflect.defineproperty() returns
true if the property was defined on the object and false if it was not.
... n/a set() n/a reflect.set() returns
true if the property was set successfully on the object and false if it was not.
... deleteproperty() n/a reflect.deleteproperty() returns
true if the property was deleted from the object and false if it was not.
...And 4 more matches
instanceof - JavaScript
// defining constructors function c() {} function d() {} let o = new c() //
true, because: object.getprototypeof(o) === c.prototype o instanceof c // false, because d.prototype is nowhere in o's prototype chain o instanceof d o instanceof object //
true, because: c.prototype instanceof object //
true c.prototype = {} let o2 = new c() o2 instanceof c //
true // false, because c.prototype is nowhere in // o's prototype chain anymore o instanceof c d.prototype =...
... new c() // add c to [[prototype]] linkage of d let o3 = new d() o3 instanceof d //
true o3 instanceof c //
true since c.prototype is now in o3's prototype chain note that the value of an instanceof test can change based on changes to the prototype property of constructors.
...components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and returns
true if queryinterface succeeded.
...And 4 more matches
Index - XPath
18 boolean xslt, xslt_reference the boolean function evaluates an expression and returns
true or false.
... 22 contains xslt, xslt_reference the contains function determines whether the first argument string contains the second argument string and returns boolean
true or false.
... 26 element-available xslt, xslt_reference the element-available function determines if an element is available and returns
true or false.
...And 4 more matches
tabs - Archive of obsolete content
tabs.open({ url: "http://www.mysite.com", innewwindow:
true }); // open a new tab on active window in the background.
... tabs.open({ url: "http://www.mysite.com", inbackground:
true }); // open a new tab as an app tab and do something once it's open.
... tabs.open({ url: "http://www.mysite.com", ispinned:
true, onopen: function onopen(tab) { // do stuff like listen for content // loading.
...And 3 more matches
core/heritage - Archive of obsolete content
also, idiomatic sdk code does not uses optional new keywords, but you're free to use it in your add-on code: var fluffy = dog('fluffy'); // instatiation fluffy instanceof dog // =>
true fluffy instanceof class // =>
true as you could notice from example above classes created via class function by default inherits from a class itself.
...this.bark() : ''; } }); var tsuga = pet('labrador', 'tsuga'); tsuga instanceof pet // =>
true tsuga instanceof dog // =>
true tsuga.call('tsuga') // => 'ruff!
...ruff!' leo.instanceof labrador // =>
true leo.instanceof dog // =>
true also, you could use class function to subclass constructor functions that were not created by a class itself: var foo = class({ extends: labrador // ...
...And 3 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
moreover, code using eval is harder to parse for a human mind, is often pretty complex, and relies on assumptions that are not necessarily
true in the future or even now.
...settimeout("dosomething();", 100); addeventlistener("load", "myaddon.init(); myaddon.onload();",
true); setinterval(am_i_a_string_or_function_reference_qmark, 100); that in itself is certainly not elegant, but it may also become a security issue if you pass code that was externally retrieved (or at least contains bits of externally retrieved data): // do not use!
... addeventlistener("load", function() { myaddon.init(); myaddon.onload(); },
true); function doxhr() { //...
...And 3 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
conditionis
true : conditionisfalse; for example, to retrieve an element, you would use: function getelement(aid){ return (document.getelementbyid) ?
...if adeep is
true, it copies over the node's entire subtree.
...internet explorer is always in quirks mode, as it does not support
true xhtml.
...And 3 more matches
Supporting private browsing mode - Archive of obsolete content
var pbs = components.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.
...function privatebrowsinglistener() { this.init(); } privatebrowsinglistener.prototype = { _os: null, _inprivatebrowsing: false, // whether we are in private browsing mode _watcher: null, // the watcher object init : function () { this._inited =
true; this._os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); this._os.addobserver(this, "private-browsing", false); this._os.addobserver(this, "quit-application", false); try { var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.int...
...erfaces.nsiprivatebrowsingservice); this._inprivatebrowsing = pbs.privatebrowsingenabled; } catch(ex) { // ignore exceptions in older versions of firefox } }, observe : function (asubject, atopic, adata) { if (atopic == "private-browsing") { if (adata == "enter") { this._inprivatebrowsing =
true; if (this.watcher && "onenterprivatebrowsing" in this._watcher) { this.watcher.onenterprivatebrowsing(); } } else if (adata == "exit") { this._inprivatebrowsing = false; if (this.watcher && "onexitprivatebrowsing" in this._watcher) { this.watcher.onexitprivatebrowsing(); } } } else if (atopic == "quit-application") { this._os.removeobserver(this, "quit-app...
...And 3 more matches
Panels - Archive of obsolete content
to do this, set the noautohide attribute on the panel to
true.
... <panel id="search-panel" noautohide="
true"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> <button label="cancel" oncommand="this.parentnode.hidepopup();"/> </panel> because the panel can no longer be closed by clicking elsewhere, the panel should always provide a means to close the panel itself.
...for instance, to have the textbox initially focused in the example above: <panel id="search-panel" onpopupshown="document.getelementbyid('search').focus()"> to disable the adjusting of focus when a panel is opened, set the noautofocus attribute to
true: <panel noautofocus="
true"> this will cause the focus to remain on the element within the main window that has focus when the panel is opened.
...And 3 more matches
Special Condition Tests - Archive of obsolete content
the iscontainer attribute should be set to
true if you only want to match containers, and false if you only want to match non-containers.
...<button label="houses in my neighbourhood" type="menu" datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood"> <template> <rule iscontainer="
true"> <menupopup> <menu uri="rdf:*" label="rdf:http://purl.org/dc/elements/1.1/title"/> </menupopup> </rule> <rule> <menupopup> <menuitem uri="rdf:*" label="rdf:http://www.xulplanet.com/rdf/address"/> </menupopup> </rule> </template> </button> the only difference in the code in this example is that the order of the rules has been switched around,...
...since the iscontainer attribute is set to
true, the rule will match as long as the member value or child of the starting node is an rdf container.
...And 3 more matches
Tree Widget Changes - Archive of obsolete content
it should return
true if a drop is allowed on a row.
... <treecol type="checkbox"> you can then set or clear the checkbox for a particular cell in that column by setting the value attribute to
true, or leaving out the attribute.
... <treecell/> <treecell value="
true"/> you need to specify the checkbox image with css for the checkbox to display.
...And 3 more matches
Commands - Archive of obsolete content
example: toggling command disabled example 2 : source view <command id="cmd_openhelp" oncommand="alert('help');"/> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> <button label="disable" oncommand="document.getelementbyid('cmd_openhelp').setattribute('disabled','
true');"/> <button label="enable" oncommand="document.getelementbyid('cmd_openhelp').removeattribute('disabled');"/> in this example, both buttons use the same command.
...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.
... iscommandenabled (command) this method should return
true if the command is enabled, or false if it is disabled.
...And 3 more matches
Modifying a XUL Interface - Archive of obsolete content
if
true, all of the children are copied as well.
... this is done recursively, so for large tree structures make sure that this is desired before passing
true to the clonenode() function.
... here is an example: example 2 : source view <hbox height="400"> <button label="copy" oncommand="this.parentnode.appendchild(this.nextsibling.clonenode(
true));"/> <vbox> <button label="first"/> <button label="second"/> </vbox> </hbox> when the copy button is pressed..
...And 3 more matches
listbox - Archive of obsolete content
iblerow, getindexofitem, getitematindex, getnumberofvisiblerows, getrowcount, getselecteditem, insertitemat, invertselection, movebyoffset, removeitemat, removeitemfromselection, scrolltoindex, selectall, selectitem, selectitemrange, timedselect, toggleitemselection examples <listbox id="thelist"> <listitem label="ruby"/> <listitem label="emerald"/> <listitem label="sapphire" selected="
true"/> <listitem label="diamond"/> </listbox> <listbox id="thelist" rows="10" width="400"> <listhead> <listheader label="1ct gem" width="240"/> <listheader label="price" width="150"/> </listhead> <listcols> <listcol/> <listcol flex="1"/> </listcols> </listbox> var thelist = document.getelementbyid('thelist'); gems = [ {gem: "ruby", price: "$3,500 - $4,600"}, ...
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
...this feature may be disabled by setting this attribute to
true.
...And 3 more matches
menu - Archive of obsolete content
allowevents type: boolean if
true, events are passed to children of the element.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... open type: boolean for the menu type buttons, the open attribute is set to
true when the menu is open.
...And 3 more matches
menuitem - Archive of obsolete content
allowevents type: boolean if
true, events are passed to children of the element.
... autocheck type: boolean if this attribute is
true or left out, the checked state of the button will be switched each time the button is pressed.
...when autocheck is
true, the button type should be "checkbox" or "radio".
...And 3 more matches
tooltip - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } default type: boolean if
true, the tooltip is used as the default popup for displaying tooltips in the window.
...if this attribute is set to
true, this will not happen and the tooltip will only hide when the user moves the mouse to another element.
... page type: boolean setting the page attribute to
true will result in the tooltip being filled automatically as appropriate for a browser content area tooltip, i.e.
...And 3 more matches
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.
...-> <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.
...And 3 more matches
Old Proxy API - Archive of obsolete content
ng the value") receiver.name = val (if receiver inherits from a proxy and does not override name) set: function(receiver, name, val) -> boolean function(receiver, name, val) { var desc = this.getownpropertydescriptor(name); if (desc) { if ('writable' in desc) { if (desc.writable) { desc.value = val; this.defineproperty(name, desc); return
true; } else { return false; } } else { // accessor if (desc.set) { desc.set.call(receiver, val); return
true; } else { return false; } } } desc = this.getpropertydescriptor(name); if (desc) { if ('writable' in desc) { if (desc.writable) { // fall through } else { return false; } } els...
...e { // accessor if (desc.set) { desc.set.call(receiver, val); return
true; } else { return false; } } } this.defineproperty(name, { value: val, writable:
true, enumerable:
true, configurable:
true}); return
true; } receiver is either the proxy or an object that inherits from the proxy.
... typeof typeof anobjectproxy === "object" typeof afunctionproxy === "function" instanceof anobjectproxy instanceof c ===
true if and only if the prototype with which anobjectproxy was initialized equals or inherits from c.prototype afunctionproxy instanceof function ===
true common mistakes and misunderstanding when starting using proxies, there are often a few beginners' mistakes and misunderstandings: not implementing all traps.
...And 3 more matches
Implementing controls using the Gamepad API - Game development
both functions are fairly simple: connect: function(evt) { gamepadapi.controller = evt.gamepad; gamepadapi.turbo =
true; console.log('gamepad connected.'); }, the connect() function takes the event as a parameter and assigns the gamepad object to the gamepadapi.controller variable.
...we then set the turbo property to
true.
... connected: a boolean variable,
true if the device is connected.
...And 3 more matches
2D maze game with device orientation - Game development
ball = { _width: 320, _height: 480 }; ball.boot = function(game) {}; ball.boot.prototype = { preload: function() { this.load.image('preloaderbg', 'img/loading-bg.png'); this.load.image('preloaderbar', 'img/loading-bar.png'); }, create: function() { this.game.scale.scalemode = phaser.scalemanager.show_all; this.game.scale.pagealignhorizontally =
true; this.game.scale.pagealignvertically =
true; this.game.state.start('preloader'); } }; the main ball object is defined and we're adding two variables called _width and _height that are the width and the height of the game canvas — they will help us position the elements on the screen.
...pe = { create: function() { this.add.sprite(0, 0, 'screen-mainmenu'); this.gametitle = this.add.sprite(ball._width*0.5, 40, 'title'); this.gametitle.anchor.set(0.5,0); this.startbutton = this.add.button(ball._width*0.5, 200, 'button-start', this.startgame, this, 2, 0, 1); this.startbutton.anchor.set(0.5,0); this.startbutton.input.usehandcursor =
true; }, startgame: function() { this.game.state.start('howto'); } }; to create a new button there's add.button method with the following list of optional arguments: top absolute position on canvas in pixels.
...here’s the code from the create() function responsible for this: window.addeventlistener("deviceorientation", this.handleorientation,
true); we’re adding an event listener to the "deviceorientation" event and binding the handleorientation function which looks like this: handleorientation: function(e) { var x = e.gamma; var y = e.beta; ball._player.body.velocity.x += x; ball._player.body.velocity.y += y; }, the more you tilt the device, the more force is applied to the ball, therefore the faster it moves (the vel...
...And 3 more matches
Client-side storage - Learn web development
if it has been stored, this call will evaluate to
true; if not, it will be false.
... if it is
true, we display a personalized greeting, display the "forget" part of the form, and hide the "say hello" part of the form.
...evious handler: // setup the database tables if this has not already been done request.onupgradeneeded = function(e) { // grab a reference to the opened database let db = e.target.result; // create an objectstore to store our notes in (basically like a single table) // including a auto-incrementing key let objectstore = db.createobjectstore('notes_os', { keypath: 'id', autoincrement:
true }); // define what data items the objectstore will contain objectstore.createindex('title', 'title', { unique: false }); objectstore.createindex('body', 'body', { unique: false }); console.log('database setup complete'); }; this is where we define the schema (structure) of our database; that is, the set of columns (or fields) it contains.
...And 3 more matches
Componentizing our React app - Learn web development
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> </butto...
... putting all that together, your todo() function should read like this: export default function todo(props) { 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"> {props.name} </label> </div> <div classname="btn-group"> <button type="button" classname="btn"> edit <span classname="visually-hidden">{props.name}</span> </button> <button type="button" classname="btn btn__danger"> delete <span classname="visually-hidden">{props.n...
...the first (eat) should have a value of
true; the rest should be false: <todo name="eat" completed={
true} /> <todo name="sleep" completed={false} /> <todo name="repeat" completed={false} /> as before, we must go back to todo.js to actually use these props.
...And 3 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
to see the editing template, you will have to change the default isediting state from false to
true in your code for now; we will look at making the edit button toggle this in the next section!
...to start with, we want to call setediting() with a value of
true when a user presses the "edit" button in our viewtemplate, so that we can switch templates.
... update the "edit" button in the viewtemplate like so: <button type="button" classname="btn" onclick={() => setediting(
true)}> edit <span classname="visually-hidden">{props.name}</span> </button> now we'll add the same onclick handler to the "cancel" button in the editingtemplate, but this time we'll set isediting to false so that it switches us back to the view template.
...And 3 more matches
mozbrowserselectionstatechanged
its properties are: canselectall: a boolean indicating whether the select all command can be issued (
true) or not (false).
... cancut: a boolean indicating whether the cut command can be issued (
true) or not (false).
... cancopy: a boolean indicating whether the copy command can be issued (
true) or not (false).
...And 3 more matches
Midas
contentreadonly this command will make the editor readonly(
true)or editable(false).
... insertbronreturn
true/false selects whether pressing return inside a paragraph creates another paragraph or just inserts a <br> tag.
...by default (at least today), this is
true.
...And 3 more matches
NSS Sample Code Sample1
runtime keys as loaded from the files pk11symkey *menckey; pk11symkey *mmackey; }; server::server(const char *servername) : mservername(0), mwrappedenckey(0), mwrappedmackey(0), menckey(0), mmackey(0) { // copy the server name mservername = pl_strdup(servername); } server::~server() { if (mservername) pl_strfree(mservername); if (mwrappedenckey) secitem_freeitem(mwrappedenckey, pr_
true); if (mwrappedmackey) secitem_freeitem(mwrappedmackey, pr_
true); if (menckey) pk11_freesymkey(menckey); if (mmackey) pk11_freesymkey(mmackey); } int server::init() { int rv = 0; seckeyprivatekey *prvkey = 0; seckeypublickey *pubkey = 0; pk11slotinfo *slot = 0; pk11rsagenparams rsaparams; secstatus s; // see if there is already a private key with this name.
... rv = getprivatekey(&prvkey); if (rv == 0 && prvkey) goto done; rv = 0; // these could be parameters to the init function rsaparams.keysizeinbits = 1024; rsaparams.pe = 65537; slot = pk11_getinternalkeyslot(); if (!slot) { rv = 1; goto done; } prvkey = pk11_generatekeypair(slot, ckm_rsa_pkcs_key_pair_gen, &rsaparams, &pubkey, pr_
true, pr_
true, 0); if (!prvkey) { rv = 1; goto done; } // set the nickname on the private key so that it // can be found later.
...done; } pubkey = seckey_extractpublickey(keyinfo); if (!pubkey) { rv = 1; goto done; } // export the encryption 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 = seci...
...And 3 more matches
NSS PKCS11 Functions
returns the function returns one of these values: if the slot is implemented in hardware, pr_
true.
...returns the function returns one of these values: if token is available, pr_
true.
...returns the function returns one of these values: if slot is read-only, pr_
true.
...And 3 more matches
pkfnc.html
returns the function returns one of these values: if the slot is implemented in hardware, pr_
true.
... returns the function returns one of these values: if token is available, pr_
true.
... returns the function returns one of these values: if slot is read-only, pr_
true.
...And 3 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.
... bool hasdefined(unsigned i) const returns
true if the i-th zero-indexed argument is present and is not undefined.
... bool isconstructing() const returns
true if the function is called via new.
...And 3 more matches
JS_DeleteProperty2
on success, *succeeded receives false if the property was not deleted because it is permanent and
true otherwise.
... description js_deleteproperty2 removes a specified property, name, from an object, obj, and stores
true or false in *succeeded.
...then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to
true and obj's jsclass.delproperty hook is called (which may change *succeeded).
...And 3 more matches
Parser API
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.
... if the generator flag is
true, the function is a generator function, i.e., contains a yield expression in its body (other than in a nested function).
... if the expression flag is
true, the function is an expression closure and the body field is an expression.
...And 3 more matches
Finishing the Component
(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", weblock_contractid, pr_
true, pr_
true, &previous); if (previous) nsmemory::free(previous); rv = catman->addcategoryentry("content-policy", "weblock", weblock_contractid, pr_
true, pr_
true, &previo...
...if the scheme isn't "http", "https", or "ftp", it immediately returns
true, which continues the loading process unblocked.
...if they match, the component allows the load to continue by returning
true.
...And 3 more matches
nsIClipboardCommands
return value
true if an image is selected, false otherwise.
...return value
true if an image is selected, false otherwise.
...return value
true if a link is selected, false otherwise.
...And 3 more matches
nsILocalFileMac
if the file object is an alias and followlinks is
true, returns the target of the alias.
...if the file object is an alias and followlinks is
true, returns the target of the alias.
...if the file object is an alias and followlinks is
true, returns the target of the alias.
...And 3 more matches
nsIMsgMessageService
amovemessage set to
true if you want the message to be moved.
... amovemessage set to
true if you want the message to be moved.
...set to
true if you want the message appended at the end of the file.
...And 3 more matches
nsIProcess
isrunning boolean
true if the process is running, otherwise false.
... void run( in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); parameters blocking if
true, this method will block until the process terminates; if false, the method returns immediately.
... holdweak optional if
true, a weak reference is used to hold the observer.
...And 3 more matches
nsIWindowsRegKey
return value this method returns
true if the key has changed and false otherwise.
... return value
true if the key has a child by the given name.
... return value
true if the key has a value by the given name.
...And 3 more matches
Styling the Folder Pane
hasunreadmessages-
true afolder.getnumunread(false) > 0 indicates that the folder (but not subfolders) has unread messages.
... isserver-
true afolder.isserver indicates that the folder is a root folder (one that represents a server).
... issecure-{
true, false} afolder.server.issecure indicates whether or not the connection to the server will be secure.
...And 3 more matches
ByteLengthQueuingStrategy - Web APIs
tegy experimentalchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to
true) and the javascript.options.streams preference (needs to be set to
true).
...droid full support 59chrome android full support 59firefox android full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to
true) and the javascript.options.streams preference (needs to be set to
true).
...ctor experimentalchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to
true) and the javascript.options.streams preference (needs to be set to
true).
...And 3 more matches
CountQueuingStrategy - Web APIs
tegy experimentalchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to
true) and the javascript.options.streams preference (needs to be set to
true).
...droid full support 59chrome android full support 59firefox android full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to
true) and the javascript.options.streams preference (needs to be set to
true).
...ctor experimentalchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to
true) and the javascript.options.streams preference (needs to be set to
true).
...And 3 more matches
DirectoryEntrySync - Web APIs
var fileentry = fs.root.getfile('seekrits.txt', {create:
true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system.
... var direntry = fs.root.getdirectory('superseekrit', {create:
true}); method overview directoryreadersync createreader () raises (fileexception); fileentrysync getfile (in domstring path, in optional flags options) raises (fileexception); directoryentrysync getdirectory (in domstring path, in optional flags options) raises (fileexception); void removerecursively () raises (fileexception); methods createreader() creates a new directoryreadersync to read entries from this directory.
... object literal condition result create:
true exclusive:
true path already exists an error is thrown.
...And 3 more matches
Document.execCommand() - Web APIs
note: only returns
true if part of a user interaction.
...this requires a boolean
true/false as the value argument.
...usecss must be
true for this to function.
...And 3 more matches
Element.classList - Web APIs
jproto, " ucl", { enumerable: 0, configurable: 0, writeable: 0, value: ele }); } else { ele.classlist=restokenlist, ele[" ucl"]=restokenlist, ele[" uclp"]=protoobj.prototype; } ele.attachevent( "onpropertychange", whenpropchanges ); } try { // much faster & cleaner version for ie8 & ie9: // should work in ie8 because element.prototype instanceof node is
true according to the specs window.object.defineproperty(window.element.prototype, "classlist", { enumerable: 1, get: function(val){ if (!hasownprop.call(this, "classlist")) polyfillclasslist(this); return this.classlist; }, configurable: 0, set: function(val){this.classname...
..."add" : "remove"](val), !!arguments[1]); var oldvalue = this.value; return (this.remove(oldvalue), oldvalue === this.value && (this.add(val),
true) /*|| false*/); }; if (!domtokenlistproto.replace || typeof testclass.replace("a", "b") !== "boolean") domtokenlistproto.replace = function(oldtoken, newtoken){ checkifvalidclasslistentry("replace", oldtoken), checkifvalidclasslistentry("replace", newtoken); var oldvalue = this.value; return (this.remove(oldtoken), this.value !== oldvalue && (th...
...is.add(newtoken),
true)); }; if (!domtokenlistproto.contains) domtokenlistproto.contains = function(value){ for (var i=0,len=this.length; i !== len; ++i) if (this[i] === value) return
true; return false; }; if (!domtokenlistproto.foreach) domtokenlistproto.foreach = function(f){ if (arguments.length === 1) for (var i = 0, len = this.length; i !== len; ++i) f( this[i], i, this); else for (var i=0,len=this.length,targ=arguments[1]; i !== len; ++i) f.call(targ, this[i], i, this); }; if (!domtokenlistproto.entries) domtokenlistproto.entries = function(){ var nextindex = 0, that = this; return {next: function() { return nextindex<that.length ?
...And 3 more matches
MediaStreamTrack - Web APIs
mediastreamtrack.enabled a boolean whose value of
true if the track is enabled, that is allowed to render the media source stream; or false if it is disabled, that is not rendering the media source stream but silence and blackness.
... 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.
... note: you can implement standard "mute" functionality by setting enabled to false, and unmute the media by setting it back to
true again.
...And 3 more matches
PublicKeyCredentialCreationOptions.extensions - Web APIs
if
true, the client outputs an array of strings containing the extensions which are supported by the authenticator.
...if
true, the client outputs an arraybuffer which contains a value uniquely identifying a user verification data record.
...if
true, the client outputs a coordinates object representing the geolocation of the authenticator.
...And 3 more matches
RTCPeerConnection.createOffer() - Web APIs
icerestart optional to restart ice on an active connection, set this to
true.
...if this value is
true, the remote peer will be offered to send audio data, even if the local side will not be sending audio data.
... in modern implementations, the presence of this member with a value
true, will ensure there is at least one transceiver set to receive audio that has not been stopped, and if there isn't one, one will be created.
...And 3 more matches
Using readable streams - Web APIs
if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done:
true }.
... next, we check whether done is
true.
... if done is not
true, we process the new chunk we’ve read (contained in the value property of the results object) and then call the pump() function again to read the next chunk.
...And 3 more matches
SubtleCrypto.importKey() - Web APIs
a json web key looks something like this (this is an ec private key): { "crv": "p-384", "d": "wouctu7nw4e8_7n5c1-xbjb4xqsb_lizhymsy8mggxuny6q8ncoh9xsiviwlffk_", "ext":
true, "key_ops": ["sign"], "kty": "ec", "x": "szrrxmyi8vwfjg1dpunbfcc9jzvjzefh7ulki1ukxaltd7rgwrcffxqygpcwu6aq", "y": "hhuag3ovdzer0uuqnd4pxhqtxp5idgdyhjhl-wlkjngjqaw0rngy5v29-av-ysew" }; examples note: you can try the working examples on github.
...*/ 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.
...contents); // convert from a binary string to an arraybuffer const binaryder = str2ab(binaryderstring); return window.crypto.subtle.importkey( "pkcs8", binaryder, { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", },
true, ["sign"] ); } subjectpublickeyinfo import this example imports an rsa public encryption key from a pem-encoded subjectpublickeyinfo object.
...And 3 more matches
Migrating from webkitAudioContext - Web APIs
the example below shows old code which downloads an audio file over the network, and then decoded it using createbuffer(): var xhr = new xmlhttprequest(); xhr.open("get", "/path/to/audio.ogg",
true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { var decodedbuffer = context.createbuffer(xhr.response, false); if (decodedbuffer) { // decoding was successful, do something useful with the audio buffer } else { alert("decoding the audio buffer failed"); } }; converting this code to use decodeaudiodata() is relatively simple, as can be seen below: var x...
...hr = new xmlhttprequest(); xhr.open("get", "/path/to/audio.ogg",
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.
...ontext can be ported to standards based audiocontext like below: // old webkitaudiocontext code: var osc = context.createoscillator(); osc.type = osc.sine; // sine waveform osc.type = osc.square; // square waveform osc.type = osc.sawtooth; // sawtooth waveform osc.type = osc.triangle; // triangle waveform osc.setwavetable(table); var iscustom = (osc.type == osc.custom); // iscustom will be
true // new standard audiocontext code: var osc = context.createoscillator(); osc.type = "sine"; // sine waveform osc.type = "square"; // square waveform osc.type = "sawtooth"; // sawtooth waveform osc.type = "triangle"; // triangle waveform osc.setperiodicwave(table); // note: setwavetable has been renamed to setperiodicwave!
...And 3 more matches
Window.find() - Web APIs
if
true, specifies a case-sensitive search.
...if
true, specifies a backward search.
...if
true, specifies a wrap around search.
...And 3 more matches
Using the aria-invalid attribute - Accessibility
true the value has failed validation.
... any value not in this vocabulary should be treated as
true.
... <input name="name" id="name" aria-required="
true" aria-invalid="false" onblur="checkvalidity('name', ' ', 'invalid name entered (requires both first and last name)');"/> <br /> <input name="email" id="email" aria-required="
true" aria-invalid="false" onblur="checkvalidity('email', '@', 'invalid e-mail address');"/> note that it is not necessary to validate the fields immediately on blur; the application could wait until the ...
...And 3 more matches
Alerts - Accessibility
here is a simple form: <form method="post" action="post.php"> <fieldset> <legend>please enter your contact details</legend> <label for="name">your name (required):</label> <input name="name" id="name" aria-required="
true"/> <br /> <label for="email">e-mail address (required):</label> <input name="email" id="email" aria-required="
true"/> <br /> <label for="website">website (optional):</label> <input name="website" id="website"/> </fieldset> <label for="message">please enter your message (required):</label> <br /> <textarea name="message" id="message" rows="5" cols="80" ...
... aria-required="
true"></textarea> <br /> <input type="submit" name="submit" value="send message"/> <input type="reset" name="reset" value="reset form"/> </form> checking for validity and notifying the user form validations consists of several steps: checking if the e-mail address or entered name are valid.
... if the above criteria is not met, the field’s aria-invalid attribute will be given a value of “
true”.
...And 3 more matches
Making content editable - Developer guides
<div contenteditable="
true"> this text can be edited by the user.
... </div> here's the above html in action: executing commands when an html element has contenteditable set to
true, the document.execcommand() method is made available.
...ccess"); user_pref("capability.policy.allowclipboard.clipboard.paste", "allaccess"); example: a simple but complete rich text editor <!doctype html> <html> <head> <title>rich text editor</title> <script type="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.
...And 3 more matches
Enumerability and ownership of properties - JavaScript
enumerable properties are those properties whose internal enumerable flag is set to
true, which is the default for properties created via simple assignment or via a property initializer (properties defined via object.defineproperty and such default enumerable to false).
... 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._enumerableandnotenu...
...merable); // 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...
...And 3 more matches
Indexed collections - JavaScript
let arr = [] arr[3.4] = 'oranges' console.log(arr.length) // 0 console.log(arr.hasownproperty(3.4)) //
true you can also populate an array when you create it: let myarray = new array('hello', myvar, 3.14159) // or let myarray = ['mango', 'apple', 'orange'] understanding length at the implementation level, javascript's arrays actually store their elements as standard object properties, using the array index as the property name.
...te that the elements of an array that are omitted when the array is defined are not listed when iterating by foreach, but are listed when undefined has been manually assigned to the element: let array = ['first', 'second', , 'fourth'] array.foreach(function(element) { console.log(element) }) // first // second // fourth if (array[2] === undefined) { console.log('array[2] is undefined') //
true } array = ['first', 'second', undefined, 'fourth'] array.foreach(function(element) { console.log(element) }) // first // second // undefined // fourth since javascript elements are saved as standard object properties, it is not advisable to iterate through javascript arrays using for...in loops, because normal elements and all enumerable properties will be listed.
... let a1 = ['a', 'b', 'c'] let a2 = a1.map(function(item) { return item.touppercase() }) console.log(a2) // logs ['a', 'b', 'c'] filter(callback[, thisobject]) returns a new array containing the items for which callback returned
true.
...And 3 more matches
Array.isArray() - JavaScript
array.isarray([1, 2, 3]); //
true array.isarray({foo: 123}); // false array.isarray('foobar'); // false array.isarray(undefined); // false syntax array.isarray(value) parameters value the value to be checked.
... return value
true if the value is an array; otherwise, false.
... description if the value is an array,
true is returned; otherwise, false is.
...And 3 more matches
Array - JavaScript
as a result, '2' and '02' would refer to two different slots on the years object, and the following example could be
true: console.log(years['2'] != years['02']) relationship between length and numerical properties a javascript array's length property and numerical properties are connected.
... array.isarray() returns
true if the argument is an array, or false otherwise.
... array.prototype.every() returns
true if every element in this array satisfies the testing function.
...And 3 more matches
Object.create() - JavaScript
this is especially
true when debugging, since common object-property converting/detecting utility functions may generate errors, or simply lose information (especially if using silent error-traps that ignore errors).
...ons shows the magnitude of the problem more clearly: > alert(oco) // shows [object object] > alert(ocn) // throws error: cannot convert object to primitive value > oco.tostring() // shows [object object] > ocn.tostring() // throws error: ocn.tostring is not a function > oco.valueof() // shows {} > ocn.valueof() // throws error: ocn.valueof is not a function > oco.hasownproperty("p") // shows "
true" > ocn.hasownproperty("p") // throws error: ocn.hasownproperty is not a function > oco.constructor // shows "object() { [native code] }" > ocn.constructor // shows "undefined" as said, these differences can make debugging even simple-seeming problems quickly go astray.
...missing object-method directly from the standard-object does not work: ocn = object.create( null ); // create "null" object (same as before) ocn.tostring = object.tostring; // since new object lacks method then try assigning it directly from standard-object > ocn.tostring // shows "tostring() { [native code] }" -- missing method seems to be there now > ocn.tostring == object.tostring // shows "
true" -- method seems to be same as the standard object-method > ocn.tostring() // error: function.prototype.tostring requires that 'this' be a function adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is really the cause of all these problems) and one cannot be directly added: ocn = object.crea...
...And 3 more matches
Reflect - JavaScript
returns a boolean that is
true if the property was successfully defined.
...returns a boolean that is
true if the target is extensible.
...returns a boolean that is
true if the update was successful.
...And 3 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.
... const str = 'hello world!'; const result = /^hello/.test(str); console.log(result); //
true the following example logs a message which depends on the success of the test: function testinput(re, str) { let midstring; if (re.test(str)) { midstring = 'contains'; } else { midstring = 'does not contain'; } console.log(`${str} ${midstring} ${re.source}`); } using test() on a regex with the "global" flag when a regex has the global flag set, test() will advance the last...
...And 3 more matches
Logical AND (&&) - JavaScript
the logical and (&&) operator (logical conjunction) for a set of operands is
true if and only if all of its operands are
true.
... syntax expr1 && expr2 description if expr1 can be converted to
true, returns expr2; else, returns expr1.
... if a value can be converted to
true, the value is so-called truthy.
...And 3 more matches
Logical OR (||) - JavaScript
the logical or (||) operator (logical disjunction) for a set of operands is
true if and only if one or more of its operands is
true.
... syntax expr1 || expr2 description if expr1 can be converted to
true, returns expr1; else, returns expr2.
... if a value can be converted to
true, the value is so-called truthy.
...And 3 more matches
Interacting with page scripts - Archive of obsolete content
to do this, add an option called “unsafe-content-script” under the “permissions” key in package.json, and set it to
true.
... "permissions": { "unsafe-content-script":
true } this is only a temporary migration aid, and will be removed eventually.
...cript> </body> </html> the content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event = new customevent("addon-message", { bubbles:
true, detail: greeting }); document.documentelement.dispatchevent(event); } finally, the page script "page-script.js" listens for the message and logs the greeting to the web console: window.addeventlistener("addon-message", function(event) { console.log(event.detail.greeting); }, false); after firefox 30: clone the message object this technique depends on being able to share the message pay...
...And 2 more matches
places/bookmarks - Archive of obsolete content
base // and store the emitter let emitter = save(bookmark); // listen for events emitter.on("data", function (saved, inputitem) { // on a "data" event, an item has been updated, passing in the // latest snapshot from the server as `saved` (with properties // such as `updated` and `id`), as well as the initial input // item as `inputitem` console.log(saved.title === inputitem.title); //
true console.log(saved !== inputitem); //
true console.log(inputitem === bookmark); //
true }).on("end", function (saveditems, inputitems) { // similar to "data" events, except "end" is an aggregate of // all progress events, with ordered arrays as `saveditems` // and `inputitems` }); creating several bookmarks with a new group let { bookmark, group, save } = require("sdk/places/bookmarks"...
... 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.
... deleting items: to delete a bookmark item, pass in a bookmark item with a property remove set to
true.
...And 2 more matches
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
<window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarname.label;" accesskey="&xulschoolhello.toolbar.accesskey;" customizable="
true" mode="icons" context="toolbar-context-menu" defaultset="xulschoolhello-hello-world-button" insertbefore="personaltoolbar" /> </toolbox> </window> (note for mac os x: <window id="main-window"> and </window> are not required) our toolbar is added as a child of the toolbox element in the main browser window.
...you should normally set this to
true, unless you have strong reasons not to want users changing your toolbar.
...*/ toolbarbutton.xulschoolhello-toolbarbutton, window:not([active="
true"]) toolbarbutton.xulschoolhello-toolbarbutton, toolbar[iconsize="small"] toolbarbutton.xulschoolhello-toolbarbutton { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png"); } #xulschoolhello-hello-world-button { -moz-image-region: rect(0px, 16px, 16px, 0px); } mac os x: /* the second and third selectors at the bottom are necessary to prevent conflicts with installed the...
...And 2 more matches
Index - Archive of obsolete content
from there you call editingsession->makewindoweditable(domwindow, editortype, pr_
true).
... 803 clicktoscroll clicktoscroll, if
true, the arrows must be clicked to scroll the scrollbox content.
... 1820 appendchild node appendchild ( node newchild ) 1821 arrowscrollbox xul elements, xul reference clicktoscroll, if
true, the arrows must be clicked to scroll the scrollbox content.
...And 2 more matches
Microsummary XML grammar reference - Archive of obsolete content
child elements: <condition> (optional) an xpath boolean expression along with a conditional interval of time, in minutes, that must elapse between updates if the expression evaluates to
true.
...if the expression evaluates to
true, firefox applies that element's interval and stops processing child elements.
... if there are no <condition> child elements, or if none of their expressions evaluate to
true, firefox applies the value of the <update> element's interval attribute.
...And 2 more matches
Building accessible custom components in XUL - Archive of obsolete content
<code> var gfocuscell = null; function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('focus', spreadsheet_focus,
true); spreadsheet.addeventlistener('click', spreadsheet_click,
true); } function spreadsheet_focus(e) { if (e.target.tagname == 'grid') { if (!gfocuscell) { gfocuscell = e.target.getelementsbytagname('label')[0]; } gfocuscell.focus(); } else { gfocuscell = e.target; } } function spreadsheet_click(e) { e.target.focus(); } </code> finall...
... <caption>cells really get focus</caption> further reading key-navigable custom dhtml widgets on mozilla.org adding keyboard navigation download stage-4.zip install stage-4.xpi
true accessibility requires complete keyboard navigability.
...<code> function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('keypress', spreadsheet_keypress,
true); spreadsheet.addeventlistener('focus', spreadsheet_focus,
true); spreadsheet.addeventlistener('click', spreadsheet_click,
true); } </code> with this new event handler and associated helper functions, we can navigate between cells and headers using the arrow keys.
...And 2 more matches
Document Object Model - Archive of obsolete content
in a browser context, the window is the global object, and the same is also
true for xul.
... <tree id="results" hidden="
true" flex="1"> .
...<splitter id="splitbar" resizeafter="grow" hidden="
true"/> <hbox> <progressmeter id="progmeter" value="50%" style="margin: 4px;" hidden="
true"/> we've added the hidden attribute and set the value to
true.
...And 2 more matches
More Tree Features - Archive of obsolete content
you do this by adding the container attribute to it as follows: <treeitem container="
true" /> this allows the user to click on the row that corresponds to the treeitem to expand and collapse the inner rows.
...example hierarchical tree the following is a simple example: example 1 : source view <tree rows="6"> <treecols> <treecol id="firstname" label="first name" primary="
true" flex="3" /> <treecol id="lastname" label="last name" flex="7" /> </treecols> <treechildren> <treeitem container="
true" open="
true"> <treerow> <treecell label="guys" /> </treerow> <treechildren> <treeitem> <treerow> <treecell label="bob" /> <treecell label="carpenter" /> </treerow> </treeitem> ...
...(note the mixed case.) if set to
true, the user may drag the column headers around to rearrange the order of the columns.
...And 2 more matches
Trees and Templates - Archive of obsolete content
example 1 : source <tree id="my-tree" flex="1" datasources="rdf:files" ref="nc:filesroot" flags="dont-build-content"> <treecols> <treecol id="name" label="name" primary="
true" flex="1"/> <splitter/> <treecol id="date" label="date" flex="1"/> </treecols> <template> <rule> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:http://home.netscape.com/nc-rdf#name"/> <treecell label="rdf:http://home.netscape.com/web-rdf#lastmodifieddate"/> </treerow> </treei...
... the final attribute, sortactive should be set to
true for one column, the one that you would like to be sorted by default.
... the following example changes the columns in the earlier example to incorporate the extra features: <treecols> <treecol id="name" label="name" flex="1" primary="
true" sortactive="
true" sortdirection="ascending" sort="rdf:http://home.netscape.com/nc-rdf#name"/> <splitter/> <treecol id="date" label="date" flex="1" sort="rdf:http://home.netscape.com/web-rdf#lastmodifieddate"/> </treecols> persisting column state one additional thing you might want to do is persist which column is currently sorted, so that it is remembered between sessions.
...And 2 more matches
XUL Questions and Answers - Archive of obsolete content
hidechrome="
true" doesn’t work on a mac?
...tml="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> <listbox rows="4"> <listhead> <listheader label="multi-column"/> </listhead> <listcols> <listcol flex="1"/> </listcols> <listitem> <listcell type="checkbox" value="1" label="vghkvghk"/> </listitem> <listitem> <listcell type="checkbox" value="2" label="vghjkvk" checked="
true"/> </listitem> <listitem> <listcell type="checkbox" value="3" label="hukfzgjcfj" disabled="
true"/> </listitem> </listbox> <listbox rows="4"> <listhead> <listheader label="single-column"/> </listhead> <listitem type="checkbox" value="1" label="vghkvghk"/> <listitem type="checkbox" value="2" label="vghjkvk" checked="
true"/> <listitem type="checkbox" value="3" label="...
...hukfzgjcfj" disabled="
true"/> </listbox> </window> list box handlers can only check for listitems not listcells.
...And 2 more matches
XUL controls - Archive of obsolete content
<checkbox label="show toolbar labels" checked="
true"/> more information about the checkbox element.
... menulist reference related elements: menupopup menuitem <menulist editable="
true"> an editable menulist is like a standard menulist except that the selected value is displayed in a textbox where it may be modified directly or values not in the popup list may be entered.
... <menulist editable="
true"> <menupopup> <menuitem label="elephants"/> <menuitem label="kangaroos"/> <menuitem label="bats" /> </menupopup> </menulist> more information about the editable menulist element.
...And 2 more matches
browser - Archive of obsolete content
, goback, goforward, gohome, gotoindex, loaduri, loaduriwithflags, reload, reloadwithflags, removeprogresslistener, stop, swapdocshells examples <!-- shows mozilla homepage inside a groupbox --> <groupbox flex="1"> <caption label="mozilla homepage"/> <browser type="content" src="http://www.mozilla.org" flex="1"/> </groupbox> attributes autocompleteenabled type: boolean set to
true to enable autocomplete of fields.
...if this attribute is set to
true or omitted, autoscroll will be enabled or depending on the user preference general.autoscroll.
... disablesecurity type: boolean set this attribute to
true to disable the security ui for this browser.
...And 2 more matches
richlistbox - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
...this feature may be disabled by setting this attribute to
true.
...if set to
true, the select event is never fired.
...And 2 more matches
tabs - Archive of obsolete content
dindex, tabbox, tabindex, tooltiptextnew, value, properties accessibletype, disabled, itemcount, selectedindex, selecteditem, tabindex, value, methods advanceselectedtab, appenditem, getindexofitem, getitematindex, insertitemat, removeitemat examples (example needed) attributes closebutton obsolete since gecko 1.9.2 type: boolean if this attribute is set to
true, the tabs row will have a "new tab" button and "close" button on the ends.
... disableclose type: boolean if this attribute is
true the close button will be disabled.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
...And 2 more matches
timepicker - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... readonly type: boolean if set to
true, then the user cannot change the value of the element.
...this should be used in combination with setting hideseconds to
true.
...And 2 more matches
where - Archive of obsolete content
if the condition is
true, the corresponding action body is generated; otherwise the result is ignored and no content is generated.
... attributes ignorecase, multiple, negate, rel, subject, value examples (example needed) attributes ignorecase type: boolean set to
true to indicate that the case does not matter when making comparisons.
... multiple type: boolean set to
true to indicate that the value contains multiple values separated by commas.
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
this statement is of the form <functionname>.proxy =
true.
... 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 </script> understanding the concept of operating context in jaxer is central to moving forward with the example application whi...
...email, message ) { // perform the same validation of the data server-side if( !validatecomments( name, email, message ) ) { throw "incomplete data was submitted."; } // assemble the string var s = "name: " + name + "<br/>" + "email: " + email + "<br/>" + "message: " + message + "<br/><br/>"; // append the entry to the log file jaxer.file.append( "dump.txt", s ); } formprocessor.proxy =
true; </script> the first function, formhandler, performs some first-level validation using the validatecomments function.
...And 2 more matches
Windows Media in Netscape - Archive of obsolete content
example 1: client-side detection scripts browser architecture supports: netscapeplugin windows media player installed:
true windows media scriptable: false windows media version: pluginversion a complete source code listing showing how that detection was done can be found here (devedge-temp).
... this is the example: needs to be embedded in wiki page (can it just be put here?) <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="media/preludesteel.wma"> your browser does not support the activex windows media player </object> the same markup (used above and shown below) will work in both ie and netscape 7.1.
... <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" /> your browser does not support the activex windows media player </object> the classid attribute references the clsid of windows media player 7 and above -- windows media player versions before 7 used a different clsid.
...And 2 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
for example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is
true, or skip the whole block if the condition is false.
... 36 boolean boolean, codingscripting, glossary, javascript, programming languages, data types in computer science, a boolean is a logical data type that can have only the values
true or false.
...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.
...And 2 more matches
Drawing graphics - Learn web development
let's try adding another arc: ctx.fillstyle = 'yellow'; ctx.beginpath(); ctx.arc(200, 106, 50, degtorad(-45), degtorad(45),
true); ctx.lineto(200, 106); ctx.fill(); the pattern here is very similar, but with two differences: we have set the last parameter of arc() to
true, meaning that the arc is drawn counterclockwise, which means that even though the arc is specified as starting at -45 degrees and ending at 45 degrees, we draw the arc around the 270 degrees not inside this portion.
... if you were to change
true to false and then re-run the code, only the 90 degree slice of the circle would be drawn.
...we also use onmousedown and onmouseup event handlers to change the value of pressed to
true when the mouse button is pressed, and back to false again when it is released.
...And 2 more matches
Componentizing our Svelte app - Learn web development
e // restores name to its initial value and editing = false // and exit editing mode } function onsave() { update({ name: name }) // updates todo name editing = false // and exit editing mode } function onremove() { dispatch('remove', todo) // emit remove event } function onedit() { editing =
true // enter editing mode } function ontoggle() { update({ completed: !todo.completed}) // updates todo status } updating the markup now we need to update our todo component's markup to call the above functions when the appropriate actions are taken.
...when it's
true, it should display the <input> field for editing the todo name, and the cancel and save buttons.
... when editing is
true, for example, svelte will show the update form; when it's false, it will remove it from the dom and add in the checkbox.
...And 2 more matches
Vue conditional rendering: editing existing todos - Learn web development
"button" class="btn" @click="oncancel"> cancel <span class="visually-hidden">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-f...
...this handler will set an isediting flag to
true.
... 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 item is being edited (or not).
...And 2 more matches
Debugging on Mac OS X
if you are using lldb on the command line (independently of xcode) and you will always run it from either the top source directory, the object directory or else the dist/bin subdirectory of the object directory, then adding the following setting to your $home/.lldbinit is sufficient: settings set target.load-cwd-lldbinit
true however, if you will run lldb from a different directory, or if you will be running it indirectly by debugging in xcode (xcode always runs lldb from "/"), then this setting will not help you.
...# therefore setting `settings set target.load-cwd-lldbinit
true` can't help us # without xcode providing that functionality.) # # the following works by setting a one-shot breakpoint to break on a function # that we know will both run early (which we want when we start first start the # app) and run frequently (which we want so that it will trigger asap if we # attach to an already running app).
...# breakpoint set --name nsthread::processnextevent --thread-index 1 --auto-continue
true --one-shot
true breakpoint command add -s python # this script that we run does not work if we try to use the global 'lldb' # object, since it is out of date at the time that the script runs (for # example, `lldb.target.executable.fullpath` is empty).
...And 2 more matches
Extending a Protocol
and the inverse is also
true, as you will soon see: pecho.idpl will need explicitly state that pwindowglobal.ipdl is managing it.
...deallocpechoparent(pechoparent* aactor) so, let's add: already_addrefed<echoparent> windowglobalparent::allocpechoparent() { puts("windowglobalparent::allocpechoparent was called"); refptr<echoparent> actor = new echoparent(); return actor.forget(); } bool windowglobalparent::deallocpechoparent( pechoparent* aactor) { refptr actor = dont_addref(static_cast(aactor)); return
true; } the "puts()" there will help us see what's going on once we get things going.
... open up dom/ipc/windowglobalchild.cpp and let's implement: allocpechochild() deallocpechochild(pechochild* aactor) already_addrefed<echochild> windowglobalchild::allocpechochild() { refptr<echochild> actor = new echochild(); return actor.forget(); } bool windowglobalchild::deallocpechochild(pechochild* actor) { delete actor; return
true; } and now finally, let's implement echochild.cpp and echoparent.cpp.
...And 2 more matches
JSPropertyOp
strict bool (jsstrictpropertyop only) if strict is
true, treating the assignment as strict mode code.
... if a jspropertyop or jsstrictpropertyop does nothing and returns
true, then property get, set, or add is unaffected.
...otherwise the callback must return
true, and the property operation proceeds.
...And 2 more matches
JS_AddArgumentFormatter
on success, it returns js_
true.
... fromjs jsbool js_
true if the conversion function should convert from jsval values to c values; js_false if the conversion function should convert from c values to jsval values.
... callback description the conversion function should return
true on success, and return false after reporting an error or detecting an already-reported error.
...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
Mozilla internal string guide
use this instead of testing string.length == 0 .equals(string) -
true if the given string has the same value as the current string.
... 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.
...this is useful when initially requesting best-case buffer size without yet knowing the
true size need.
...And 2 more matches
mozIThirdPartyUtil
for example, if auri is "http://mail.google.com/", achannel has a uri of "http://google.com/", and its parent is the topmost content window with a uri of "http://mozilla.com", the result will be
true.
... return value
true if auri is third party with respect to the channel uri or any of the uris associated with the same-type window hierarchy of the channel.
...boolean isthirdpartyuri( in nsiuri afirsturi, in nsiuri aseconduri ); parameters afirsturi missing description aseconduri missing description return value
true if afirsturi is third party with respect to aseconduri.
...And 2 more matches
nsIAppShellService
attributes attribute type description applicationprovidedhiddenwindow boolean return
true if the application hidden window was provided by the application.
... return value
true if a window was opened.
...to get an out of process element you want to communicate with via message manager, then append a browser element with remote attribute set to
true.
...And 2 more matches
nsIApplicationUpdateService
canapplyupdates boolean
true if the update service can download and install updates.
... cancheckforupdates boolean
true if the update service can check for updates.
... canupdate boolean
true if the update service is able to download and install updates.
...And 2 more matches
nsICookieManager2
aissecure
true if the cookie should only be sent over a secure connection.
... aishttponly
true if the cookie should only be sent to, and can only be modified by, an http connection.
... aissession
true if the cookie should exist for the current session only.
...And 2 more matches
nsIDOMNSHTMLDocument
return value
true if the command was recognized, false otherwise.
... return value returns
true if the command is supported and enabled, false otherwise.
... return value for stateful commands, returns
true if the command is in an indeterminate state, false otherwise.
...And 2 more matches
nsIFileView
to create an instance, use: var fileview = components.classes["@mozilla.org/filepicker/fileview;1"] .createinstance(components.interfaces.nsifileview); method overview void setdirectory(in nsifile directory); void setfilter(in astring filterstring); void sort(in short sorttype, in boolean reversesort); attributes attribute type description reversesort boolean if
true results will be sorted in ascending order.
... showhiddenfiles boolean if
true hidden files will be shown.
... showonlydirectories boolean if
true only directory entries will be returned.
...And 2 more matches
nsIFrameScriptLoader
if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is
true, then the script will also be loaded into any applicable new frames opened after the loadframescript() call.
... if this function is called on a chromemessagesender: it will load the frame script only into this chromemessagesender's frame aallowdelayedload should always be
true.
... for example: let windowmm = window.messagemanager; windowmm.loadframescript('data:,dump("foo\n");',
true); this will load a separate instance of the frame script into every tab open in the window associated with this window message manager.
...And 2 more matches
nsIMacDockSupport
void activateapplication( in boolean aignoreotherapplications ); parameters aignoreotherapplications if
true, the application is activated regardless of the state of other applications.
...in.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macmenuitem.setattribute('label', 'show most recent window'); macmenuitem.setattribute('id', 'mymacmenuitem'); macmenuitem.addeventlistener('command', function(){ var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); docksupport.activateapplication(
true); services.wm.getmostrecentwindow(null).focus() }) macmenu.appendchild(macmenuitem); var mainpopupset = win.document.getelementbyid('mainpopupset'); mainpopupset.appendchild(macmenu); let dockmenuelement = macmenu; //document.getelementbyid("menu_mac_dockmenu");66 let nativemenu = cc["@mozilla.org/widget/standalonenativemenu;1"].createinstance(ci.nsistandalonenativemenu); console.log('dockmen...
...notice the activateapplication(
true), if this is not done then firefox will not be activated.
...And 2 more matches
nsIMsgDBView
true if it is enabled.
... return values
true if the motion is available.
... void reloadmessage(); reloadmessagewithallparts() reload the currently shown message with fetchcompletemessage set to
true.
...And 2 more matches
nsINavBookmarksService
if ownsweak is
true, then aobserver must implement nsisupportsweakreference, and the bookmark service will keep a weak reference to the observer.
...if this is set to
true, ui will not allow the user to add, remove, or reorder children in this folder.
... return value returns
true if the folder is marked as read-only, otherwise returns false.
...And 2 more matches
nsINavHistoryContainerResultNode
childrenreadonly boolean false if the node's list of children can be modified (by adding or removing children, or rearranging them), or
true if the user interface should not allow the list of children to be altered.
...it's
true for non-folder nodes.
... containeropen boolean set this to
true to allow descent into this container.
...And 2 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 2 more matches
nsIProcessScriptLoader
if aallowdelayedload is
true, then the script will also be loaded into any new child processes created after the loadprocessscript() call.
... if this function is called on a chromemessagesender: it will load the process script only into this chromemessagesender's child process aallowdelayedload should always be
true.
... for example: let ppmm = services.ppmm.getchildat(1); ppmm.loadprocessscript('data:,dump("foo\n");',
true); parameters name type description aurl string url for the script to load.
...And 2 more matches
nsISHistoryListener
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.
... return value
true to allow the operation to proceed or false to cancel it.
...And 2 more matches
nsITaskbarPreviewButton
attributes attribute type description disabled boolean if
true, the button is disabled.
... dismissonclick boolean if
true, the array of previews should be dismissed when the button is clicked.
... hasborder boolean if
true, the taskbar should draw a border around this button's image.
...And 2 more matches
nsIURI
for example, comparing "http://foo.com:80/" and "http://foo.com/" will return
true.
... return value
true if the two uris represent the same location; otherwise false.
...for example, comparing "http://foo.com/#" and "http://foo.com/" or "http://foo.com/#aaa" and "http://foo.com/#bbb" will return
true.
...And 2 more matches
nsIUpdatePrompt
if the app.update.silent preference is
true or the user interface is already displayed the call will be a no-op.
...if background is
true (for example the download was not user initiated) and the app.update.silent preference is
true the call will be a no-op.
...background optional an optional parameter that, if provided and
true, presents a less-obtrusive, non-modal notification alert.
...And 2 more matches
nsMsgNavigationType
for example to move forward a message, you would call: // assuming gdbview is a global nsimsgdbview var resultid = new object(); var resultindex = new object(); var threadindex = new object(); gdbview.viewnavigate(components.interfaces.nsmsgnavigationtype.nextmessage, resultid, resultindex, threadindex,
true); the nsmsgnavigationtype interface is defined as a global variable in thunderbird: var nsmsgviewcommandtype = components.interfaces.nsmsgviewcommandtype; mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
...will wrap around if the wrap flag is set to
true.
...will wrap around if the wrap flag is set to
true.
...And 2 more matches
Plug-in Basics - Plugins
for example, this object element calls a plug-in that displays video: <object data="newave.avi" type="video/avi" width="320" height="200" autostart="
true" loop="
true"> </object> a hidden plug-in is a type of embedded plug-in that is not drawn on the screen when it is invoked.
...here's an example: <embed src="audiplay.aiff" type="audio/x-aiff" hidden="
true"> note: whether a plug-in is windowed or windowless is not meaningful if the plug-in is invoked with the hidden attribute.
... the embed element has the following syntax and attributes: <embed src="location" type="mimetype" pluginspage="instrurl" pluginurl="pluginurl" align="left"|"right"|"top"|"bottom" border="borderwidth" frameborder="no" height="height" width="width" units="units" hidden="
true|false" hspace="horizmargin" vspace="vertmargin" name="pluginname" palette="foreground"|"background" > ...
...And 2 more matches
Browser Console - Firefox Developer Tools
to enable it set the devtools.chrome.enabled preference to
true in about:config, or set the "enable browser chrome and add-on debugging toolboxes" (firefox 40 and later) option in the developer tool settings.
... here is an example on how to clear the contents of the browser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); hud.jsterm.clearoutput(
true); if you would like to access the content document of the browser console this can be done with the hudservice.
..." button it will clear the browser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); var clearbtn = hud.chromewindow.document.queryselector('.webconsole-clear-console-button'); clearbtn.addeventlistener('mouseover', function() { hud.jsterm.clearoutput(
true); }, false); bonus features available for add-on sdk add-ons, the console api is available automatically.
...And 2 more matches
Debugger.Script - Firefox Developer Tools
accessor properties of the debugger.script prototype object a debugger.script instance inherits the following accessor properties from its prototype: isgeneratorfunction
true if this instance refers to a jsscript for a function defined with a function* expression or statement.
... isasyncfunction
true if this instance refers to a jsscript for an async function, defined with an async function expression or statement.
...the object has the following properties: linenumber: the line number for which offset is an entry point columnnumber: the column number for which offset is an entry point isentrypoint:
true if the offset is a column entry point, as would be reported by getallcolumnoffsets(); otherwise false.
...And 2 more matches
AudioWorkletProcessor.process - Web APIs
returning
true forces the web audio api to keep the node alive, while returning false allows the browser to terminate the node if it is neither generating new audio data nor receiving data through its inputs that it is processing.
...an audioworkletprocessor implementing such a node should return
true from the process method as long as it produces an output.
...for example, take the audiobuffersourcenode — the processor behind such a node should return
true from the process method while the buffer is playing, and start returning false when the buffer playing has ended (there's no way to call play on the same audiobuffersourcenode again).
...And 2 more matches
Using the CSS Typed Object Model - Web APIs
btnwidth = allcomputedstyles.get('width') console.log( btnwidth ); // cssmathsum console.log( btnwidth.values ); // cssnumericarray {0: cssunitvalue, 1: cssunitvalue, length: 2} console.log( btnwidth.operator ); // 'sum' // csstransformvalue let transform = allcomputedstyles.get('transform'); console.log( transform ); // csstransformvalue {0: cssscale, 1: csstranslate, length: 2, is2d:
true} console.log( transform.length ); // 1 console.log( transform[0] ); // cssscale {x: cssunitvalue, y: cssunitvalue, z: cssunitvalue, is2d:
true} console.log( transform[0].x ); // cssunitvalue {value: 0.95, unit: "number"} console.log( transform[0].y ); // cssunitvalue {value: 0.95, unit: "number"} console.log( transform[0].z ); // cssunitvalue {value: 1, unit: "number"} console.log( tran...
...sform.is2d ); //
true // cssimagevalue let bgimage = allcomputedstyles.get('background-image'); console.log( bgimage ); // cssimagevalue console.log( bgimage.tostring() ); // url("https://mdn.mozillademos.org/files/16793/magicwand.png") // cssunparsedvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // let parsedunit = cssnumericvalue.parse( unit ); console.log( parsedunit ); console.log( parsedunit.unit ); console.log( parsedunit.value ); for this example to work, the example must be closed out here.
... let transform = allcomputedstyles.get('transform'); console.log( transform ); // csstransformvalue {0: cssscale, 1: csstranslate, length: 2, is2d:
true} console.log( transform.length ); // 1 console.log( transform[0] ); // cssscale {x: cssunitvalue, y: cssunitvalue, z: cssunitvalue, is2d:
true} console.log( transform[0].x ); // cssunitvalue {value: 0.95, unit: "number"} console.log( transform[0].y ); // cssunitvalue {value: 0.95, unit: "number"} console.log( transform[0].z ); // cssunitvalue {value: 1, unit: "number"} console.log( t...
...And 2 more matches
Cache.delete() - Web APIs
the delete() method of the cache interface finds the cache entry whose key is the request, and if found, deletes the cache entry and returns a promise that resolves to
true.
... if set to
true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... ignoremethod: a boolean that, when set to
true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false.
...And 2 more matches
KeyboardEvent.initKeyEvent() - Web APIs
ctrlkeyarg is a boolean that is
true if the virtual key to be generated is a combination of keys containing the ctrl key.
... altkeyarg is a boolean that is
true if the virtual key to be generated is a combination of keys containing the alt key.
... shiftkeyarg a boolean that is
true if the virtual key to be generated is a combination of keys containing the shift key.
...And 2 more matches
MouseEvent - Web APIs
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.
... mouseevent.metakey read only returns
true if the meta key was down when the mouse event was fired.
...And 2 more matches
MutationObserverInit.attributeFilter - Web APIs
if this property is specified, there's no need to also set attributes to
true, as it's implied.
... if the attributes permission is
true but no attributefilter is included in the options object, all attributes' values are watched for changes.
... if this property exists on the options object when the mutationobserver() constructor is used to create a new mutationobserver, attribute monitoring is enabled regardless of whether or not the attributes property is
true.
...And 2 more matches
MutationObserverInit.attributes - Web APIs
syntax var options = { attributes:
true | false } value a boolean value indicating whether or not to report through the callback any changes to the values of attributes on the node or nodes being monitored.
... if
true, the callback specified when observe() was used to start observing the node or subtree will be called any time one or more attributes have changed on observed nodes.
... subtree lets you specify whether to watch the target node and all of its descendants (
true), or just the target node (false).
...And 2 more matches
MutationObserverInit.characterData - Web APIs
so either pass directly a text node to the observe() method or you need to also set subtree:
true.
... syntax var options = { characterdata:
true | false } value a boolean value indicating whether or not to call the observer's callback function when textual nodes' values change.
... if
true, the callback specified when observe() was used to start observing the node or subtree is called any time the contents of a text node are changed.
...And 2 more matches
MutationObserverInit.subtree - Web APIs
the mutationobserverinit dictionary's optional subtree property can be set to
true to monitor the targeted node and all of its descendants.
... syntax var options = { subtree:
true | false } value a boolean value.
...changing this value to
true causes the entire subtree rooted at the specified target node to be monitored for the changes indicated by the other options.
...And 2 more matches
Navigator.onLine - Web APIs
the property returns a boolean value, with
true meaning online and false meaning offline.
... in chrome and safari, if the browser is not able to connect to a local area network (lan) or a router, it is offline; all other conditions return
true.
... so while you can assume that the browser is offline when it returns a false value, you cannot assume that a
true value necessarily means that the browser can access the internet.
...And 2 more matches
PaymentResponse - Web APIs
this option is only present when the requestpayeremail option is set to
true in the options parameter of the paymentrequest() constructor.
...this option is only present when the requestpayername option is set to
true in the options parameter of the paymentrequest() constructor.
...this option is only present when the requestpayerphone option is set to
true in the options parameter of the paymentrequest() constructor.
...And 2 more matches
RTCIceCandidateStats.deleted - Web APIs
if this value is
true, the candidate described by the rtcicecandidatestats object is no longer under consideration.
... dthe exact meaning varies depending on the type of candidate: local candidate a value of
true means the candidate has been deleted as described by rfc 5245: 8.3.
... host candidate a value of
true indicates that the candidate's network resources have been released.
...And 2 more matches
RTCOfferOptions.iceRestart - Web APIs
the icerestart property of the rtcofferoptions dictionary is a boolean value which, when
true, tells the rtcpeerconnection to start ice renegotiation.
... note: rather than manually creating and submitting an offer with icerestart set to
true, you should consider calling the rtcpeerconnection method restartice() instead.
... syntax var options = { icerestart:
trueorfalse }; value a boolean value indicating whether or not the rtcpeerconnection should generate new values for the connection's ice-ufrag and ice-pwd values, which will trigger ice renegotiation on the next message sent to the remote peer.
...And 2 more matches
Screen Capture API - Web APIs
a value of
true indicates a logical display surface is to be captured.
... mediatracksettings.logicalsurface a boolean value which is
true if the video being captured doesn't directly correspond to a single onscreen display area.
... mediatracksupportedconstraints mediatracksupportedconstraints.cursor a boolean which is
true if the user agent and device support the mediatrackconstraints.cursor constraint.
...And 2 more matches
SubtleCrypto.exportKey() - Web APIs
to export a key, the key must have cryptokey.extractable set to
true.
...*/ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, },
true, ["encrypt", "decrypt"] ).then((key) => { const exportbutton = document.queryselector(".raw"); exportbutton.addeventlistener("click", () => { exportcryptokey(key); }); }); pkcs #8 export this example exports an rsa private signing key as a pkcs #8 object.
...*/ window.crypto.subtle.generatekey( { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", },
true, ["sign", "verify"] ).then((keypair) => { const exportbutton = document.queryselector(".pkcs8"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.privatekey); }); }); subjectpublickeyinfo export this example exports an rsa public encryption key as a pem-encoded subjectpublickeyinfo object.
...And 2 more matches
ValidityState.patternMismatch - Web APIs
if the field supports the pattern attribute -- which means the <input> is of type text, tel, email, url, password, or search -- and the pattern value is set to a valid regular expression, if the value don't doesn't conform to the constraints set by the pattern value, the patternmismatch property will be
true.
... if the values are too long or too short, or contain characters that aren't digits, patternmismatch will be
true.
... when
true, the element matches the :invalid css pseudo-classes.
...And 2 more matches
WebGL2RenderingContext - Web APIs
webgl2renderingcontext.isquery() returns
true if a given object is a valid webglquery object.
... webgl2renderingcontext.issampler() returns
true if a given object is a valid webglsampler object.
... webgl2renderingcontext.issync() returns
true if the passed object is a valid webglsync object.
...And 2 more matches
Window.customElements - Web APIs
ment', mycustomelement); however, it is usually shortened to something like the following: customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(
true)); } } ); see our web-components-examples repo for more usage examples.
... full support 79firefox full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.customelements.enabled preference (needs to be set to
true).
...— 59disabled disabled until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true) and the dom.webcomponents.customelements.enabled preference (needs to be set to
true).
...And 2 more matches
XRWebGLLayer.ignoreDepthValues - Web APIs
the read-only xrwebgllayer property ignoredepthvalues is a boolean value which is
true if the session has been configured to ignore the values in the depth buffer while rendering the scene.
... syntax let ignoringdepthbuffer = xrwebgllayer.ignoredepthvalues; value a boolean value which is
true if the webgl context's depth buffer is being used while computing the locations of points in the 3d world.
... otherwise, if this is
true, the depth buffer's values are being used to assist in placing objects in the scene.
...And 2 more matches
ARIA live regions - Accessibility
the possible settings are: false or
true.
... aria-atomic="
true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g.
... <div id="clock" role="timer" aria-live="polite" aria-atomic="
true"></div> note: as observed, setting/updating the innerhtml again would cause the whole text to be read again, whether or not you set aria-atomic="
true", so the above clock example does not work as expected.
...And 2 more matches
ARIA: grid role - Accessibility
aria-multiselectable if aria-multiselectable is set to
true, multiple items in the grid can be selected.
... aria-readonly if the user can navigate the grid but not change the value or values of the grid, the aria-readonly should be set to
true.
... examples calendar example html <table role="grid" aria-labelledby="calendarheader" aria-readonly=
true> <caption id="calendarheader">september 2018</caption> <thead role="rowgroup"> <tr role="row"> <td></td> <th role="columnheader" aria-label="sunday">s</th> <th role="columnheader" aria-label="monday">m</th> <th role="columnheader" aria-label="tuesday">t</th> <th role="columnheader" aria-label="wednesday">w</th> <th role="columnheader" aria-label="thursd...
...And 2 more matches
WAI ARIA Live Regions/API Support - Developer guides
aria-relevant on ancestor element container-busy "
true" | "false" | "error" "false" the current changes are not yet complete.
... aria-busy on ancestor element container-atomic "
true" | "false" "false" is this change inside a region that should always be presented at once.
... if yes, member-of relation will point to the root of the region (see next section) aria-atomic on ancestor element member-of if container-atomic=
true, points to an ancestor accessible object (thus it is actually an accessible relation, not object attribute) not in atomic region if not provided points to the root of the atomic container that this object is in.
...And 2 more matches
Audio and Video Delivery - Developer guides
<source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <a href="audiofile.mp3">download audio</a> <object width="320" height="30" type="application/x-shockwave-flash" data="flashmediaelement.swf"> <param name="movie" value="flashmediaelement.swf" /> <param name="flashvars" value="controls=
true&isvideo=false&file=audiofile.mp3" /> </object> </audio> the process is very similar with video — just remember to set isvideo=
true in the flashvars value parameters.
... web audio api var context; var request; var source; try { context = new audiocontext(); request = new xmlhttprequest(); request.open("get","http://jplayer.org/audio/mp3/riomez-01-sleep_together.mp3",
true); request.responsetype = "arraybuffer"; request.onload = function() { context.decodeaudiodata(request.response, function(buffer) { source = context.createbuffersource(); source.buffer = buffer; source.connect(context.destination); // auto play source.start(0); // start was previously noteon }); }; request.send(); } catch(e) ...
... to grab the stream from your webcam, first set up a <video> element: <video id="webcam" width="480" height="360"></video> next, if supported connect the webcam source to the video element: if (navigator.mediadevices) { navigator.mediadevices.getusermedia({ video:
true, audio: false }) .then(function onsuccess(stream) { var video = document.getelementbyid('webcam'); video.autoplay =
true; video.srcobject = stream; }) .catch(function onerror() { alert('there has been a problem retreiving the streams - are you running on file:/// or did you disallow access?'); }); } else { alert('getusermedia is not supported in this browser.'); } to f...
...And 2 more matches
HTML attribute: pattern - HTML: Hypertext Markup Language
if a non-null value doesn't conform to the constraints set by the pattern value, the validitystate object's read-only patternmismatch property will be
true.
...if the pattern attribute isn't present, and the value doesn't match the expected syntax for that value type, the validitystate object's read-only typemismatch property will be
true.
... if the values are too long or too short, or contain characters that aren't digits, the patternmismatch will be
true.
...And 2 more matches
<input type="button"> - HTML: Hypertext Markup Language
disabling and enabling a button to disable a button, simply specify the disabled global attribute on it, like so: <input type="button" value="disable me" disabled> you can enable and disable buttons at run time by simply setting disabled to
true or false.
... in this example our button starts off enabled, but if you press it, it is disabled using button.disabled =
true.
... hidden code 1 <input type="button" value="enabled"> const button = document.queryselector('input'); button.addeventlistener('click', disablebutton); function disablebutton() { button.disabled =
true; button.value = 'disabled'; window.settimeout(function() { button.disabled = false; button.value = 'enabled'; }, 2000); } if the disabled attribute isn't specified, the button inherits its disabled state from its parent element.
...And 2 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
additional attributes in addition to the common attributes shared by all <input> elements, "checkbox" inputs support the following attributes: attribute description checked boolean; if present, the checkbox is toggled on by default indeterminate a boolean which, if present, indicates that the value of the checkbox is indeterminate rather than
true or false value the string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on checked a boolean attribute indicating whether or not this checkbox is checked by default (when the page loads).
... indeterminate if the indeterminate attribute is present on the <input> element defining a checkbox, the checkbox's value is neither
true nor false, but is instead indeterminate, meaning that it's state cannot be determined or stated in pure binary terms.
...this is set using the htmlinputelement object's indeterminate property via javascript (it cannot be set using an html attribute): inputinstance.indeterminate =
true; a checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.
...And 2 more matches
spellcheck - HTML: Hypertext Markup Language
it may have the following values:
true, which indicates that the element should be, if possible, checked for spelling errors; false, which indicates that the element should not be checked for spelling errors.
...this means that the explicit usage of one of the values
true or false is mandatory, and that a shorthand like <textarea spellcheck></textarea> is not allowed.
... the correct usage is <textarea spellcheck="
true"></textarea>.
...And 2 more matches
JavaScript data types and data structures - JavaScript
variables in javascript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types: let foo = 42; // foo is now a number foo = 'bar'; // foo is now a string foo =
true; // foo is now a boolean data and structure types the latest ecmascript standard defines nine types: six data types that are primitives, checked by typeof operator: undefined : typeof instance === "undefined" boolean : typeof instance === "boolean" number : typeof instance === "number" string : typeof instance === "string" bigint : typeof instance === "bigint" symbol ...
... boolean type boolean represents a logical entity and can have two values:
true and false.
...for example, +0 === -0 is
true.
...And 2 more matches
Details of the object model - JavaScript
if that argument converts to
true, the operator returns it.
...javascript provides a shortcut: the instanceof operator tests an object against a function and returns
true if the object inherits from the function prototype.
... for example, var f = new foo(); var is
true = (f instanceof foo); for a more detailed example, suppose you have the same set of definitions shown in inheriting properties.
...And 2 more matches
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.
...And 2 more matches
BigInt - JavaScript
type information when tested against typeof, a bigint will give "bigint": typeof 1n === 'bigint' //
true typeof bigint('1') === 'bigint' //
true when wrapped in an object, a bigint will be considered as a normal "object" type: typeof object(1n) === 'object' //
true operators the following operators may be used with bigints (or object-wrapped bigints): +, *, -, **, %.
... const expected = 4n / 2n // ↪ 2n const rounded = 5n / 2n // ↪ 2n, not 2.5n comparisons a bigint is not strictly equal to a number, but it is loosely so: 0n === 0 // ↪ false 0n == 0 // ↪
true a number and a bigint may be compared as usual: 1n < 2 // ↪
true 2n > 1 // ↪
true 2 > 2 // ↪ false 2n > 2 // ↪ false 2n >= 2 // ↪
true they may be mixed in arrays and sorted: const mixed = [4n, 6, -12n, 10, 4, 0, 0n] // ↪ [4n, 6, -12n, 10, 4, 0, 0n] mixed.sort() // default sorting behavior // ↪ [ -12n, 0, 0n, 10, 4n, 4, 6 ] mixed.sort((a, b) => a - b) // won't work since...
...1 : 0)) // ↪ [ -12n, 0, 0n, 4n, 4, 6, 10 ] note that comparisons with object-wrapped bigints act as with other objects, only indicating equality when the same object instance is compared: 0n === object(0n) // false object(0n) === object(0n) // false const o = object(0n) o === o //
true conditionals a bigint behaves like a number in cases where: it is converted to a boolean: via the boolean function; when used with logical operators ||, &&, and !; or within a conditional test like an if statement.
...And 2 more matches
Generator.prototype.next() - JavaScript
return value an object with two properties: done (boolean) has the value
true if the iterator is past the end of the iterated sequence.
...can be omitted when done is
true.
...xt() the following example shows a simple generator and the object that the next method returns: function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // "generator { }" g.next(); // "object { value: 1, done: false }" g.next(); // "object { value: 2, done: false }" g.next(); // "object { value: 3, done: false }" g.next(); // "object { value: undefined, done:
true }" using next() with a list function* getpage(pagesize = 1, list) { let output = []; let index = 0; while (index < list.length) { output = []; for (let i = index; i < index + pagesize; i++) { if (list[i]) { output.push(list[i]); } } yield output; index += pagesize; } } list = [1, 2, 3, 4, 5, 6, 7, 8] var page = getpage(3, list); /...
...And 2 more matches
Object.prototype.constructor - JavaScript
the value is only read-only for primitive values such as 1,
true, and "test".
... let o = {} o.constructor === object //
true let o = new object o.constructor === object //
true let a = [] a.constructor === array //
true let a = new array a.constructor === array //
true let n = new number(3) n.constructor === number //
true examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree).
...only
true, 1, and "test" will not be affected (as they have read-only native constructors).
...And 2 more matches
Object.getOwnPropertyDescriptor() - JavaScript
writable
true if and only if the value associated with the property may be changed (data descriptors only).
... configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
... enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
...And 2 more matches
Proxy - JavaScript
let validator = { set: function(obj, prop, value) { if (prop === 'age') { if (!number.isinteger(value)) { throw new typeerror('the age is not an integer'); } if (value > 200) { throw new rangeerror('the age seems invalid'); } } // the default behavior to store the value obj[prop] = value; // indicate success return
true; } }; const person = new proxy({}, validator); person.age = 100; console.log(person.age); // 100 person.age = 'young'; // throws an exception person.age = 300; // throws an exception extending constructor a function proxy could easily extend a constructor with a new constructor.
... let view = new proxy({ selected: null }, { set: function(obj, prop, newval) { let oldval = obj[prop]; if (prop === 'selected') { if (oldval) { oldval.setattribute('aria-selected', 'false'); } if (newval) { newval.setattribute('aria-selected', '
true'); } } // the default behavior to store the value obj[prop] = newval; // indicate success return
true; } }); let i1 = view.selected = document.getelementbyid('item-1'); //giving error here, i1 is null console.log(i1.getattribute('aria-selected')); // '
true' let i2 = view.selected = document.getelementbyid('item-2'); console.log(i1.getattribute('aria-selected')); ...
...// 'false' console.log(i2.getattribute('aria-selected')); // '
true' note: even if selected: !null, then giving oldval.setattribute is not a function value correction and an extra property the products proxy object evaluates the passed value and converts it to an array if needed.
...And 2 more matches
Set - JavaScript
examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) myset.add({a: 1, b: 2}) // o is referencing a different object, so this is okay myset.has(1) //
true myset.has(3) // false, since 3 has not been added to the set myset.has(5) //
true myset.has(math.sqrt(25)) //
true myset.has('some text'.tolowercase()) //
true myset.has(o) //
true myset.size // 5 myset.delete(5) // removes 5 from the set myset.has(5) // false, 5 has been removed myset.size // 4, since we just removed one value console...
...1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of myset.entries()) console.log(key) // convert set object to an array object, with array.from let myarr = array.from(myset) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an html document myset.add(document.body) myset.has(document.queryselector('body')) //
true // converting between set and array myset2 = new set([1, 2, 3, 4]) myset2.size // 4 [...myset2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new set([...set1].filter(x => set2.has(x))) // difference can be simulated via let difference = new set([...set1].filter(x => !set2.has(x))) // iterate set entries with foreach() myset.foreach...
...(function(value) { console.log(value) }) // 1 // 2 // 3 // 4 implementing basic set operations function issuperset(set, subset) { for (let elem of subset) { if (!set.has(elem)) { return false } } return
true } function union(seta, setb) { let _union = new set(seta) for (let elem of setb) { _union.add(elem) } return _union } function intersection(seta, setb) { let _intersection = new set() for (let elem of setb) { if (seta.has(elem)) { _intersection.add(elem) } } return _intersection } function symmetricdifference(seta, setb) { let _difference = new set(seta) for (let elem of setb) { if (_difference.has(elem)) { _difference.delete(elem) } else {...
...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
isNaN() - JavaScript
return value
true if the given value is nan; otherwise, false.
... 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('123abc'); //
true: parseint("123abc") is 123 but num...
...ber("123abc") is nan isnan(''); // false: the empty string is converted to 0 which is not nan isnan(' '); // false: a string with spaces is converted to 0 which is not nan // dates isnan(new date()); // false isnan(new date().tostring()); //
true // this is a false positive and the reason why isnan is not entirely reliable isnan('blabla'); //
true: "blabla" is converted to a number.
...And 2 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.
... if a value can be converted to
true, the value is so-called truthy.
...And 2 more matches
Strict equality (===) - JavaScript
if both operands are objects, return
true only if they refer to the same object.
... if both operands are null or both operands are undefined, return
true.
... booleans must be both
true or both false.
...And 2 more matches
function* - JavaScript
the done property of the object returned by it will be set to
true).
... when a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done:
true}.
... examples simple example function* idmaker() { var index = 0; while (
true) yield index++; } var gen = idmaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ...
...And 2 more matches
while - JavaScript
the while statement creates a loop that executes a specified statement as long as the test condition evaluates to
true.
...if this condition evaluates to
true, statement is executed.
... statement an optional statement that is executed as long as the condition evaluates to
true.
...And 2 more matches
Strict mode - JavaScript
the inverse is also
true: non-strict plus strict looks non-strict.
... (function() { 'use strict'; false.
true = ''; // typeerror (14).sailing = 'home'; // typeerror 'with'.you = 'far away'; // typeerror })(); simplifying variable uses strict mode simplifies how variable names map to particular variable definitions in the code.
...thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined: 'use strict'; function fun() { return this; } console.assert(fun() === undefined); console.assert(fun.call(2) === 2); console.assert(fun.apply(null) === null); console.assert(fun.call(undefined) === undefined); console.assert(fun.bind(
true)() ===
true); that means, among other things, that in browsers it's no longer possible to reference the window object through this inside a strict mode function.
...And 2 more matches
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.
...otherwise, it evaluates
true.
...And 2 more matches
Communicating With Other Scripts - Archive of obsolete content
this is
true as long as both context scripts have direct access to the same dom objects.
...ent script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event = document.createevent('customevent'); event.initcustomevent("addon-message",
true,
true, greeting); document.documentelement.dispatchevent(event); } finally, the page script "page-script.js" listens for the message and logs the greeting to the web console: window.addeventlistener("addon-message", function(event) { console.log(event.detail.greeting); }, false); after firefox 30: clone the message object this technique depends on being able to share the message payload...
...page script's scope using the global cloneinto() function: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var cloned = cloneinto(greeting, document.defaultview); var event = document.createevent('customevent'); event.initcustomevent("addon-message",
true,
true, cloned); document.documentelement.dispatchevent(event); } messaging from page script to content script sending messages using custom dom events from the page script to the content script is just the same, but in reverse.
...ain.org/talk.html", contentscriptfile: data.url("listen.js") }); the web page "talk.html" creates and dispatches a custom dom event, using initcustomevent()'s detail parameter to supply the payload: <!doctype html> <html> <head></head> <body> <script> function sendmessage() { var event = document.createevent('customevent'); event.initcustomevent("addon-message",
true,
true, { hello: 'world' }); document.documentelement.dispatchevent(event); } </script> <button onclick="sendmessage()">send message</button> </body> </html> finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute: window.addeventlistener("addon-message", function(event) { console.log(json.stringify(event.det...
simple-prefs - Archive of obsolete content
hidden a boolean value which, if present and set to
true, means that the preference won't appear in the add-ons manager interface, so users of your add-on won't be able to see or alter it.
... { "name": "myhiddeninteger", "type": "integer", "title": "how many?", "hidden":
true } your add-on's code will still be able to access and modify it, just like any other preference you define.
... { "description": "does it have tentacles?", "type": "bool", "name": "hastentacles", "value":
true, "title": "tentacles" } boolint displayed as a checkbox and stores an integer.
... a boolint is presented to the user as a checkbox, but instead of storing
true or false, the "on" or "off" checkbox states are mapped to integers using "on" or "off" properties in the specification.
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
attribute("value", "testvalue"); newitem.setattribute("label", "another popup menu item"); menupopup.appendchild(newitem); }; var jsontemplatebtn = ["xul:toolbarbutton", { id: "mytestbutton", class: "toolbarbutton-1", type: "menu", label: "test button label", tooltiptext: "test button tooltip", removable:
true, key: "mytestbutton123" }, [ "menupopup", { onpopupshowing: function(event) { addentrytopopup(this, document, window); } }, null ] ]; var capturednodes = {}; var toolbox = doc.getelementbyid("navigator-toolbox"); var palette = toolbox.palette; var domfragment = jsontodom(jsontemplatebtn, document, capture...
... * @param {boolean} allowstyle if
true, allow <style> nodes and * style attributes in the parsed fragment.
... * @param {boolean} isxml if
true, parse the fragment as xml.
... document.body.appendchild(parsehtml(document, xhr.responsetext,
true, xhr.channel.uri)); see also displaying web content in an extension without security issues how to create a dom tree node.textcontent node.appendchild() element.setattribute() document.createelement() document.createtextnode() original document information author(s): kris maglione last updated date: 2011-08-08 ...
Supporting per-window private browsing - Archive of obsolete content
to do this, observe the last-pb-context-exiting notification and set the data field of the nsisupportsprbool subject to
true.
...observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(function (asubject, atopic, adata) { asubject.queryinterface(components.interfaces.nsisupportsprbool); // if another extension has not already canceled entering the private mode if (!asubject.data) { /* you should display some user interface here */ asubject.data =
true; // cancel the operation } }, "last-pb-context-exiting", false); forcing a channel into private mode usually, network channels inherit the privacy status of the document that created them, which means that they work correctly most of the time.
...var channel = services.io.newchannel("http://example.org", null, null); channel.queryinterface(components.interfaces.nsiprivatebrowsingchannel); channel.setprivate(
true); // force the channel to be loaded in private mode similarly, xmlhttprequest objects created via createinstance(ci.nsixmlhttprequest) will often require explicit adjustment, since they have no context from which to derive a privacy status.
... var xhr = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(components.interfaces.nsixmlhttpreqeust); var channel = xhr.channel.queryinterface(components.interfaces.nsiprivatebrowsingchannel); channel.setprivate(
true); ...
allowevents - Archive of obsolete content
« xul reference home allowevents type: boolean if
true, events are passed to children of the element.
...by setting the allowevents attribute to
true, this special behavior is disabled, and the events are targeted the same as other elements.
...instead, the allowevents may be set to
true on a descendant instead.
...for the latter, the allowevents attribute is set to
true to have a click on the child button receive events instead of targeting all events at the menu.
spellcheck - Archive of obsolete content
« xul reference home spellcheck type: boolean if
true, spell checking is enabled by default for the text box; if false, spell checking is disabled by default.
... if not specified, this defaults to false the html the spellcheck attribute uses values of
true or false (you cannot simply add the spellcheck attribute to a given element): <!-- spellcheck everything!
... --> <input type="text" spellcheck="
true" /><br /> <textarea spellcheck="
true"></textarea> <div contenteditable="
true" spellcheck="
true">i am some content</div> <!-- spellcheck nothing!
... --> <input type="text" spellcheck="false" /><br /> <textarea spellcheck="false"></textarea> <div contenteditable="
true" spellcheck="false">i am some content</div> you can use spellcheck on input, textarea, and contenteditable elements.
command - Archive of obsolete content
ctrlkey read only boolean
true if the control key was down when the event was fired.
... shiftkey read only boolean
true if the shift key was down when the event was fired.
... altkey read only boolean
true if the alt key was down when the event was fired.
... metakey read only boolean
true if the meta key was down when the event was fired.
Getting File Information - Archive of obsolete content
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.
... nsifile.isexecutable() - returns
true if the file can be executed.
... nsifile.ishidden() - returns
true if the file is hidden.
appendNotification - Archive of obsolete content
if the return value from this function is not
true, then the notification is closed.
... isdefault - if
true, this is the default button.
... .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 = { ...
... popup: null }; buttons.push(button1); let button2 = { isdefault:
true, accesskey: "2", label: "button 2", callback: testnotificationbutton2callback, type: "", // if a popup, then must be: "menu-button" or "menu".
Floating Panels - Archive of obsolete content
a floating panel can be created using the panel element with at least two additional attributes as in the following example: <panel id="tools-panel" noautohide="
true" titlebar="normal"> <label control="name" value="name:"/> <textbox id="name"/> </panel> the noautohide attribute is used to indicate that the panel is not temporary.
... when set to
true, the popup will not close when the user clicks outside of it, nor when the user presses the escape key.
...a label for the titlebar may be set using the label attribute, as in the following example: <panel id="info-panel" noautohide="
true" titlebar="normal" label="image properties"> closing a floating panel unlike other panels, a floating panel does not close when clicking outside of it.
...<panel id="info-panel" noautohide="
true" titlebar="normal" label="image properties" close="
true"> the hidepopup method may be used to manually close a popup.
Adding Event Handlers - Archive of obsolete content
to show errors in chrome javascript, it is necessary to change the preference javascript.options.showinconsole to
true.
...by setting this value to
true, non-standard, poorly written, or syntax prone to cause logic errors are logged to the javascript console.
...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.
...finally, the last argument should be
true for capturing listeners.
button - Archive of obsolete content
autocheck type: boolean if this attribute is
true or left out, the checked state of the button will be switched each time the button is pressed.
...when autocheck is
true, the button type should be "checkbox" or "radio".
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... open type: boolean for the menu type buttons, the open attribute is set to
true when the menu is open.
dialog - Archive of obsolete content
ext/css"?> <dialog id="donothing" title="dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" buttonlabelcancel="cancel" buttonlabelaccept="save"> <dialogheader title="options" description="my preferences"/> <groupbox> <caption label="colour"/> <radiogroup> <radio label="red"/> <radio label="green" selected="
true"/> <radio label="blue"/> </radiogroup> <label value="nickname"/> <textbox/> </groupbox> </dialog> attributes activetitlebarcolor type: color string specify background color of the window's titlebar when it is active (foreground).
... buttondisabledaccept type: boolean if
true, the accept button is disabled.
...if it is set to
true any changes to settings are supposed to be applied immediately.
...the default setting of browser.preferences.instantapply currently is
true on linux and mac os and false on windows (which however might or might not change soon, see bug 738797 and bug 1037225).
listitem - Archive of obsolete content
cesskey, checked, command, crop, current, disabled, image, label, preference, selected, tabindex, type, value properties accesskey, accessible, checked, control, crop, current, disabled, image, label, selected, tabindex, value style classes listitem-iconic examples <listbox id="thelist"> <listitem label="ruby"/> <listitem label="emerald"/> <listitem label="sapphire" selected="
true"/> <listitem label="diamond"/> </listbox> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } current type: boolean this attribute will be set to
true if the listitem is the current item.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... selected type: boolean this property's value is
true if this element is selected, or false if it is not.
radio - Archive of obsolete content
attributes accesskey, command, crop, disabled, focused, group, image, label, selected, tabindex, value properties accesskey, accessibletype, control, crop, disabled, image, label, radiogroup, selected, tabindex, value examples <radiogroup> <radio id="orange" label="red" accesskey="r"/> <radio id="violet" label="green" accesskey="g" selected="
true"/> <radio id="yellow" label="blue" accesskey="b" disabled="
true"/> </radiogroup> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... focused type: boolean this attribute is
true if the element is focused.
... selected type: boolean this property's value is
true if this element is selected, or false if it is not.
radiogroup - Archive of obsolete content
attributes disabled, focused, preference, tabindex, value properties accessibletype, disabled, focuseditem, itemcount, selectedindex, selecteditem, tabindex, value methods appenditem, checkadjacentelement, getindexofitem, getitematindex, insertitemat, removeitemat examples <radiogroup> <radio id="orange" label="red"/> <radio id="violet" label="green" selected="
true"/> <radio id="yellow" label="blue"/> </radiogroup> attributes disabled type: boolean indicates whether the element is disabled or not.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... focused type: boolean this attribute is
true if the element is focused.
...if the argument dir is
true, the next radio button is selected.
toolbar - Archive of obsolete content
e, currentset, firstpermanentchild, lastpermanentchild, toolbarname, toolboxid methods insertitem style classes chromeclass-toolbar examples <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton id="nav-users" accesskey="u" label="users"/> <toolbarbutton id="nav-groups" accesskey="p" label="groups"/> <toolbarbutton id="nav-events" accesskey="e" label="events" disabled="
true"/> </toolbar> </toolbox> attributes autohide type: boolean when set to
true, the toolbar will be invisible unless the alt key is pressed by the user.
... customizable not in seamonkey 1.x type: boolean set this attribute to
true on toolbars that can be customized.
... grippyhidden seamonkey only type: boolean when set to
true, the grippy will be hidden.
...if the second argument is null, but the beforepermanent argument is
true, the item is added to the beginning of the toolbar before the first permanent item.
toolbarbutton - Archive of obsolete content
autocheck type: boolean if this attribute is
true or left out, the checked state of the button will be switched each time the button is pressed.
...when autocheck is
true, the button type should be "checkbox" or "radio".
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... open type: boolean for the menu type buttons, the open attribute is set to
true when the menu is open.
Debugging a XULRunner Application - Archive of obsolete content
/* debugging prefs */ pref("browser.dom.window.dump.enabled",
true); pref("javascript.options.showinconsole",
true); pref("javascript.options.strict",
true); pref("nglayout.debug.disable_xul_cache",
true); pref("nglayout.debug.disable_xul_fastload",
true); don't forget to change these preferences back to their defaults when you've finished debugging; leaving them as-is can significantly harm performance and usability.
...this will only work if the pref pref("browser.dom.window.dump.enabled",
true) is enabled.
...to show errors in chrome javascript, the pref pref("javascript.options.showinconsole",
true) must be set.
... debuggerserver.addbrowseractors("myxulrunnerappwindowtype"); } debuggerserver.openlistener(6000); for xulrunner version 37+ the code to enable the debugger has changed: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); debuggerserver.addbrowseractors(); debuggerserver.allowchromeprocess =
true; } let dbglistener=debuggerserver.createlistener(); dbglistener.portorpath=6000; dbglistener.open(); add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled",
true); in firefox, go to tools > web developer > connect...
NPFullPrint - Archive of obsolete content
syntax typedef struct _npfullprint { npbool pluginprinted; /*
true: print fullscreen */ npbool printone; /*
true: print one copy */ /* to default printer */ void* platformprint; /* platform-specific */ } npfullprint; fields the data structure has the following fields: pluginprinted determines whether the plug-in prints in full-page mode.
... values:
true: plug-in takes complete control of the printing process and prints full-page.
...
true: print single copy of page to the default printer.
...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.
-ms-accelerator - Archive of obsolete content
initial valuefalseapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete syntax /* the object is not a keyboard shortcut (the default) */ -ms-accelerator: false /* the object is a keyboard shortcut */ -ms-accelerator:
true values false the object is not a keyboard shortcut.
...
true the object is a keyboard shortcut.
... formal syntax false |
true examples this example uses the -ms-accelerator attribute in a <u> element to specify that the "n" in the <label> element is a keyboard shortcut.
... <!doctype html> <html> <head> <title>accelerator</title> </head> <body> <label for="oname"><u style="-ms-accelerator:
true; accelerator:
true">n</u>ame: </label> <input type="text" id="oname" size="25" accesskey="n" value="your name here" /> </body> </html> specifications not part of any specification.
Reference - Archive of obsolete content
--maian 05:41, 22 september 2005 (pdt) this is
true.
...which basicly says function != object alert(function instanceof object) //
true alert(object instanceof function) //
true alert(math instanceof object) //
true alert(math instanceof function) //false note that the methods and properties for object in this reference are also available for function and vice versa ...
...the reason object instanceof function evaluates to
true is because object can be used as a constructor function.
...this is why math instanceof object evaluates to
true, but math instanceof function does not.
Describing microformats in JavaScript - Archive of obsolete content
standard attributes are: plural a boolean value indicating that, if
true indicates that the property can have multiple values.
...this is only used if virtual is
true.
...the adr microformat is defined as follows: var adr_definition = { mfversion: 0.8, mfobject: adr, classname: "adr", properties: { "type" : { plural:
true, types: ["work", "home", "pref", "postal", "dom", "intl", "parcel"] }, "post-office-box" : { }, "street-address" : { plural:
true }, "extended-address" : { }, "locality" : { }, "region" : { }, "postal-code" : { }, "country-name" : { } } }; the properties are quite simple here.
...since the plural property is
true, multiple types can be specified.
RDF in Mozilla FAQ - Archive of obsolete content
by setting // ablocking to
true, we could force it to be synchronous, but this // is generally a bad idea, because your ui will completely lock up!
...refer to mozilla rdf back end architecture ds.assert(homepage, fv_quality, value,
true); ds.unassert(homepage, fv_quality, value,
true); how do i save back changes to an rdf/xml datasource?
...if (bookmarks.hasassertion( rdf.getresource("http://home.netscape.com/nc-rdf#bookmarksroot"), rdf.getresource("http://home.netscape.com/nc-rdf#child"), rdf.getresource("http://home.netscape.com/nc-rdf#personaltoolbarfolder"),
true) { // ...
...(shut down mozilla first since it overwrites your preferences file when you quit.) user_pref("signed.applets.codebase_principal_support",
true); mozilla will ask you if you want to grant the scripts in duplicates.xul permission to access xpconnect; respond in the affirmative.
Common causes of memory leaks in extensions - Extensions
however, while this is still
true, the window.setinterval() in the example originates from the outer chrome window (browser.xul) and not from the content window.
... window.addeventlistener("leaky", leakref,
true); // the following line still fails to avoid the leak, as usecapture differs // and removeeventlistener will not remove anything.
... unload(function() window.removeeventlistener("leaky", leakref,
true), window); } note: the unload() function is an external function which can be added in your add-on to easily provide a way to undo changes upon unloading of your add-on or a specific part/object.
...you may also specify ownsweak =
true in the call to nsiobserverservice.addobserver(), but that might require you to properly implement weak references as well.
Paddle and keyboard controls - Game development
the same pattern is
true for the second listener: keyup events will fire the keyuphandler() function (when the keys stop being pressed).
... add these to your code now, below the addeventlistener() lines: function keydownhandler(e) { if(e.key == "right" || e.key == "arrowright") { rightpressed =
true; } else if(e.key == "left" || e.key == "arrowleft") { leftpressed =
true; } } function keyuphandler(e) { if(e.key == "right" || e.key == "arrowright") { rightpressed = false; } else if(e.key == "left" || e.key == "arrowleft") { leftpressed = false; } } when we press a key down, this information is stored in a variable.
... the relevant variable in each case is set to
true.
...if the left cursor is pressed, then the leftpressed variable is set to
true, and when it is released, the leftpressed variable is set to false.
Visual typescript game engine - Game development
*/ private addson: addson = [ { name: "cache", enabled:
true, scriptpath: "externals/cacheinit.ts", }, { name: "hackertimer", enabled:
true, scriptpath: "externals/hack-timer.js", }, { name: "dragging", enabled:
true, scriptpath: "externals/drag.ts", }, ]; /** * @description this is main coordinary types of positions * can be "diametric-fullscreen" or "frame".
... * in other way keep it '
true'.
... */ private appusebroadcaster: boolean = false; /** * possible variant by default : * "register", "login" */ private startuphtmlform: string = "register"; private gamelist: any[]; /** * implement default gameplay variable's */ private defaultgameplaylevelname: string = "level1"; private autostartgameplay: boolean =
true; start the dependency system from app.ts the first game template is platformer.
... this.networkdeeplogs = false; this.rtcserverport = 12034; this.rtc3serverport = 12034; this.connectorport = 1234; this.domain = "192.168.0.14"; this.masterserverkey = "multi-platformer-sever1.maximum"; this.protocol = "http"; this.issecure = false; this.appuseaccountssystem =
true; this.appusevideochat =
true; this.databasename = "masterdatabase"; this.databaseroot = "mongodb://localhost:27017"; - the running server is easy : npm run rtc with this cmd: npm run rtc we run server.js and connector.ts websocket.
Video and Audio APIs - Learn web development
next, let's look at our button icons: @font-face { font-family: 'heydingscontrolsregular'; src: url('fonts/heydings_controls-webfont.eot'); src: url('fonts/heydings_controls-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/heydings_controls-webfont.woff') format('woff'), url('fonts/heydings_controls-webfont.ttf') format('
truetype'); font-weight: normal; font-style: normal; } button:before { font-family: heydingscontrolsregular; font-size: 20px; position: relative; content: attr(data-icon); color: #aaa; text-shadow: 1px 1px 0px black; } first of all, at the top of the css we use a @font-face block to import a custom web font.
...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?
Basic math in JavaScript — numbers and operators - Learn web development
this is especially
true when we are learning to program javascript (or any other language for that matter) — so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that javascript has a full-featured set of math functions available.
...you can see that it's been incremented if you return the variable value again: num1; the same is
true of -- : try the following let num2 = 6; num2--; num2; note: you can make the browser do it the other way round — increment/decrement the variable then return the value — by putting the operator at the start of the variable instead of the end.
... comparison operators sometimes we will want to run
true/false tests, then act accordingly depending on the result of that test — to do this we use comparison operators.
... if you try entering some of these values in a console, you'll see that they all return
true/false values — those booleans we mentioned in the last article.
Starting our Svelte Todo list app - Learn web development
</label> </h2> <input type="text" id="todo-0" autocomplete="off" class="input input__lg" /> <button type="submit" disabled="" class="btn btn__primary btn__lg"> add </button> </form> <!-- filter --> <div class="filters btn-group stack-exception"> <button class="btn toggle-btn" aria-pressed="
true"> <span class="visually-hidden">show</span> <span>all</span> <span class="visually-hidden">tasks</span> </button> <button class="btn toggle-btn" aria-pressed="false"> <span class="visually-hidden">show</span> <span>active</span> <span class="visually-hidden">tasks</span> </button> <button class="btn toggle-btn" aria-pressed="false"> <span ...
...for example: <button class="btn toggle-btn" aria-pressed="
true"> <span class="visually-hidden">show</span> <span>all</span> <span class="visually-hidden">tasks</span> </button> here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed.
...setting a value of
true means that the button is pressed by default.
... body { font-size: 1.9rem; line-height: 1.31579; } } /*end resets*/ /* global styles */ .form-group > input[type="text"] { display: inline-block; margin-top: 0.4rem; } .btn { padding: 0.8rem 1rem 0.7rem; border: 0.2rem solid #4d4d4d; cursor: pointer; text-transform: capitalize; } .btn.toggle-btn { border-width: 1px; border-color: #d3d3d3; } .btn.toggle-btn[aria-pressed="
true"] { text-decoration: underline; border-color: #4d4d4d; } .btn__danger { color: #fff; background-color: #ca3c3c; border-color: #bd2130; } .btn__filter { border-color: lightgrey; } .btn__primary { color: #fff; background-color: #000; } .btn__primary:disabled { color: darkgrey; background-color:#565656; } .btn-group { display: flex; justify-content: space-between; } .btn-grou...
TypeScript support in Svelte - Learn web development
typescript also has some disadvantages: not
true static typing: types are only checked at compile time, and they are removed from the generated code.
... no replacement for automatic tests: even though types might help you catch several bugs, typescript is not a
true replacement for a comprehensive suite of automated tests.
...this is how the contents will end up: // stores.ts import { writable } from 'svelte/store' import { localstore } from './localstore.js' import type { todotype } from './types/todo.type' export const alert = writable('welcome to the to-do list app!') const initialtodos: todotype[] = [ { id: 1, name: 'visit mdn web docs', completed:
true }, { id: 2, name: 'complete the svelte tutorial', completed: false }, ] export const todos = localstore('mdn-svelte-todo', initialtodos) remember to update the import statements in app.svelte, alert.svelte, and todos.svelte.
...// save also to local storage as a string return set(value) }, update } } and thanks to generic type inference, typescript already knows that our $todos store should contain an array of todotype: once again, if we wanted to be explicit about it, we could do so in the stores.ts file like this: const initialtodos: todotype[] = [ { id: 1, name: 'visit mdn web docs', completed:
true }, { id: 2, name: 'complete the svelte tutorial', completed: false }, ] export const todos = localstore<todotype[]>('mdn-svelte-todo', initialtodos) that will do for our brief tour of typescript generics.
Working with Svelte stores - Learn web development
update the <script> section of your alert.svelte component like so: <script> import { ondestroy } from 'svelte' import { alert } from '../stores.js' export let ms = 3000 let visible let timeout const onmessagechange = (message, ms) => { cleartimeout(timeout) if (!message) { // hide alert if message is empty visible = false } else { visible =
true // show alert if (ms > 0) timeout = settimeout(() => visible = false, ms) // and hide it after ms milliseconds } } $: onmessagechange($alert, ms) // whenever the alert store or the ms props changes run onmessagechange ondestroy(()=> cleartimeout(timeout)) // make sure we clean-up the timeout </script> and update t...
...if it is not empty, we set visible to
true and use the settimeout() function to clear the alert after ms milliseconds.
... update your app.svelte file like this: <script> import todos from './components/todos.svelte' import alert from './components/alert.svelte' import { todos } from './stores.js' $todos = [ { id: 1, name: 'create a svelte starter app', completed:
true }, { id: 2, name: 'create your first component', completed:
true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] </script> <alert /> <todos bind:todos={$todos} /> try it out; everything should work.
... update stores.js like so: import { writable } from 'svelte/store' import { localstore } from './localstore.js' export const alert = writable('welcome to the to-do list app!') const initialtodos = [ { id: 1, name: 'visit mdn web docs', completed:
true }, { id: 2, name: 'complete the svelte tutorial', completed: false }, ] export const todos = localstore('mdn-svelte-todo', initialtodos) using localstore('mdn-svelte-todo', initialtodos), we are configuring the store to save the data in web storage under the key mdn-svelte-todo.
Gecko info for Windows accessibility vendors
finally,
true descriptions are now exposed with the text "description: " prepending the description.
... hresult get_computedstyle( /* [in] */ unsigned short maxstyleproperties, /* [in] */ boolean usealternateview, // if
true, returns properties for media // as set in nsidomdocument::set_alternateviewmediatypes /* [out] */ bstr *styleproperties, /* [out] */ bstr *stylevalues, /* [out] */ unsigned short *numstyleproperties); a variation on this method is get_computedstyleforproperties, which lets turns the styleproperties array into an [in] parameter, letting you specify only those style properties you're inter...
... hresult get_computedstyleforproperties( /* [in] */ unsigned short numstyleproperties, /* [in] */ boolean usealternateview, // if
true, returns properties for media // as set in nsidomdocument::set_alternateviewmediatypes /* [in] */ bstr *styleproperties, /* [out] */ bstr *stylevalues); to scroll the document in order make a specific element visible in the window, use scrollto(boolean placetopleft).
... if the parameter placetopleft is
true the document will be scrolled so that the element is placed in the top left corner of the window.
Debugging JavaScript
to enable it, go to about:config in the url bar and set devtools.chrome.enabled to
true, or set the "enable chrome and add-on debugging" option in the developer tool settings.
... go to about:config and set the following two prefs: devtools.chrome.enabled:
true devtools.debugger.remote-enabled:
true after you restart the browser, you can access the browser debugger through tools > web developer > browser toolbox.
... strict code checking if you set the pref javascript.options.strict to
true, the javascript engine gives you more types of warnings on the error console, most of which hint at code bugs that are easy to oversee or even bad syntax.
... to see anything, you need to set the pref browser.dom.window.dump.enabled to
true, e.g.
Creating Custom Events That Can Pass Data
this remains
true even if you mark you extension code as "internal".
...var event = document.createevent("nsdommyevent"); event.initevent("nsdommyevent",
true,
true); window.dispatchevent(event); dispatching your event in c++ the following shows how to dispatch your event in c++: nscomptr<nsiwindowwatcher> wwatcher (do_getservice("@mozilla.org/embedcomp/window-watcher;1")); // the window watcher will be able to give me a handle to the window nscomptr<nsidomwindow> awindow; // a handle to the window nscomptr<nsidomdocument> adoc; // a handle to the document nscomptr<nsidomeventtarget> twindow; // the target window (really the same window as above but you need // a different inteface :/ nscomptr<nsidomevent> event; //this will be the event ...
... docevent->createevent(ns_literal_string("nsdommyevent"), getter_addrefs(event)); //create the event event->initevent(ns_literal_string("nsdommyevent"), pr_
true, pr_
true); //initialize it twindow = do_queryinterface(awindow); //use the window for a target.
... prbool defaultactionenabledwin; prbool defaultactionenableddoc; nscomptr<nsiprivatedomevent> privevt(do_queryinterface(event)); privevt->settrusted(pr_
true); //make the event trusted twindow->dispatchevent(event, &defaultactionenabledwin); //dispatch it (i.e.
Performance best practices for Firefox front-end engineers
hide your panels if you’re adding a new xul <xul:popup> or <xul:panel> to a document, set the hidden attribute to
true by default.
... you can activate paint flashing for browser chrome by setting nglayout.debug.paint_flashing_chrome to
true.
... you can activate paint flashing for web content by setting nglayout.debug.paint_flashing to
true.
...for example: services.scriptloader.loadsubscriptwithoptions(myscripturl, { async:
true }).then(() => { console.log("script at " + myscripturl + " loaded asynchronously!"); }); ...
HTMLIFrameElement.setVisible()
if the visible state is set to
true, it means that the browser <iframe> should have high priority over the resources needed to render and handle its content.
... as an example, if the content of a browser <iframe> uses the window.requestanimationframe method and if the visible state is set to
true, window.requestanimationframe will be called as often as necessary.
... parameters visible a boolean that indicates if the browser <iframe> visible state is
true or false.
... examples var browser = document.queryselector('iframe'); browser.setvisible(
true); specification not part of any specification.
IPDL Tutorial
the generated c++ will result in something containing: class pplugininstanceparent { public: typedef mozpromise<tuple<bool, bool> responserejectreason,
true> asyncinitpromise; typedef mozpromise<bool, responserejectreason,
true> otherfunctionpromise; void sendasyncinit(mozilla::ipc::resolvecallback<tuple<bool, bool>>&& aresolve, mozilla::ipc::rejectcallback&& areject); refptr<asyncinitpromise> sendasyncinit(); void sendotherfunction(mozilla::ipc::resolvecallback<bool>&& aresolve, mozilla::ipc::reje...
... return
true; } ...
...}; virtual pexamplechild* toplevelchild::allocpexample() { refptr<examplechild*> actor = new examplechild(); return actor.forget(); } virtual bool toplevelchild::deallocpexample(pexamplechild* actor) { ns_release(static_cast<examplechild*>(actor)); return
true; } if an object that implements a protocol can't be constructed inside allocpfoo, has been previously constructed and doesn't require an ipdl connection throughout its lifetime, or implements a refcounted protocol where the first form of constructor is not available, there is a second form of sendpfooconstructor which can be used: class examplechild { public: void dosomething() { a...
... for a protocol pfoo managed by pmanager, that manages pmanagee, the methods are pmanager* pfoo::manager() const infallibletarray<pmanagee*> pfoo::managedpmanagee(); void pfoo::managedpmanagee(infallibletarray<pmanagee*>&); shutdown and error handling the c++ methods which implement ipdl messages return bool:
true for success, and false for catastrophic failure.
AddonListener
void onenabling( in addon addon, in boolean needsrestart ) parameters addon the addon that is being enabled needsrestart
true if an application restart is necessary for the change to take effect onenabled() called when an add-on has been enabled.
... void ondisabling( in addon addon, in boolean needsrestart ) parameters addon the addon that is being disabled needsrestart
true if an application restart is necessary for the change to take effect ondisabled() called when an add-on has been disabled.
... void oninstalling( in addon addon, in boolean needsrestart ) parameters addon the addon that is being installed needsrestart
true if an application restart is necessary for the change to take effect oninstalled() called when an add-on has been installed.
... void onuninstalling( in addon addon, in boolean needsrestart ) parameters addon the addon that is being uninstalled needsrestart
true if an application restart is necessary for the change to take effect onuninstalled() called when an add-on has been uninstalled.
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.
...if
true, the notification will remain visible even if the browser navigates to a different location.
... nevershow notifications with this parameter set to
true will be removed when they would have otherwise been dismissed (i.e.
... removeondismissal notifications with this parameter set to
true will be removed when they would have otherwise been dismissed (that is, any time the popup is closed due to user interaction).
PromiseWorker.jsm
complete example following example provides resolvetest function, which resolves the promise when
true is passed as an argument, and rejects the promise when false is passed as an argument, and post messages to it from the main thread.
...nction() { self.close(); }; worker.log = function(...args) { dump('worker: ' + args.join(' ') + '\n'); }; self.addeventlistener('message', msg => worker.handlemessage(msg)); // start - my functionalities function resolvetest(shouldresolve) { if (shouldresolve) { return 'you sent to promiseworker argument of: `' + shouldresolve + '`'; } else { throw new error('you passed in a non-
true value for shouldresolve argument and therefore this will reject the main thread promise'); } } main thread file bootstrap.js const { utils: cu } = components; const { basepromiseworker } = cu.import('resource://gre/modules/promiseworker.jsm', {}); var myworker = new basepromiseworker('chrome://path/to/content/myworker.js'); var promise_domyfunc
true = myworker.post('resolvetest', [
true]); ...
...promise_domyfunc
true.then( function(aval) { console.log('fullfilled - promise_domyfunc
true - ', aval); }, function(areason) { console.error('rejected - promise_domyfunc
true - ', areason); } ).catch( function(acaught) { console.error('caught - promise_domyfunc
true - ', acaught); } ); var promise_domyfuncfalse = myworker.post('resolvetest', [false]); promise_domyfuncfalse.then( function(aval) { console.log('fullfilled - promise_domyfuncfalse - ', aval); }, function(areason) { console.error('rejected - promise_domyfuncfalse - ', areason); } ).catch( function(acaught) { console.error('caught - promise_domyfuncfalse - ', acaught); } ); result running the code above will log the following information ...
...to the console: "fullfilled - promise_domyfunc
true - " "you sent to promiseworker argument of: `
true`" bootstrap.js line 8 "rejected - promise_domyfuncfalse - " "you passed in a non-
true value for shouldresolve argument and therefore this will reject the main thread promise" bootstrap.js line 25 other examples github :: promiseworker with backward compatability - this example is of a firefox addon that copies and pastes in the contents of promiseworker.js and promiseworker.jsm so that it works all the way back till the firefox version in which the promise interface was frozen.
Index
true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode.
... -fips [
true | false] enable (
true) or disable (false) fips 140-2 compliance for the default nss module.
...for example: modutil -fips
true -dbdir sql:/home/my/sharednssdb/ fips mode enabled.
... to verify that status of fips mode, run the -chkfips command with either a
true or false flag (it doesn't matter which).
NSS tools : modutil
true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode.
... -fips [
true | false] enable (
true) or disable (false) fips 140-2 compliance for the default nss module.
...for example: modutil -fips
true -dbdir sql:/home/my/sharednssdb/ fips mode enabled.
... to verify that status of fips mode, run the -chkfips command with either a
true or false flag (it doesn't matter which).
NSS tools : modutil
true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode.
... -fips [
true | false] enable (
true) or disable (false) fips 140-2 compliance for the default nss module.
...for example: modutil -fips
true -dbdir sql:/home/my/sharednssdb/ fips mode enabled.
... to verify that status of fips mode, run the -chkfips command with either a
true or false flag (it doesn't matter which).
JSAPI User Guide
on success, a jsnative must call js_set_rval and return
true.
....; break; } } return
true; } defining classes this pulls together the above api elements by defining a constructor function, a prototype object, and properties of the prototype and of the constructor, all with one api call.
...this is especially
true if you are using the js engine with scripts to automate your application.
... block simple denial-of-service attacks - a program like while(
true){} should not hang your application.
JSBool
js_
true has been replaced by just
true and in the same way js_false by false.
...js_
true indicates success; js_false indicates an error or exception occurred.
...js_
true is (jsbool) 1 and js_false is (jsbool) 0.
...instead, use jsval_
true and jsval_false, and use boolean_to_jsval and jsval_to_boolean to convert.
JSDeletePropertyOp
if a jsdeletepropertyop does nothing and returns
true, then property delete is unaffected.
...otherwise the callback must return
true, and the property operation proceeds.
... if no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return
true.
... if no error occurred and the deletion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to
true and return
true.
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.
JSVAL_TO_BOOLEAN
as a precondition, jsval_is_boolean(v) must be
true.
... that is, v must be either jsval_
true or jsval_false.
...the result is js_
true or js_false respectively.
...js_false is 0; js_
true is 1.
JS_AlreadyHasOwnProperty
*foundp receives
true if the property is found or false if it is not found.
...*foundp is set to
true only if lookupproperty reports that the property was found on obj itself and not on some other object (even the corresponding outer object, if any).
... if the property is found on obj, this sets *foundp to
true and returns
true.
... if the property is not found on obj, this sets *foundp to false and returns
true (to indicate that no error occurred).
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.
... on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return
true.
A Web PKI x509 certificate primer
write extensions file (openssl.root.cnf) basicconstraints = critical, ca:
true keyusage = keycertsign, crlsign subjectkeyidentifier = hash nameconstraints = permitted;dns:example.com,permitted;dns:example.net self-sign csr (using sha256) and append the extensions described in the file "openssl x509 -req -sha256 -days 3650 -in root.csr -signkey rootkey.pem -set_serial $any_small_integer -extfile openssl.root.cnf -out root.pem" now you have ca pem ...
... write extensions file (openssl.int.cnf) basicconstraints = critical, ca:
true authoritykeyidentifier = keyid, issuer subjectkeyidentifier = hash keyusage = keycertsign, crlsign extendedkeyusage =serverauth authorityinfoaccess = ocsp;uri:http://ocsp.example.com:8888/ sign the intermediate csr with the root key and the intermediate extensions "openssl x509 -req -sha256 -days 2922 -in int.csr -cakey rootkey.pem -ca root.pem -set_serial $some_large_i...
...e what it means what can i do sec_error_bad_der a certificate is not properly encoded according to asn.1 (der) encoding re-generate the improperly-encoded certificate sec_error_ca_cert_invalid an end-entity certificate is being used to issue another certificate ensure that any certificate intended to issue certificates has a basic constraints extension with ca:
true sec_error_bad_signature a signature on a certificate is improperly formatted or the certificate has been tampered with re-issue the certificate with the bad signature sec_error_cert_bad_access_location the ocsp uri in the authorityinformationaccess extension is improperly formed re-generate the certificate with a well-formed ocsp uri sec_error_cert_not_in_na...
... import the root certificate into firefox or have the server send the intermediate sec_error_invalid_key sec_error_unsupported_keyalg sec_error_expired_issuer_certificate an issuer certificate is too old re-issue the issuer certificate mozilla_pkix_error_ca_cert_used_as_end_entity a certificate with a basic constraints extension with ca:
true is being used as an end-entity certificate re-generate the end-entity certificate without the basic constraints extension mozilla_pkix_error_inadequate_key_size a certificate has a key that is too small to be secure re-generate a larger key and issue a certificate using that key ...
jsdIStackFrame
|
true| if this context should be allowed to run scripts, |false| otherwise.
... isconstructing boolean
true if stack frame is constructing a new object.
... isdebugger boolean
true if stack frame represents a frame created as a result of a debugger evaluation.
... isnative boolean
true if stack frame represents a native frame.
mozIStorageConnection
transactioninprogress boolean returns
true if there is a transaction in progress on the database.
... mozistorageconnection clone( in boolean areadonly optional ); parameters areadonly if
true, the returned database connection is in read only mode.
... return value
true if the index exists, false otherwise.
... return value returns
true if the table exists, false otherwise.
nsIAccessibleHyperLink
note: currently only used with aria links, and the author has to specify that the link is invalid via the aria-invalid='
true' attribute.
... in all other cases,
true is returned.
... return value
true if the element currently has the focus.
... return value
true if the hyperlink is valid.
nsIAccessibleTable
return value
true if the cell is selected, false if the cell is not selected.
... return value
true if the column is selected, false if the column is not selected.
... return value
true if the table is probably for layout, false if the table is probably not for layout.
... return value
true if the row is selected, false if the row is not selected.
nsIAlertsService
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.
...if
true, the image url will be loaded in private browsing mode.
... getservice(components.interfaces.nsialertsservice); try { alertsservice.showalertnotification("", "alerts service test", "click me",
true, "cookie", listener, ""); } catch (e) { // this can fail on mac os x } example 2 this example shows how to use all the available observer topics: var as = cc['@mozilla.org/alerts-service;1'].getservice(ci.nsialertsservice); var notiflistener = { observe: function(asubject, atopic, adata) { console.error('incoming notification observer:', asubject, atopic, adata); if (at...
...click here to focus the tab',
true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service.
nsIAnnotationService
return value returns
true, if an annotation exists for given uri, otherwise returns false.
... return value returns
true, if an annotation exists for given item, otherwise returns false.
... aoverwritedest if you want to overwrite existing annotation, set this parameter to
true, or else set it to false.
... aoverwritedest if you want to overwrite existing annotation, set this parameter to
true or else false.
nsIApplicationCacheChannel
1.0 66 introduced gecko 1.9.1 inherits from: nsiapplicationcachecontainer last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void markofflinecacheentryasforeign(); attributes attribute type description chooseapplicationcache boolean when
true, the channel will choose an application cache if one was not explicitly provided and none is available from the notification callbacks.
... inheritapplicationcache boolean
true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided.
... the default value is
true.
... loadedfromapplicationcache prbool
true if the resource was loaded from the application cache, otherwise false.
nsIAsyncStreamCopier
asourcebuffered
true if asource implements nsiinputstream.readsegments().
... asinkbuffered
true if asink implements nsiinputstream.writesegments() .
...aclosesource
true if asource should be closed after copying.
... aclosesink
true if asink should be closed after copying.
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.
nsIDOMMouseScrollEvent
ctrlkeyarg
true if the control key was down when the event occurred, otherwise false.
... altkeyarg
true if the alt key was down when the event occurred, otherwise false.
... shiftkeyarg
true if the shift key was down when the event occurred, otherwise false.
... metakeyarg
true if the meta key was down when the event occurred, otherwise false.
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.
...
true if the current selection anchor is editable; otherwise false.
nsIJumpListBuilder
return value
true if the operation completed successfully.
...return value
true if the operation completed successfully.
...return value
true if the operation completed successfully.
... return value
true if the operation completed successfully.
nsINavHistoryQueryOptions
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) method overview nsinavhistoryqueryoptions clone(); attributes attribute type description applyoptionstocontainers boolean if
true, the query options are only applied to the containers.
... asyncenabled boolean when
true, the root container node generated by these options and all of its descendant containers are opened asynchronously if they support doing so.
... excludequeries boolean set to
true to exclude queries ("place:" uris) from the query results.
... excludereadonlyfolders boolean set to
true to exclude read-only folders from the query results.
nsIPrincipal
void checkmayload( in nsiuri uri, in boolean report ); parameters uri missing description report if
true, will report a warning to the console service if the load is not allowed.
... return value
true if the two principals are equivalent; otherwise false.
... istrusted
true if the certificate is a codebase trusted one.
...boolean subsumes( in nsiprincipal other ); parameters other missing description return value
true if this principal subsumes the specified principal; otherwise false.
nsISelection
if partlycontained is set to pr_
true, the function returns
true when some part of the node is part of the selection.
... if partlycontained is set to pr_false, the function only returns
true when the entire node is part of the selection.
... boolean containsnode( in nsidomnode node, in boolean partlycontained ); parameters node the nsidomnode to look for partlycontained if partlycontained is set to pr_false, the function only returns
true when the entire node is part of the selection.
...void selectionlanguagechange( in boolean langrtl ); parameters langrtl is pr_
true if the new language is right-to-left or pr_false if the new language is left-to-right.
nsITreeColumn
cycler boolean if
true, then the column is a cycler column.
... editable boolean if
true the nsitreecolumn content is editable.
... primary boolean if
true the nsitreecolumn is the primary column.
... selectable boolean if
true the nsitreecolumn is able to be selected.
nsIWebBrowserFindInFrames
default is
true.
... setting nsiwebbrowserfind.searchframes to
true sets this to
true.
...default is
true.
... setting nsiwebbrowserfind.searchframes to
true sets this to
true.
Type conversion
)(); var somecfunction = library.declare("somecfunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); somecfunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type implicit conversion can be tested in the following way: var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = 1; console.log(mystruct.v.tostring()); // '
true' boolean type target type source converted value ctypes.bool js boolean src js number (0 or 1) if src == 0: false if src == 1:
true var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v =
true; console.log(mystruct.v.tostring()); // '
true' mystruct.v = false; console.log(mystruct.v.tostring()); // 'f...
...alse' mystruct.v = 1; console.log(mystruct.v.tostring()); // '
true' mystruct.v = 0; console.log(mystruct.v.tostring()); // 'false' mystruct.v = 10; // throws error mystruct.v = "a"; // throws error integer types target type source converted value ctypes.char16_t js string (only if its length == 1) src.charcodeat(0) any integer types js number (only if fits to the size) src js boolean if src ==
true: 1 if src == false: 0 var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.char16_t } ])(); mystruct.v = 0x41; console.log(mystruct.v.tostring()); // "a" mystruct.v =
true; console.log(mystruct.v.tostring()); // "\x01" mystruct.v = "x"; console.log(mystruct.v.tostring()); // "x" mystruct.v ...
...= "xx"; // throws error var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.int16_t } ])(); mystruct.v = 0x41; console.log(mystruct.v.tostring()); // 65 mystruct.v =
true; console.log(mystruct.v.tostring()); // 1 mystruct.v = "x"; // throws error integer/float types are implicitly convertible if any data of source type could be representable in the target type.
...ted explicitly, when passing to cdata constructor: ctypes.int32_t("123"); // string "123" is parsed as 10-base string explicit convert tries implicit convert first, and if it fails, the following rules are applied: boolean type target type source converted value ctype.bool js value toboolean(src) console.log(ctypes.bool("123").tostring()); // 'ctypes.bool(
true)' console.log(ctypes.bool("").tostring()); // 'ctypes.bool(false)' integer types target type source converted value any integer types js number except -infinity, infinity, nan c-style cast -infinity 0 infinity nan ctypes.int64 c-style cast ctypes.uint64 js string with base-10 or base-16 string (onl...
Debugger.Environment - Firefox Developer Tools
accessor properties of the debugger.environment prototype object a debugger.environment instance inherits the following accessor properties from its prototype: inspectable
true if this environment is a debuggee environment, and can therefore be inspected.
... optimizedout
true if this environment is optimized out.
...when
true, getvariable returns an ordinary javascript object whose optimizedout property is
true on all bindings, and setvariable throws a referenceerror.
...if the given variable should be in scope, but getvariable is unable to produce its value, it returns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is
true.
Debugger.Frame - Firefox Developer Tools
a frame is a visible frame if any of the following are
true: it is running debuggee code; its immediate caller is a frame running debuggee code; or it is a "debugger" frame, representing the continuation of debuggee code invoked by the debugger.
... live
true if the frame this debugger.frame instance refers to is still on the stack; false if it has completed execution or been popped in some other way.
... generator
true if this frame is a generator frame, false otherwise.
... constructing
true if this frame is for a function called as a constructor, false otherwise.
Debugger.Memory - Firefox Developer Tools
allocation site tracking the javascript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some debugger instancedbg; and dbg.memory.trackingallocationsites is set to
true.
... allocation logging ifdbg is a debugger instance, and dbg.memory.trackingallocationsites is set to
true, then the javascript engine logs each object allocated bydbg’s debuggee code.
...reading the accessor produces
true if the debugger is capturing stacks for object allocations, and false otherwise.
... 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.
Attr - Web APIs
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.
... originally, it returned
true if the attribute was explicitly specified in the source code or by a script, and false if its value came from the default one defined in the document's dtd.
... specified this property now always returns
true.
AudioBufferSourceNode.loopEnd - Web APIs
this is only used if the loop property is
true.
...this property is only used if the loop property is
true.
... function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop ...
...=
true; loopstartcontrol.setattribute('max', math.floor(songlength)); loopendcontrol.setattribute('max', math.floor(songlength)); }, function(e){"error with decoding audio data" + e.err}); } request.send(); } ...
Background Tasks API - Web APIs
as a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the
true requestidlecallback(), it does at least limit the callback to no more than 50 milliseconds of run time per pass.
...er(task.data); schedulestatusrefresh(); } if (tasklist.length) { taskhandle = requestidlecallback(runtaskqueue, { timeout: 1000} ); } else { taskhandle = 0; } } runtaskqueue()'s core is a loop which continues as long as there's time left (as determined by checking deadline.timeremaining) to be sure it's more than 0 or if the timeout limit was reached (deadline.didtimeout is
true), and as long as there are tasks in the task list.
... function schedulestatusrefresh() { if (!statusrefreshscheduled) { requestanimationframe(updatedisplay); statusrefreshscheduled =
true; } } this is a simple function.
...!= currenttasknumber) { currenttasknumberelem.textcontent = currenttasknumber; progressbarelem.value = currenttasknumber; } } if (logfragment) { logelem.appendchild(logfragment); logfragment = null; } if (scrolledtoend) { logelem.scrolltop = logelem.scrollheight - logelem.clientheight; } statusrefreshscheduled = false; } first, scrolledtoend is set to
true if the text in the log is scrolled to the bottom; otherwise it's set to false.
Element: mousedown event - Web APIs
first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to
true.
...if isdrawing is
true, the event handler calls the drawline function to draw a line from the stored x and y values to the current location.
... html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when
true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
... // add the event listeners for mousedown, mousemove, and mouseup mypics.addeventlistener('mousedown', e => { x = e.offsetx; y = e.offsety; isdrawing =
true; }); mypics.addeventlistener('mousemove', e => { if (isdrawing ===
true) { drawline(context, x, y, e.offsetx, e.offsety); x = e.offsetx; y = e.offsety; } }); window.addeventlistener('mouseup', e => { if (isdrawing ===
true) { drawline(context, x, y, e.offsetx, e.offsety); x = 0; y = 0; isdrawing = false; } }); function drawline(context, x1, y1, x2, y2) { context.beginpath(); context.strokestyle = 'black'; context.linewidth = 1; context.moveto(x1, y1); context.lineto(x2, y2); context.stroke(); context.closepath(); } result specifications specification status ...
Element: mousemove event - Web APIs
first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to
true.
...if isdrawing is
true, the event handler calls the drawline function to draw a line from the stored x and y values to the current location.
... html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when
true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
... // add the event listeners for mousedown, mousemove, and mouseup mypics.addeventlistener('mousedown', e => { x = e.offsetx; y = e.offsety; isdrawing =
true; }); mypics.addeventlistener('mousemove', e => { if (isdrawing ===
true) { drawline(context, x, y, e.offsetx, e.offsety); x = e.offsetx; y = e.offsety; } }); window.addeventlistener('mouseup', e => { if (isdrawing ===
true) { drawline(context, x, y, e.offsetx, e.offsety); x = 0; y = 0; isdrawing = false; } }); function drawline(context, x1, y1, x2, y2) { context.beginpath(); context.strokestyle = 'black'; context.linewidth = 1; context.moveto(x1, y1); context.lineto(x2, y2); context.stroke(); context.closepath(); } result specifications specification status ...
Element: mouseup event - Web APIs
first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to
true.
...if isdrawing is
true, the event handler calls the drawline function to draw a line from the stored x and y values to the current location.
... html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when
true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
... // add the event listeners for mousedown, mousemove, and mouseup mypics.addeventlistener('mousedown', e => { x = e.offsetx; y = e.offsety; isdrawing =
true; }); mypics.addeventlistener('mousemove', e => { if (isdrawing ===
true) { drawline(context, x, y, e.offsetx, e.offsety); x = e.offsetx; y = e.offsety; } }); window.addeventlistener('mouseup', e => { if (isdrawing ===
true) { drawline(context, x, y, e.offsetx, e.offsety); x = 0; y = 0; isdrawing = false; } }); function drawline(context, x1, y1, x2, y2) { context.beginpath(); context.strokestyle = 'black'; context.linewidth = 1; context.moveto(x1, y1); context.lineto(x2, y2); context.stroke(); context.closepath(); } result specifications specification status ...
Event.composed - Web APIs
syntax const iscomposed = event.composed; value a boolean which is
true if the event will cross from the shadow dom into the standard dom after reaching the shadow root.
...for example, this includes synthetic events that are created without their composed option wil set to
true.
... propagation only occurs if the bubbles property is also
true.
... the composed property returns
true beause the click event is always able to propagate across shadow boundaries.
EventTarget.removeEventListener() - Web APIs
for example, consider this call to addeventlistener(): element.addeventlistener("mousedown", handlemousedown,
true); now consider each of these two calls to removeeventlistener(): element.removeeventlistener("mousedown", handlemousedown, false); // fails element.removeeventlistener("mousedown", handlemousedown,
true); // succeeds the first call fails because the value of usecapture doesn't match.
... now consider this: element.addeventlistener("mousedown", handlemousedown, { passive:
true }); here, we specify an options object in which passive is set to
true, while the other options are left to the default value of false.
...any of them in which capture or usecapture is
true fail; all others succeed.
... element.removeeventlistener("mousedown", handlemousedown, { passive:
true }); // succeeds element.removeeventlistener("mousedown", handlemousedown, { capture: false }); // succeeds element.removeeventlistener("mousedown", handlemousedown, { capture:
true }); // fails element.removeeventlistener("mousedown", handlemousedown, { passive: false }); // succeeds element.removeeventlistener("mousedown", handlemousedown, false); // succeeds element.removeeventlistener("mousedown", handlemousedown,
true); // fails it's worth noting that some browser releases have been inconsistent on this, and unless you have specific reasons otherwise, it's probably wise to use the same values used for the ca...
FileSystemFlags.create - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
...
true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
...
true true path exists the errorcallback is called with an appropriate error, such as fileerror.path_exists_err.
...
true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
FileSystemFlags.exclusive - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
...
true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
...
true true path exists the errorcallback is called with an appropriate error, such as fileerror.path_exists_err.
...
true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
Guide to the Fullscreen API - Web APIs
te name alternate name uses the non-standard name: webkitisfullscreenfirefox full support 64 full support 64 no support 49 — 65disabled disabled from version 49 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to
true).
...alternate name uses the non-standard name: webkitisfullscreenfirefox android full support 64 full support 64 no support 49 — 65disabled disabled from version 49 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to
true).
...bkitedge full support 12firefox full support 64 full support 64 no support 47 — 65disabled disabled from version 47 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to
true).
...sprefixed prefixed implemented with the vendor prefix: webkitfirefox android full support 64 full support 64 no support 47 — 65disabled disabled from version 47 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to
true).
HTMLSlotElement.name - Web APIs
3edge full support 79firefox full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
...— 59disabled disabled until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
... full support 53firefox android full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
...— 59disabled disabled until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
HTMLVideoElement.msZoom - Web APIs
syntax htmlvideoelement.mszoom; value boolean value set to
true trims the video frame to the display space.
... when the mszoom attribute is set to
true, the rendered video is trimmed to fit the dimensions of the video object.
... example this examples gets a video object and sets the mszoom property to
true.
... var myvideo = document.getelementbyid("videotag1"); myvideo.mszoom =
true; myvideo.play(); see also htmlvideoelement microsoft api extensions ...
Ajax navigation example - Web APIs
first_page.php: <?php $page_title = "first page"; $as_json = false; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { $as_json =
true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" .
...t_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> second_page.php: <?php $page_title = "second page"; $as_json = false; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { $as_json =
true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" .
..."&" + 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.classname === 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 = /^[^\?]*...
IDBKeyRange.lowerOpen - Web APIs
syntax var loweropen = mykeyrange.loweropen value a boolean: value indication
true the lower-bound value is not included in the key range.
...here we declare keyrangevalue = idbkeyrange.upperbound("f", "w",
true,
true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (
true).
... after declaring the key range, we log its loweropen property value to the console, which should appear as "
true": the lower bound is open, so won't be included in the range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w",
true,
true); console.log(keyrangevalue.loweropen); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displaye...
IDBKeyRange.upperOpen - Web APIs
syntax var upperopen = mykeyrange.upperopen value a boolean: value indication
true the upper-bound value is not included in the key range.
...here we declare keyrangevalue = idbkeyrange.upperbound("f", "w",
true,
true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (
true).
... after declaring the key range, we log its upperopen property value to the console, which should appear as "
true": the upper bound is open, so won't be included in the range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w",
true,
true); console.log(keyrangevalue.upperopen); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displaye...
KeyboardEvent.key - Web APIs
if the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the keyboardevent.repeat read only property is set to
true.
... if the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with htmlelement.contenteditable set to
true, the beforeinput and input event types are fired in that order.
...as we keep holding the key, the keydown event continues to fire repeatedly and the keyboardevent.repeat property is set to
true.
... } // cancel the default action to avoid it being handled twice event.preventdefault(); },
true); specification specification status comment ui eventsthe definition of 'keyboardevent.key' in that specification.
MediaStreamConstraints.audio - Web APIs
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.
... using a boolean value in this example, we provide a simple value of
true for the audio property.
...-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { 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.
...e; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: { samplesize: 8, echocancellation:
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 calls getusermedia(), specifying a set of audio constraints requesting that echo cancellation be enabled and that, if possible, the sample rate be 8 bits per sample instead of the more common 16 bits (possibly as a bandw...
MediaTrackSettings - Web APIs
properties of audio tracks autogaincontrol a boolean which indicates the current value of the autogaincontrol property, which is
true if automatic gain control is enabled and is false otherwise.
... echocancellation a boolean indicating the current value of the echocancellation property, specifying
true if echo cancellation is enabled, otherwise false.
... noisesuppression a boolean which indicates the current value of the noisesupression property, which is
true if noise suppression is enabled and is false otherwise.
... logicalsurface a boolean value which, if
true, indicates that the video contained in the stream's video track contains a background rendering context, rather than a user-visible one.
MutationObserverInit.attributeOldValue - Web APIs
syntax var options = { attributeoldvalue:
true | false } value a boolean value indicating whether or not the prior value of a changed attribute should be included in the mutationobserver.oldvalue property when reporting attribute value changes.
... if
true, oldvalue is set accordingly.
... when using attributeoldvalue, setting the attributes option to
true is optional.
...utation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.queryselector("#target"); var observer = new mutationobserver(callback); observer.observe(targetnode, { attributes:
true, attributeoldvalue:
true }); the callback() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects.
MutationObserverInit.characterDataOldValue - Web APIs
if you set the mutationobserverinit.characterdata property to
true but don't set characterdataoldvalue to
true as well, the mutationrecord will not include information describing the prior state of the text node's contents.
... syntax var options = { characterdataoldvalue:
true | false } value a boolean value indicating whether or not to set the mutationrecord's oldvalue property to be a string containing the value of the character node's contents prior to the change represented by the mutation record.
...to watch for changes to the text contents of all descendants of target, set the subtree option to
true.
... if you set characterdataoldvalue to
true, characterdata is automatically assumed to be
true, even if you don't expressly set it as such.
PaymentResponse.shippingAddress - Web APIs
you can trigger this by setting paymentoptions.requestshipping to
true when calling the paymentrequest constructor.
...}).catch(function(err) { console.error("uh oh, something bad happened", err.message); }); function updatedetails(details, shippingaddress, resolve) { if (shippingaddress.country === 'us') { var shippingoption = { id: '', label: '', amount: {currency: 'usd', value: '0.00'}, selected:
true }; if (shippingaddress.region === 'mo') { shippingoption.id = 'mo'; shippingoption.label = 'free shipping in missouri'; details.total.amount.value = '55.00'; } else { shippingoption.id = 'us'; shippingoption.label = 'standard shipping in us'; shippingoption.amount.value = '5.00'; details.total.amount.value = '60.00'; } details.displayi...
... 61edge full support 15firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
...to change preferences in chrome, visit chrome://flags.firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentResponse.shippingOption - Web APIs
this option is only present when the requestshipping option is set to
true in the paymentoptions object passed to the paymentrequest constructor.
... = 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.
... 61edge full support 15firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
...to change preferences in chrome, visit chrome://flags.firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
Using the Payment Request API - Web APIs
in the following snippet, a merchant page performs this check, and if it returns
true updates the checkout button to use paymentrequest instead of legacy web forms.
... checking before all prices are known if the checkout flow needs to know whether paymentrequest.canmakepayment() will return
true even before all line items and their prices are known, you can instantiate paymentrequest with dummy data and pre-query .canmakepayment().
...let shouldcallpaymentrequest =
true; let fallbacktolegacyonpaymentrequestfailure = false; (new paymentrequest(supportedpaymentmethods, {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(result) { shouldcallpaymentrequest = result; }).catch(function(error) { console.log(error); // the user may have turned off query ability in their privacy settings.
... shouldcallpaymentrequest =
true; fallbacktolegacyonpaymentrequestfailure =
true; }); // user has clicked on the checkout button.
PublicKeyCredentialRequestOptions.extensions - Web APIs
if
true, the client outputs an arraybuffer which contains a value uniquely identifying a user verification data record.
...if
true, the client outputs a coordinates object representing the geolocation of the authenticator.
...if
true, the client outputs an array of arrays with 3 values containing information about how the user was verified (e.g.
... examples var options = { extensions: { uvm:
true, loc: false, txauthsimple: "could you please verify yourself?" }, challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); })...
RTCPeerConnection.createDataChannel() - Web APIs
rtcdatachannelinit dictionary the rtcdatachannelinit dictionary provides the following fields, any of which may be included in the object passed as the options parameter in order to configure the data channel to suit your needs: ordered optional indicates whether or not messages sent on the rtcdatachannel are required to arrive at their destination in the same order in which they were sent (
true), or if they're allowed to arrive out-of-order (false).
... default:
true.
...alternatively (
true), they can be negotiated out of-band, where both sides call createdatachannel with an agreed-upon id.
... { var channel = event.channel; channel.onopen = function(event) { channel.send('hi back!'); } channel.onmessage = function(event) { console.log(event.data); } } alternatively, more symmetrical out-of-band negotiation can be used, using an agreed-upon id (0 here): // both sides var pc = new rtcpeerconnection(options); var channel = pc.createdatachannel("chat", {negotiated:
true, id: 0}); channel.onopen = function(event) { channel.send('hi!'); } channel.onmessage = function(event) { console.log(event.data); } for a more thorough example showing how the connection and channel are established, see a simple rtcdatachannel sample.
SVGSVGElement - Web APIs
if the initial view is a "custom" view, then this attribute is
true.
... svgsvgelement.animationspaused() returns
true if this svg document fragment is in a paused state.
... svgsvgelement.checkintersection() returns
true if the rendered content of the given element intersects the supplied rectangle.
... svgsvgelement.checkenclosure() returns
true if the rendered content of the given element is entirely contained within the supplied rectangle.
Slottable: assignedSlot - Web APIs
3edge full support 79firefox full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
...— 59disabled disabled until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
... full support 53firefox android full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
...— 59disabled disabled until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
SourceBuffer - Web APIs
sourcebuffer.updating changes from
true to false.
...sourcebuffer.updating changes from
true to false.
...sourcebuffer.updating changes from
true to false.
... sourcebuffer.onupdatestart fired whenever the value of sourcebuffer.updating transitions from false to
true.
SubtleCrypto.generateKey() - Web APIs
let keypair = window.crypto.subtle.generatekey( { name: "rsa-oaep", moduluslength: 4096, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256" },
true, ["encrypt", "decrypt"] ); elliptic curve key pair generation this code generates an ecdsa signing key pair.
... let keypair = window.crypto.subtle.generatekey( { name: "ecdsa", namedcurve: "p-384" },
true, ["sign", "verify"] ); hmac key generation this code generates an hmac signing key.
... let key = window.crypto.subtle.generatekey( { name: "hmac", hash: {name: "sha-512"} },
true, ["sign", "verify"] ); aes key generation this code generates an aes-gcm encryption key.
... let key = window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256 },
true, ["encrypt", "decrypt"] ); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.generatekey()' in that specification.
SubtleCrypto.unwrapKey() - Web APIs
const saltbuffer = bytestoarraybuffer(saltbytes); // 3 derive the key from key material and salt return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: saltbuffer, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-kw", "length": 256},
true, [ "wrapkey", "unwrapkey" ] ); } /* unwrap an aes secret key from an arraybuffer containing the raw bytes.
...unwrap the key return window.crypto.subtle.unwrapkey( "raw", // import format wrappedkeybuffer, // arraybuffer representing key to unwrap unwrappingkey, // cryptokey representing key encryption key "aes-kw", // algorithm identifier for key encryption key "aes-gcm", // algorithm identifier for key to unwrap
true, // extractability of key to unwrap ["encrypt", "decrypt"] // key usages for key to unwrap ); } unwrapping a "pkcs8" key in this example we unwrap an rsa-pss private signing key.
... const saltbuffer = bytestoarraybuffer(saltbytes); // 3 derive the key from key material and salt return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: saltbuffer, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256},
true, [ "wrapkey", "unwrapkey" ] ); } /* unwrap an rsa-pss private signing key from an arraybuffer containing the raw bytes.
... // import format wrappedkeybuffer, // arraybuffer representing key to unwrap unwrappingkey, // cryptokey representing key encryption key { // algorithm params for key encryption key name: "aes-gcm", iv: ivbuffer }, { // algorithm params for key to unwrap name: "rsa-pss", hash: "sha-256" },
true, // extractability of key to unwrap ["sign"] // key usages for key to unwrap ); } specifications specification status comment web cryptography apithe definition of 'subtlecrypto.unwrapkey()' in that specification.
Animating textures in WebGL - Web APIs
getting access to the video the first step is to create the <video> element that we'll use to retrieve the video frames: // will set to
true when video can be copied to texture var copyvideo = false; function setupvideo(url) { const video = document.createelement('video'); var playing = false; var timeupdate = false; video.autoplay =
true; video.muted =
true; video.loop =
true; // waiting for 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.
...in the code above, we confirm whether we got both of those events; if so, we set a global variable, copyvideo, to
true to indicate that it's safe to start copying the video to a texture.
... in the definition of render() if copyvideo is
true, then we call updatetexture() each time just before we call the drawscene() function.
WebGL best practices - Web APIs
shaders, programs, and glsl avoid "#ifdef gl_es", which is always
true you should never use #ifdef gl_es in your webgl shaders; although some early examples used this, it's not necessary, since this condition is always
true in webgl shaders.
... 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.getshaderinfolog(fs)); } } consider: function compileonce(g...
...l, 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 blocks until the compile or link completes.
... demo: https://jdashg.github.io/misc/webgl/device-pixel-presnap.html resizeobserver and 'device-pixel-content-box' on supporting browsers (chromium?), resizeobserver can be used with 'device-pixel-content-box' to request a callback that includes the
true device pixel size of an element.
Signaling and video calling - Web APIs
function sendtooneuser(target, msgstring) { var isunique =
true; var i; for (i=0; i<connectionarray.length; i++) { if (connectionarray[i].username === target) { connectionarray[i].send(msgstring); break; } } } this function iterates over the list of connected users until it finds one matching the specified username, then sends the message to that user.
... starting a call when the user clicks on a username they want to call, the invite() function is invoked as the event handler for that click event: var mediaconstraints = { audio:
true, // we want an audio track video:
true // ...and we want a video track }; function invite(evt) { if (mypeerconnection) { alert("you can't start a call because you already have one open!"); } else { var clickedusername = evt.target.textcontent; if (clickedusername === myusername) { alert("i'm afraid i can't let you talk to yourself.
... } if (localvideo.srcobject) { localvideo.srcobject.gettracks().foreach(track => track.stop()); } mypeerconnection.close(); mypeerconnection = null; } remotevideo.removeattribute("src"); remotevideo.removeattribute("srcobject"); localvideo.removeattribute("src"); remotevideo.removeattribute("srcobject"); document.getelementbyid("hangup-button").disabled =
true; targetusername = null; } after pulling references to the two <video> elements, we check if a webrtc connection exists; if it does, we proceed to disconnect and close the call: all of the event handlers are removed.
... finally, we set the disabled property to
true on the "hang up" button, making it unclickable while there is no call underway; then we set targetusername to null since we're no longer talking to anyone.
Writing a WebSocket server in C# - Web APIs
the value is zero until networkstream.dataavailable is
true.
... tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); //enter to an infinite cycle to be able to handle every change in stream while (
true) { while (!stream.dataavailable); byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.length); } handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocket from a simple http request.
...ess.parse(ip), port); server.start(); console.writeline("server has started on {0}:{1}, waiting for a connection...", ip, port); tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); // enter to an infinite cycle to be able to handle every change in stream while (
true) { while (!stream.dataavailable); while (client.available < 3); // match against "get" byte[] bytes = new byte[client.available]; stream.read(bytes, 0, client.available); string s = encoding.utf8.getstring(bytes); if (regex.ismatch(s, "^get", regexoptions.ignorecase)) { console.writeline("=====handshaking fr...
...ing protocols\r\n" + "connection: upgrade\r\n" + "upgrade: websocket\r\n" + "sec-websocket-accept: " + swkasha1base64 + "\r\n\r\n"); stream.write(response, 0, response.length); } else { bool fin = (bytes[0] & 0b10000000) != 0, mask = (bytes[1] & 0b10000000) != 0; // must be
true, "all messages from the client to the server have this bit set" int opcode = bytes[0] & 0b00001111, // expecting 1 - text message msglen = bytes[1] - 128, // & 0111 1111 offset = 2; if (msglen == 126) { // was touint16(bytes, offset) but the result is incorrect msglen = bitconverter.t...
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 that feature.
...e 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 { xhr.open("get", "detect.html"); xhr.responsetype = "document"; xhr.send(); } catch (e) { window.settimeout(function() { if (!done) { done...
... =
true; callback(false); } }, 0); } } the argument callback is a function that will be called asynchronously with
true as the only argument if html parsing is supported and false as the only argument if html parsing is not supported.
...(new regexp("(?:(?:.(?!<\\s*" + aexec[1] + "[^>]*[>]))*.?<\\s*" + aexec[1] + "[^>]*[>](?:.(?!<\\s*\/\\s*" + aexec[1] + "\\s*>))*.?<\\s*\/\\s*" + aexec[1] + "\\s*>)*(?:.(?!<\\s*\/\\s*" + aexec[1] + "\\s*>))*.?", "i")).exec(ssrc.slice(ssrc.indexof(aexec[0]) + aexec[0].length)) || "" : ""; } var oreq = new xmlhttprequest(); oreq.open("get", "yourpage.html",
true); oreq.onload = function () { console.log(gethtml(this, "intro")); }; oreq.send(null); note: this solution is very expensive for the interpreter.
Sending and Receiving Binary Data - Web APIs
var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png",
true); oreq.responsetype = "arraybuffer"; oreq.onload = function (oevent) { var arraybuffer = oreq.response; // note: not oreq.responsetext if (arraybuffer) { var bytearray = new uint8array(arraybuffer); for (var i = 0; i < bytearray.bytelength; i++) { // do something with each byte in the array } } }; oreq.send(null); you can also read a binary file as a blob by setting ...
... var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png",
true); oreq.responsetype = "blob"; oreq.onload = function(oevent) { var blob = oreq.response; // ...
... var oreq = new xmlhttprequest(); oreq.open("post", url,
true); oreq.onload = function (oevent) { // uploaded.
... var req = new xmlhttprequest(); req.open("post", url,
true); // set headers and mime-type appropriately req.setrequestheader("content-length", 741); req.sendasbinary(abody); line 4 sets the content-length header to 741, indicating that the data is 741 bytes long.
Synchronous and asynchronous requests - Web APIs
var xhr = new xmlhttprequest(); xhr.open("get", "/bar/foo.txt",
true); xhr.onload = function (e) { if (xhr.readystate === 4) { if (xhr.status === 200) { console.log(xhr.responsetext); } else { console.error(xhr.statustext); } } }; xhr.onerror = function (e) { console.error(xhr.statustext); }; xhr.send(null); line 2 specifies
true for its third parameter to indicate that the request should be handled asynchronously.
...*/) { var xhr = new xmlhttprequest(); xhr.callback = callback; xhr.arguments = array.prototype.slice.call(arguments, 2); xhr.onload = xhrsuccess; xhr.onerror = xhrerror; xhr.open("get", url,
true); xhr.send(null); } usage: function showmessage(message) { console.log(message + this.responsetext); } loadfile("message.txt", showmessage, "new message!\n\n"); the signature of the utility function loadfile declares (i) a target url to read (via an http get request), (ii) a function to execute on successful completion of the xhr operation, and (iii) an arbitrary list of additional ...
... line 15 specifies
true for its third parameter to indicate that the request should be handled asynchronously.
... new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { if (xhr.readystate === 4) { if (xhr.status === 200) { callback.apply(xhr, args); } else { console.error(xhr.statustext); } } }; xhr.open("get", url,
true); xhr.timeout = timeout; xhr.send(null); } notice the addition of code to handle the "timeout" event by setting the ontimeout handler.
XMLHttpRequest() - Web APIs
setting the mozanon flag to
true effectively resembles the anonxmlhttprequest() constructor described in older versions of the xmlhttprequest specification.
... const request = new xmlhttprequest(paramsdictionary); parameters (non-standard) objparameters there are two flags you can set: mozanon boolean: setting this flag to
true will cause the browser not to expose the origin and user credentials when fetching resources.
... mozsystem boolean: setting this flag to
true allows making cross-site connections without requiring the server to opt-in using cors.
... requires setting mozanon:
true, i.e.
XMLHttpRequest.withCredentials - Web APIs
xmlhttprequest from a different domain cannot set cookie values for their own domain unless withcredentials is set to
true before making the request.
... the third-party cookies obtained by setting withcredentials to
true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.
... note: xmlhttprequest responses from a different domain cannot set cookie values for their own domain unless withcredentials is set to
true before making the request, regardless of access-control- header values.
... example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/',
true); xhr.withcredentials =
true; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XRView.eye - Web APIs
however, we have flags which, if
true, indicate that a particular eye has been injured during gameplay.
... when rendering that eye, if the flag is
true, that view is skipped instead of being rendered.
...injured) { skipview = updateinjury(body.righteye); } if (!skipview) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); renderscene(gl, view); } } for each of the views, the value of eye is checked and if it's either left or right, we check to see if the body.lefteye.injured or body.righteye.injured property is
true; if so, we call a function updateinjury() on that eye to do things such as allow a bit of healing to occur, track the progress of a poison effect, or the like, as appropriate for the game's needs.
... updateinjury() returns
true if the eye is still injured or false if the eye has been restored to health by the function,.
ARIA: checkbox role - Accessibility
similarly, an element with role="checkbox" can expose three states through the aria-checked attribute:
true, false, or mixed.
...this attribute has one of three possible values:
true the checkbox is checked false the checkbox is not checked mixed the checkbox is partially checked, or indeterminate tabindex="0" used to make it focusable so the assistive technology user can tab to it and start reading right away.
... html <span role="checkbox" id="chkpref" aria-checked="false" onclick="changecheckbox()" onkeypress="changecheckbox()" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label" onclick="changecheckbox()" onkeypress="changecheckbox()">remember my preferences</label> css [role="checkbox"] { padding:5px; } [aria-checked="
true"]::before { content: "[x]"; } [aria-checked="false"]::before { content: "[ ]"; } javascript function changecheckbox(event) { let item = document.getelementbyid('chkpref'); switch(item.getattribute('aria-checked')) { case "
true": item.setattribute('aria-checked', "false"); break; case "false": item.setattribute('aria-checked', ...
..."
true"); break; } } accessibility concerns when the checkbox role is added to an element, the user agent should do the following: expose the element as having a checkbox role in the operating system's accessibility api.
Basic form hints - Accessibility
="radiogroup" id="rg1" role="radiogroup" aria-labelledby="rg1_label"> <li id="r1" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> thai </li> <li id="r2" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> subway </li> <li id="r3" tabindex="0" role="radio" aria-checked="
true"> <img role="presentation" src="radio-checked.gif" /> radio maria </li> </ul> describing with aria form controls sometimes have a description associated with them, in addition to the label.
...on lines 4 and 12, the aria-required attributes are set to
true (in addition to the asterisks next to the labels), indicating that the name and email fields are required.
... <form> <div> <label for="name">* name:</label> <input type="text" value="name" id="name" aria-required="
true"/> </div> <div> <label for="phone">phone:</label> <input type="text" value="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.
CSS Scrollbars - CSS: Cascading Style Sheets
noedge no support nofirefox full support 64 full support 64 full support 63disabled disabled from version 63: this feature is behind the layout.css.scrollbar-width.enabled preference (needs to be set to
true).
...ochrome android no support nofirefox android full support 64 full support 64 full support 63disabled disabled from version 63: this feature is behind the layout.css.scrollbar-width.enabled preference (needs to be set to
true).
... full support 63disabled disabled from version 63: this feature is behind the layout.css.scrollbar-color.enabled preference (needs to be set to
true).
...ochrome android no support nofirefox android full support 64 full support 64 full support 63disabled disabled from version 63: this feature is behind the layout.css.scrollbar-color.enabled preference (needs to be set to
true).
Getting Started - Developer guides
}; next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send() methods of the http request object, like this: httprequest.open('get', 'http://www.example.org/some.file',
true); httprequest.send(); the first parameter of the call to open() is the http request method – get, post, head, or another method supported by your server.
...if
true (the default), javascript execution will continue and the user can interact with the page while the server response has yet to arrive.
...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).
... </style> </head> <body> <p id="writedata" class="data">off-line</p> <p id="laststamp">no data yet</p> <script> const fulldata = document.getelementbyid('writedata'); const lastdata = document.getelementbyid('laststamp'); function fetchdata() { console.log('fetching updated data.'); let xhr = new xmlhttprequest(); xhr.open("get", "time-log.txt",
true); xhr.onload = function() { updatedisplay(xhr.response); } xhr.send(); } function updatedisplay(text) { fulldata.textcontent = text; let timearray = text.split('\n'); // included because some file systems always include a blank line at the end of text files.
Creating and triggering events - Developer guides
event.initevent('build',
true,
true); // listen for the event.
...to trigger an event from a child element, and have an ancestor catch it; optionally, with data: <form> <textarea></textarea> </form> const form = document.queryselector('form'); const textarea = document.queryselector('textarea'); // create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventawesome = new customevent('awesome', { bubbles:
true, detail: { text: () => textarea.value } }); // the form element listens for the custom "awesome" event and then consoles the output of the passed text() method form.addeventlistener('awesome', e => console.log(e.detail.text())); // as the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addeventlistener('input', e =...
...tor('textarea'); form.addeventlistener('awesome', e => console.log(e.detail.text())); textarea.addeventlistener('input', function() { // create and dispatch/trigger an event on the fly // note: optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchevent(new customevent('awesome', { bubbles:
true, detail: { text: () => textarea.value } })) }); triggering built-in events this example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using dom methods.
... function simulateclick() { const event = new mouseevent('click', { view: window, bubbles:
true, cancelable:
true }); const cb = document.getelementbyid('checkbox'); const cancelled = !cb.dispatchevent(event); if (cancelled) { // a handler called preventdefault.
User input and controls - Developer guides
for example if you want to add controls when any key gets pressed, you need to add an event listener on the window object: window.addeventlistener("keydown", handlekeydown,
true); window.addeventlistener("keyup", handlekeyup,
true); where handlekeydown and handlekeyup are the functions implementing the controls about the keydown and keyup events.
... <div draggable="
true" ondragstart="event.datatransfer.setdata('text/plain', 'this text may be dragged')">
this text <strong>may</strong> be dragged.
...
</div> in which we: set the draggable attribute to
true on the element that you wish to make draggable add a listener for the dragstart event and set the drag data within this listener note: you can find more information in the mdn drag & drop documentation.
... <div contenteditable="
true">
this text can be edited by the user.
The Web Open Font Format (WOFF) - Developer guides
it uses a compressed version of the same table-based sfnt structure used by
truetype, opentype, and open font format, but adds metadata and private-use data structures, including predefined fields allowing foundries and vendors to provide license information if desired.
... there are three main benefits to using woff: the font data is compressed, so sites using woff will use less bandwidth and will load faster than if they used equivalent uncompressed
truetype or opentype files.
... many font vendors that are unwilling to license their
truetype or opentype format fonts for use on the web will license woff format fonts.
...it works exactly like opentype and
truetype format fonts do, except it will likely let your content download more efficiently due to the addition of compression.
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
reportvalidity() returns
true if the element's value passes validity checks; otherwise, returns false.
... :indeterminate checkbox elements whose indeterminate property is set to
true by javascript, radio elements, when all radio buttons with the same name value in the form are unchecked, and <progress> elements in an indeterminate state :valid form controls that can have constraint validation applied and are currently valid.
...the validity object includes: validitystate.valuemissing validitystate.typemismatch validitystate.patternmismatch validitystate.toolong validitystate.tooshort validitystate.rangeunderflow validitystate.rangeoverflow validitystate.stepmismatch validitystate.badinput validitystate.valid validitystate.customerror for each of these boolean properties, a value of
true indicates that the specified reason validation may have failed is
true, with the exception of the valid property, which is
true if the element's value obeys all constraints.
...if there is no custom error message, and none of the other properties return
true, valid will be
true, and the form can be submitted.
Global attributes - HTML: Hypertext Markup Language
the attribute must take one of the following values:
true or the empty string, which indicates that the element must be editable; false, which indicates that the element must not be editable.
...it can have the following values:
true, which indicates that the element may be dragged false, which indicates that the element may not be dragged.
...it may have the following values:
true, which indicates that the element should be, if possible, checked for spelling errors; false, which indicates that the element should not be checked for spelling errors.
...from html 4.01 specification, the concept of global attributes is introduced and the dir, lang, style, id, class, tabindex, accesskey, and title are now
true global attributes.
Browser detection using the user agent - HTTP
problems like these can be avoided by testing for support of the feature itself instead: var islookbehindsupported = false; try { new regexp("(?<=)"); islookbehindsupported =
true; } catch (err) { // if the agent doesn't support lookbehinds, the attempted // creation of a regexp object using that syntax throws and // islookbehindsupported remains false.
...ts" in navigator) { hastouchscreen = navigator.maxtouchpoints > 0; } else if ("msmaxtouchpoints" in navigator) { hastouchscreen = navigator.msmaxtouchpoints > 0; } else { var mq = window.matchmedia && matchmedia("(pointer:coarse)"); if (mq && mq.media === "(pointer:coarse)") { hastouchscreen = !!mq.matches; } else if ('orientation' in window) { hastouchscreen =
true; // deprecated, but good fallback } else { // only as a last resort, fall back to user agent sniffing var ua = navigator.useragent; hastouchscreen = ( /\b(blackberry|webos|iphone|iemobile)\b/i.test(ua) || /\b(android|windows phone|ipad|ipod)\b/i.test(ua) ); } } if (hastouchscreen) document.getelementbyid("examplebutton").style.pa...
... var ua=navigator.useragent, iswebkit=/\b(ipad|iphone|ipod)\b/.test(ua) && /webkit/.test(ua) && !/edge/.test(ua) && !window.msstream; var mediaqueryupdated =
true, mql = []; function whenmediachanges(){mediaqueryupdated =
true} var listentomediaquery = iswebkit ?
...function(mq) { for (var i=0,len=mql.length|0; i<len; i=i+1|0) if (mql[i][0] === mq) mql.splice(i, 1); mq.removelistener(whenmediachanges); } : listentomediaquery; var orientationchanged = false; addeventlistener("orientationchange", function(){ orientationchanged =
true; }, passive_listener_option); addeventlistener("resize", settimeout.bind(0,function(){ if (orientationchanged && !mediaqueryupdated) for (var i=0,len=mql.length|0; i<len; i=i+1|0) mql[i][1]( mql[i][0] ); mediaqueryupdated = orientationchanged = false; },0)); which part of the user agent contains the information you are looking for?
Atomics - JavaScript
wait and notify the wait() and notify() methods are modeled on linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes
true and are typically used as blocking constructs.
...returns
true if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock).
... examples using atomics const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.and(ta, 0, 1); atomics.load(ta, 0); // 1 atomics.compareexchange(ta, 0, 5, 12); atomics.load(ta, 0); // 12 atomics.exchange(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.islockfree(1); //
true atomics.islockfree(2); //
true atomics.islockfree(3); // false atomics.islockfree(4); //
true atomics.or(ta, 0, 1); atomics.load(ta, 0); // 5 atomics.store(ta, 0, 12); // 12 atomics.sub(ta, 0, 2); atomics.load(ta, 0); // 3 atomics.xor(ta, 0, 1); atomics.load(ta, 0); // 4 waiting and notifiying given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32arra...
...as long as that is
true, it will not go on.
Intl.Locale.prototype.numeric - JavaScript
numeric is a boolean value, which means that it can be either
true or false.
...if numeric is set to
true, then the locale will take numeric characters into account when collating strings.
...if you want to set numeric to
true, simply adding the kn key will suffice.
... let numericviaobj= new intl.locale("en-latn-us", {numeric:
true}); console.log(us12hour.numeric); // prints "
true" specifications specification ecmascript internationalization api (ecma-402) ...
JSON.stringify() - JavaScript
examples using json.stringify json.stringify({}); // '{}' json.stringify(
true); // '
true' json.stringify('foo'); // '"foo"' json.stringify([1, 'false', false]); // '[1,"false",false]' json.stringify([nan, null, infinity]); // '[null,null,null]' json.stringify({ x: 5 }); // '{"x":5}' json.stringify(new date(2006, 0, 2, 15, 4, 5)) // '"2006-01-02t15:04:05.000z"' json.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' json.stringif...
....stringify({ [symbol('foo')]: 'foo' }); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, [symbol.for('foo')]); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { return 'a symbol'; } }); // undefined // non-enumerable properties: json.stringify( object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable:
true } }) ); // '{"y":"y"}' // bigint values throw json.stringify({x: 2n}); // typeerror: bigint value can't be serialized in json the replacer parameter the replacer parameter can be either a function or an array.
... var a = json.stringify({ foo: "bar", baz: "quux" }) //'{"foo":"bar","baz":"quux"}' var b = json.stringify({ baz: "quux", foo: "bar" }) //'{"baz":"quux","foo":"bar"}' console.log(a !== b) //
true // some memoization functions use json.stringify to serialize arguments, // which may cause a cache miss when encountering the same object like above example of using json.stringify() with localstorage in a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of...
... json.stringify(): // creating an example of json var session = { 'screens': [], 'state':
true }; session.screens.push({ 'name': 'screena', 'width': 450, 'height': 250 }); session.screens.push({ 'name': 'screenb', 'width': 650, 'height': 350 }); session.screens.push({ 'name': 'screenc', 'width': 750, 'height': 120 }); session.screens.push({ 'name': 'screend', 'width': 250, 'height': 60 }); session.screens.push({ 'name': 'screene', 'width': 390, 'height': 120 }); session.screens.push({ 'name': 'screenf', 'width': 1240, 'height': 650 }); // converting the json string with json.stringify() // then saving with localstorage in the name of session localstorage.setitem('session', json.stringify(session)); // example of how to transform the string generated through // json.stringify() and saved...
Number.isInteger() - JavaScript
description if the target value is an integer, return
true, otherwise return false.
...the method will also return
true for floating point numbers that can be represented as integer.
... polyfill number.isinteger = number.isinteger || function(value) { return typeof value === 'number' && isfinite(value) && math.floor(value) === value; }; examples using isinteger number.isinteger(0); //
true number.isinteger(1); //
true number.isinteger(-100000); //
true number.isinteger(99999999999999999999999); //
true number.isinteger(0.1); // false number.isinteger(math.pi); // false number.isinteger(nan); // false number.isinteger(infinity); // false number.isinteger(-infinity); // false number.isinteger('10'); // false number.isinteger(
true); // false number.isinteger(false); // false number.isinteger([1]); // false number.isinteger(5.0); //
true number.isinteger(5.000000000000001); // false number.isinteger(5...
....0000000000000001); //
true specifications specification ecmascript (ecma-262)the definition of 'number.isinteger' in that specification.
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.assign() - JavaScript
polyfill this polyfill doesn't support symbol properties, since es5 doesn't have symbols anyway: if (typeof object.assign !== 'function') { // must be writable:
true, enumerable: false, configurable:
true object.defineproperty(object, "assign", { value: function assign(target, varargs) { // .length of function is 2 'use strict'; if (target === null || target === undefined) { throw new typeerror('cannot convert undefined or null to object'); } var to = object(target); for (var index = 1; index < arguments.length; i...
...ource = arguments[index]; if (nextsource !== null && nextsource !== undefined) { for (var nextkey in nextsource) { // avoid bugs when hasownproperty is shadowed if (object.prototype.hasownproperty.call(nextsource, nextkey)) { to[nextkey] = nextsource[nextkey]; } } } } return to; }, writable:
true, configurable:
true }); } examples cloning an object const obj = { a: 1 }; const copy = object.assign({}, obj); console.log(copy); // { a: 1 } warning for deep clone for deep cloning, we need to use alternatives, because object.assign() copies property values.
... }, baz: { value: 3, enumerable:
true // baz is an own enumerable property.
... } }); const copy = object.assign({}, obj); console.log(copy); // { baz: 3 } primitives will be wrapped to objects const v1 = 'abc'; const v2 =
true; const v3 = 10; const v4 = symbol('foo'); const obj = object.assign({}, v1, null, v2, undefined, v3, v4); // primitives will be wrapped, null and undefined will be ignored.
Object.defineProperties() - JavaScript
data descriptors and accessor descriptors may optionally contain the following keys: configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
... enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
... writable
true if and only if the value associated with the property may be changed with an assignment operator.
... var keys = object.keys(properties); var descs = []; for (var i = 0; i < keys.length; i++) descs.push([keys[i], converttodescriptor(properties[keys[i]])]); for (var i = 0; i < descs.length; i++) object.defineproperty(obj, descs[i][0], descs[i][1]); return obj; } examples using object.defineproperties var obj = {}; object.defineproperties(obj, { 'property1': { value:
true, writable:
true }, 'property2': { value: 'hello', writable: false } // etc.
Object.prototype.hasOwnProperty() - JavaScript
note hasownproperty returns
true even if the value of the property is null or undefined.
... o = new object(); o.propone = null; o.hasownproperty('propone'); // returns
true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns
true examples using hasownproperty to test for a property's existence the following example determines whether the o object contains a property named prop: o = new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty('prop'); // returns
true direct vs.
... inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns
true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties.
...exists that an object might have a property with this name, it is necessary to use an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty // and call it with 'this' set to foo ({}).hasownproperty.call(foo, 'bar'); //
true // it's also possible to use the hasownproperty property // from the object prototype for this purpose object.prototype.hasownproperty.call(foo, 'bar'); //
true note that in the last case there are no newly created objects.
Object - JavaScript
however, an object may be deliberately created for which this is not
true (e.g.
... by object.create(null)), or it may be altered so that this is no longer
true (e.g.
... examples using object given undefined and null types the following examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) using object to create boolean objects the following examples store boolean objects in o: // equivalent to o = new boolean(
true) let o = new object(
true) // equivalent to o = new boolean(false) let o = new object(boolean()) object prototypes when altering the behavior of existing object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic.
...for example: var person = function(name) { this.name = name; this.cantalk =
true; }; person.prototype.greet = function() { if (this.cantalk) { console.log('hi, i am ' + this.name); } }; var employee = function(name, title) { person.call(this, name); this.title = title; }; employee.prototype = object.create(person.prototype); employee.prototype.constructor = employee; //if you don't set object.prototype.constructor to employee, ...
RegExp.prototype.sticky - JavaScript
property attributes of regexp.prototype.sticky writable no enumerable no configurable yes description the value of sticky is a boolean and
true if the "y" flag was used; otherwise, false.
... examples using a regular expression with the sticky flag var str = '#foo#'; var regex = /foo/y; regex.lastindex = 1; regex.test(str); //
true regex.lastindex = 5; regex.test(str); // false (lastindex is taken into account with sticky flag) regex.lastindex; // 0 (reset after match failure) anchored sticky flag for several versions, firefox's spidermonkey engine had a bug with regard to the ^ assertion and the sticky flag which allowed expressions starting with the ^ assertion and using the sticky flag to match when they shouldn't.
...perhaps because of the bug, the es2015 specification specifically calls out the fact that: when the y flag is used with a pattern, ^ always matches only at the beginning of the input, or (if multiline is
true) at the beginning of a line.
... examples of correct behavior: var regex = /^foo/y; regex.lastindex = 2; regex.test('..foo'); // false - index 2 is not the beginning of the string var regex2 = /^foo/my; regex2.lastindex = 2; regex2.test('..foo'); // false - index 2 is not the beginning of the string or line regex2.lastindex = 2; regex2.test('.\nfoo'); //
true - index 2 is the beginning of a line specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.sticky' in that specification.
TypedArray.prototype.every() - JavaScript
return value
true if the callback function returns a truthy value for every array element; otherwise, false.
...otherwise, if callback returned a
true value for all elements, every will return
true.
... function isbigenough(element, index, array) { return element >= 10; } new uint8array([12, 5, 8, 130, 44]).every(isbigenough); // false new uint8array([12, 54, 18, 130, 44]).every(isbigenough); //
true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
... new uint8array([12, 5, 8, 130, 44]).every(elem => elem >= 10); // false new uint8array([12, 54, 18, 130, 44]).every(elem => elem >= 10); //
true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.every' 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.
... otherwise javascript attempts to convert non-numeric types to numeric values: boolean values
true and false are converted to 1 and 0 respectively.
... examples string to string comparison console.log("a" < "b"); //
true console.log("a" < "a"); // false console.log("a" < "3"); // false string to number comparison console.log("5" < 3); // false console.log("3" < 3); // false console.log("3" < 5); //
true console.log("hello" < 5); // false console.log(5 < "hello"); // false console.log("5" < 3n); // false console.log("3" < 5n); //
true number to number comparison console...
....log(5 < 3); // false console.log(3 < 3); // false console.log(3 < 5); //
true number to bigint comparison console.log(5n < 3); // false console.log(3 < 5n); //
true comparing boolean, null, undefined, nan console.log(
true < false); // false console.log(false <
true); //
true console.log(0 <
true); //
true console.log(
true < 1); // false console.log(null < 0); // false console.log(null < 1); //
true console.log(undefined < 3); // false console.log(3 < undefined); // false console.log(3 < nan); // false console.log(nan < 3); // false specifications specification ecmascript (ecma-262)the definition of 'relational operators' in that specification.
yield* - JavaScript
the value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is
true).
... 1; yield* g1(); yield 5; } const iterator = g2(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: false} console.log(iterator.next()); // {value: 4, done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: undefined, done:
true} other iterable objects besides generator objects, yield* can also yield other kinds of iterables (e.g., arrays, strings, or arguments objects).
...ole.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: "3", done: false} console.log(iterator.next()); // {value: "4", done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: 6, done: false} console.log(iterator.next()); // {value: undefined, done:
true} the value of yield* expression itself yield* is an expression, not a statement—so it evaluates to a value.
...returnvalue = yield* g4(); console.log(g4returnvalue) // 'foo' return g4returnvalue; } const iterator = g5(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: false} done is false because g5 generator isn't finished, only g4 console.log(iterator.next()); // {value: 'foo', done:
true} specifications specification ecmascript (ecma-262)the definition of 'yield' in that specification.
yield - JavaScript
in this case, execution of the generator ends and an iteratorresult is returned to the caller in which the value is undefined and done is
true.
...in this case, execution of the generator ends and an iteratorresult is returned to the caller in which the value is the value specified by the return statement and done is
true.
... let applestore = countapplesales() // generator { } console.log(applestore.next()) // { value: 3, done: false } console.log(applestore.next()) // { value: 7, done: false } console.log(applestore.next()) // { value: 5, done: false } console.log(applestore.next()) // { value: undefined, done:
true } you can also send a value with next(value) into the generator.
... 'step' evaluates as a return value in this syntax [rv] = yield [expression] function* counter(value) { let step; while (
true) { step = yield ++value; if (step) { value += step; } } } const generatorfunc = counter(0); console.log(generatorfunc.next().value); // 1 console.log(generatorfunc.next().value); // 2 console.log(generatorfunc.next().value); // 3 console.log(generatorfunc.next(10).value); // 14 console.log(generatorfunc.next().value); // 15 console.log(generatorfunc.next(10).value); // 26 specifications specification ecmascript (ecma-262)the definition of 'yield' in that specification.
for - JavaScript
if this expression evaluates to
true, statement is executed.
...if omitted, the condition always evaluates to
true.
... statement a statement that is executed as long as the condition evaluates to
true.
...again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is
true at some point.
import - JavaScript
import '/modules/my-module.js'; this works with dynamic imports as well: (async () => { if (somethingis
true) { // import module for side effects await import('/modules/my-module.js'); } })(); if your project uses packages that export esm, you can also import them for side effects only.
... (async () => { if (somethingis
true) { const { default: mydefault, foo, bar } = await import('/modules/my-module.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time.
...(static import only supports static specifiers.) when the module being imported has side effects, and you do not want those side effects unless some condition is
true.
... the module: file.js function getjson(url, callback) { let xhr = new xmlhttprequest(); xhr.onload = function () { callback(this.responsetext) }; xhr.open('get', url,
true); xhr.send(); } export function getusefulcontents(url, callback) { getjson(url, data => callback(json.parse(data))); } the main program: main.js import { getusefulcontents } from '/modules/file.js'; getusefulcontents('http://www.example.com', data => { dosomethinguseful(data); }); dynamic import this example shows how to load functionality on to a page based on a user action, in thi...
externalResourcesRequired - SVG: Scalable Vector Graphics
in particular, if an element sets externalresourcesrequired="
true", then all style sheets must be available since any style sheet might affect the rendering of that element.
... because setting externalresourcesrequired="
true" on a container element will have the effect of disabling progressive display of the contents of that container, if that container includes elements that reference external resources, authors should avoid simply setting externalresourcesrequired="
true" on the outermost <svg> element on a universal basis.
... instead, it is better to specify externalresourcesrequired="
true" on those particular graphics elements or container elements which specifically need the availability of external resources in order to render properly.
... usage notes value false |
true default value false animatable no
true this value indicates that resources external to the current document are required.
panel - Archive of obsolete content
from firefox 33 you can enable a context menu by passing contextmenu:
true to the panel's constructor.
...optional, default to
true.
...script defaults to
true.
private-browsing - Archive of obsolete content
opting into private browsing add-ons built using the sdk must opt into private browsing by setting the following key in their package.json file: "permissions": {"private-browsing":
true} if an add-on has not opted in, then the high-level sdk modules will not expose private windows, or objects (such as tabs) that are associated with private windows: the windows module will not list any private browser windows, generate any events for private browser windows, or let the add-on open any private browser windows the tabs module will not list any tabs that belong to priva...
...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.
selection - Archive of obsolete content
getting the selection when iscontiguous is
true returns the text of the first selection.
...getting the selection when iscontiguous is
true returns the text of the first selection.
... iscontiguous
true if the current selection is a single, contiguous selection, and false if there are two or more discrete selections, each of which may or may not be spatially adjacent.
io/file - Archive of obsolete content
exists(path) returns
true if a file exists at the given path and false otherwise.
... returns boolean :
true if the file exists and false otherwise.
... isfile(path) returns
true only if this path specifies a file.
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.
ui/frame - Archive of obsolete content
if you send a json object, the sdk takes care of serializing and deserializing it for you: // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); },
true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source.postmessage("pong", event.origin); } } globals constructors frame(options) creates an frame.
... message listen to this event if you want to receive messages from frame scripts that are sent using window.parent.postmessage(): // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage("ping", "*"); },
true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data == "ping") { e.source.postmessage("pong", e.origin); } } arguments event : this contains three properties: source, which defines a postmessage() function which you can use to send messages back to this particular frame i...
...if the payload was a json object, you can access it like an object: // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); },
true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source.postmessage("pong", e.origin); } } ...
Dialogs and Prompts - Archive of obsolete content
programmatic button access if you want to access the accept ("ok") and cancel buttons from script, use this: // disable the ok and cancel btns document.documentelement.getbutton("accept").disabled =
true; document.documentelement.getbutton("cancel").disabled =
true; links dialog.xml — xbl bindings for <dialog> and <dialogheader> elements.
...the code to open a dialog named mydialog.xul and pass it arguments: var params = {inn:{name:"foo", description:"bar", enabled:
true}, out:null}; window.opendialog("chrome://myext/content/mydialog.xul", "", "chrome, dialog, modal, resizable=yes", params).focus(); if (params.out) { // user clicked ok.
... // notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0].out = {name:document.getelementbyid("name").value, description:document.getelementbyid("description").value, enabled:document.getelementbyid("enabled").checked}; return
true; } see also passing parameter to a dialog and getting return values from it.
HTML to DOM - Archive of obsolete content
var frame = document.getelementbyid("sample-frame"); if (!frame) { // create frame frame = document.createelement("iframe"); // iframe (or browser on older firefox) frame.setattribute("id", "sample-frame"); frame.setattribute("name", "sample-frame"); frame.setattribute("type", "content"); frame.setattribute("collapsed", "
true"); document.getelementbyid("main-window").appendchild(frame); // or // document.documentelement.appendchild(frame); // set restrictions as needed frame.webnavigation.allowauth = false; frame.webnavigation.allowimages = false; frame.webnavigation.allowjavascript = false; frame.webnavigation.allowmetaredirects =
true; frame.webnavigation.allowplugins = false; frame.webnavigatio...
...// when done remove frame or set location "about:blank" settimeout(function (){ var frame = document.getelementbyid("sample-frame"); // remove frame // frame.destroy(); // if using browser element instead of iframe frame.parentnode.removechild(frame); // or set location "about:blank" // frame.contentdocument.location.href = "about:blank"; },10); },
true); } // load a page frame.contentdocument.location.href = "http://www.mozilla.org/"; // or // frame.webnavigation.loaduri("http://www.mozilla.org/",components.interfaces.nsiwebnavigation,null,null,null); if you are starting with an html string, you can convert it to a data uri and use that to load in the browser element.
... <vbox hidden="false" height="0"> <iframe type="content" src="" name="donkey-browser" hidden="false" id="donkey-browser" height="0"/> </vbox> then, in your extension's "load" event handler: onload: function() { donkeybrowser = document.getelementbyid("donkey-browser"); if (donkeybrowser) { donkeybrowser.style.height = "0px"; donkeybrowser.webnavigation.allowauth =
true; donkeybrowser.webnavigation.allowimages = false; donkeybrowser.webnavigation.allowjavascript = false; donkeybrowser.webnavigation.allowmetaredirects =
true; donkeybrowser.webnavigation.allowplugins = false; donkeybrowser.webnavigation.allowsubframes = false; donkeybrowser.addeventlistener("domcontentloaded", function (e) { donkeyfire.donkeybrowser_onpageload(e); },
true); } with ...
Preferences - Archive of obsolete content
service;1"] .getservice(components.interfaces.nsiprefservice); this._branch = prefservice.getbranch(branch_name); this._branch.queryinterface(components.interfaces.nsiprefbranch2); this._callback = callback; } preflistener.prototype.observe = function(subject, topic, data) { if (topic == 'nspref:changed') this._callback(this._branch, data); }; /** * @param {boolean=} trigger if
true triggers the registered function * on registration, that is, when this method is called.
... function() { if (this._branch) this._branch.removeobserver('', this); }; var mylistener = new preflistener( "extensions.myextension.", function(branch, name) { switch (name) { case "pref1": // extensions.myextension.pref1 was changed break; case "pref2": // extensions.myextension.pref2 was changed break; } } ); mylistener.register(
true); note: you need to keep a reference to the preference branch you are observing (unless it is the root branch) or it will get garbage collected and will never notify you.
...if so, it will return
true, otherwise false.
StringView - Archive of obsolete content
arguments wholebuffer optional a boolean expressing whether the returned base64-encoded string will correspond to the whole buffer (
true) or to the stringview (false or omitted).
... examples alert((new stringview("hello world!")).valueof() === "hello world!"); //
true javascript calls the stringview.valueof() method to convert an object to a primitive value.
... examples alert((new stringview("hello world!")).tostring() === "hello world!"); //
true the stringview.tostring() method is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected.
Enhanced Extension Installation - Archive of obsolete content
}; tracking install locations since there are only two locations, the installed location of an extension is expressed throughout the code using a boolean value, often referred to as isprofile -
true if the item is installed in the profile directory's extensions folder.
... regardless of whether or not the extension system is called from the startup process with the dirty flag set to
true (i.e.
... extension authors installing into restricted install locations can specify that their item does not show up in the extensions ui by using the <em:hidden>
true<em:hidden> property in their install manifests.
How to convert an overlay extension to restartless - Archive of obsolete content
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 request.onerror(event); }; request.send(); } loadfile("chrome://mya...
...in such cases, request.readystate == 4, request.status == 0 and request.response will evaluate to
true.
...the big culprits are jsm files and locale files (namely property files), though in some situations this is
true for dynamically loaded image files too.
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
passing
true as a parameter for the nsilocalfile.remove() method will recursively delete folders and files.
... let's see what happens when we pass
true to delete all the contents of a folder.
... listing 14: writing a binary file var array = [88, 85, 76]; file.initwithpath('c:\\temp\\temp.txt'); if (file.exists()) file.remove(
true); file.create(file.normal_file_type, 0666); var filestream = components.classes['@mozilla.org/network/file-output-stream;1'] .createinstance(components.interfaces.nsifileoutputstream); filestream.init(file, 2, 0x200, false); var binarystream = components.classes['@mozilla.org/binaryoutputstream;1'] .createinstance(components.interfaces.nsibinaryoutputstream); b...
Intercepting Page Loads - Archive of obsolete content
this._loadhandler = function() {that._onpageload(); }; gbrowser.addeventlistener("load", this._loadhandler,
true); gbrowser is a global object that corresponds to the tabbrowser element in the main browser window.
... gbrowser.removeeventlistener("load", this._loadhandler,
true); finally, the actual code for the handler, which is very simple: _onpageload : function(event) { // this is the content document of the loaded page.
...here's a code sample that keeps track of your progress listeners for all tabs: init : function() { gbrowser.browsers.foreach(function (browser) { this._toggleprogresslistener(browser.webprogress,
true); }, this); gbrowser.tabcontainer.addeventlistener("tabopen", this, false); gbrowser.tabcontainer.addeventlistener("tabclose", this, false); }, uninit : function() { gbrowser.browsers.foreach(function (browser) { this ._toggleprogresslistener(browser.webprogress, false); }, this); gbrowser.tabcontainer.removeeventlistener("tabopen", this, false); gbrowser.tabcontainer.removee...
XUL user interfaces - Archive of obsolete content
olumn/> </columns> <rows> <row> <label class="text-prompt" value="date:" accesskey="d" control="date-text"/> <textbox id="date-text" type="timed" timeout="750" oncommand="refresh();"/> </row> <row> <label value="day:"/> <hbox id="day-box"> <label class="day" value="sunday" disabled="
true"/> <label class="day" value="monday" disabled="
true"/> <label class="day" value="tuesday" disabled="
true"/> <label class="day" value="wednesday" disabled="
true"/> <label class="day" value="thursday" disabled="
true"/> <label class="day" value="friday" disabled="
true"/> <label class="day" value="saturday" disabled="
true"/> ...
...sh() } // called by date textbox function refresh() { var d = datebox.value var thedate = null showstatus(null) if (d != "") { try { var a = d.split("/") var thedate = new date(a[2], a[0] - 1, a[1]) showstatus(thedate) } catch (ex) {} } setday(thedate) } // internal function setday(adate) { if (currentday) currentday.setattribute("disabled", "
true") if (adate == null) currentday = null else { var d = adate.getday() currentday = daybox.firstchild while (d-- > 0) currentday = currentday.nextsibling currentday.removeattribute("disabled") } datebox.focus(); } function showstatus(adate) { if (adate == null) { status.removeattribute("warning") status.setattribute("label", "") } else if (adate === fals...
...e || isnan(adate.gettime())) { status.setattribute("warning", "
true") status.setattribute("label", "date is not valid") } else { status.removeattribute("warning") status.setattribute("label", adate.tolocaledatestring()) } } to see the result exactly as intended, use the default theme in your browser.
Install.js - Archive of obsolete content
['classic', 'modern'] extpostinstallmessage: null, // set to null for no post-install message // --- editable items end --- profileinstall:
true, silentinstall: false, install: function() { var jarname = this.extshortname + '.jar'; var profiledir = install.getfolder('profile', 'chrome'); // parse http arguments this.parsearguments(); // check if extension is already installed in profile if (file.exists(install.getfolder(profiledir, jarname))) { if (!this.silentinstall) { install.alert('updating existing ...
...profile install of ' + this.extfullname + ' to version ' + this.extversion + '.'); } this.profileinstall =
true; } else if (!this.silentinstall) { // ask user for install location, profile or browser dir?
...ed) { 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) { install.alert('error: could not install ' + this.extfullname + ' ' + this.extversion + ' (error code: ' + err + ')'); } install.cancelinstall(err); } }; xpiinstaller.install(); ...
MMgc - Archive of obsolete content
this is
true whether the object containing the pointer is gcobject or rcobject.
...if this isn't
true we hope to eliminate other threads from doing this and if we can't do that we will be forced to make our gc thread safe, although we hope we don't have to do that.
...e main thread will require locking and may suffer due to lock overhead/contention supporting mac classic's cooperative threads makes this approach harder flash's frame based architecture gives us a very natural place to do this work we have better control over how much time is spent marking without threads when smp systems become more prevalent it may be worth investigating this approach because
true parallelism may afford better performance.
Code snippets - Archive of obsolete content
let collection = "forms"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full =
true; coll.recordhandler = function(item) { item.collection = collection; item.decrypt(); console.log(item.cleartext); }; coll.get(); print an individual record let collection = "history"; let id = "guid_goes_here"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let recordtype = weave.engines.get(collection)._recordo...
...bj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full =
true; coll.ids = [id]; coll.recordhandler = function(item) { item.collection = collection; item.decrypt(); console.log(item.cleartext); }; coll.get(); count types of bookmark records components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let deleted = 0; let items = {}; let collection = "bookmarks"; let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full =
true; coll.limit = null; coll.recordhandler = function(item) { item.collection = collection; item.decrypt(); if (item.deleted) { deleted++;...
...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.storageurl + collection + "/" + id); let del = new cryptowrapper(collection, id); del.deleted =
true; del.encrypt(); // save the old value.
JavaScript Client API - Archive of obsolete content
itemexists(guid) should simply return
true if an item with the given guid exists in the store, false otherwise.
...function foostore(name) { store.call(this, name); } foostore.prototype = { __proto__: store.prototype, itemexists: function(guid) { // return
true if an item with given guid exists in the store.
... this._enabled =
true; } break; case "weave:engine:stop-tracking": if (this._enabled) { // remove event handler or observer here ...
Introducing the Audio API extension - Archive of obsolete content
the following example extracts the data from an audio element: <!doctype html> <html> <head> <title>javascript metadata example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="
true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </scrip...
... we can extend the previous example to visualize the timestamp and the first two samples in a <div> element: <!doctype html> <html> <head> <title>javascript visualization example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="
true" style="width: 512px;"> </audio> <pre id="raw">hello</pre> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } function audioavailable(event) { var framebuffer = event.framebuffer; var t = event.time; ...
... var prebuffersize = samplerate * 0.020; // initial buffer is 20 ms var autolatency =
true, started = new date().valueof(); ...
Menu - Archive of obsolete content
isshowing boolean
true if the menu is currently visible and false otherwise.
... disabled boolean if
true, the menuitem is disabled.
... the selector must be a
true css selector, not a jquery or other type of pseudo-selector.
Using Breakpoints in Venkman - Archive of obsolete content
stop if result is
true effectively makes this a conditional breakpoint.
... 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.
... the //@jsd_break comment will insert a breakpoint which is set to execute the script that follows and stop if the result is
true.
Using XPInstall to Install Plugins - Archive of obsolete content
) has already been called // using the install object's execute method to block on a native installer execute("setup.exe", "-s",
true); // in the above sample, assume that running "setup -s" from the // command prompt runs the setup executable, and that "-s" is some // invocation parameter defined by the setup.exe file, perhaps to force // the installer to run silently.
...// by passing '
true' we are telling the install script to block // on the execution of the installable, and do it synchronously // must call performinstall to make it all happen...
...this install.js file assumes that the plugin software that is to be installed consists of both a dll and an xpt file, which is not always
true.
Windows Install - Archive of obsolete content
diskspaceavailable(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.
...flongfilepath; var sshortfilepath; if(fren8dot3ini != null) { for(i = 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 = adddirect...
...ory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fprogram, // 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 ...
execute - Archive of obsolete content
the optional blocking argument, when set to
true, specifies that the installation should wait for this executable to finish before processing the next queued install command.
...the following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c",
true); when you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required.
... this means that in order to pass three command-line arguments (-c, -d, and -s) to the executable, you should format the args string as follows: err = file.execute(myfile, '"-c""-d""-s"',
true); //technically, given the rules above, you could also pass the same //arguments with the following line, but the result is much less //readable: err = file.execute(myfile, "\"-c\"\"-d\"\"-s\"",
true); also see the note about binaries on the macintosh platform in addfile.
showpopup - Archive of obsolete content
« xul reference home showpopup type: boolean note: applies to: thunderbird, seamonkeyif
true, the popup will be shown.
...you can set this to false and set the autofill attribute to
true to emulate a communicator 4.x style autocomplete textbox.
... the default value is
true.
Index - Archive of obsolete content
56 clicktoscroll clicktoscroll, if
true, the arrows must be clicked to scroll the scrollbox content.
... 1089 appendchild node appendchild ( node newchild ) 1090 arrowscrollbox xul elements, xul reference clicktoscroll, if
true, the arrows must be clicked to scroll the scrollbox content.
...if the condition is
true, the corresponding action body is generated; otherwise the result is ignored and no content is generated.
ContextMenus - Archive of obsolete content
function checkcontextmenu(event) { if (event.target.localname == "textbox") event.preventdefault(); } function init() { var container = document.getelementbyid("container"); container.addeventlistener("contextmenu", checkcontextmenu,
true); } the 'checkcontextmenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventdefault method.
... <menupopup id="link-menu"> <menuitem label="open link" default="
true"/> <menuitem label="open in new window"/> <menuitem label="properties"/> </menupopup> the default attribute has been set to
true on the first menu item ('open link').
... to hide an item, set its hidden property to
true.
PopupKeys - Archive of obsolete content
note that the last argument here is
true to listen for events during the capturing phase of event propagation: window.addeventlistener("keypress", someaction,
true); however, the default listener provides all the suitable responses to keys, so there shouldn't be a need to handle keys yourself.
...when the ignorekeys attribute is placed on a <menupopup> or <panel> element, and its value is set to the value
true, the key listener is not used.
... <panel ignorekeys="
true"> in this case, none of the key handling described above is performed.
Template and Tree Listeners - Archive of obsolete content
all you need to do is add a tree builder observer which returns
true for the candrop method.
...var treebuilderobserver = { candropbeforeafter : function(idx, orient) { return false; }, candropon : function(idx, orient) { return
true; }, candrop : function(idx, orient) { return !orient; }, ondrop : function(idx, orient) { // do something here }, }; //tree.builderview.addobserver(treebuilderobserver); // ppchenhui@hotmail.com tree.builder.queryinterface (components.interfaces.nsixultreebuilder) .addobserver(treebuilderobserver); the candropbeforeafter method returns false since we do not want to allow before and after drops.
... the candropon method returns
true however.
Adding Buttons - Archive of obsolete content
syntax of buttons the button tag has the following syntax: <button id="identifier" class="dialog" label="ok" image="images/image.jpg" disabled="
true" accesskey="t"/> the attributes are as follows, all of which are optional: id a unique identifier so that you can identify the button with.
... disabled if this attribute is set to
true, the button is disabled.
... some examples of buttons example 1 : source view <button label="normal"/> <button label="disabled" disabled="
true"/> the examples above will generate the buttons in the image.
Adding Methods to XBL-defined Elements - Archive of obsolete content
xul: <box id="num" class="labeledbutton" title="number of things:" value="52"/> <button label="show" oncommand="document.getelementbyid('num').showtitle(
true)"/> <button label="hide" oncommand="document.getelementbyid('num').showtitle(false)"/> xbl: <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> </content> <implementation> <method name="showtitle"> <parameter name="state"/> <body> if (state) { document.getanonymousnodes(this)[0].setattri...
...for example, we could move the show and hide buttons into the xbl file and do the following: example 1: source <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> <xul:button label="show" oncommand="document.getbindingparent(this).showtitle(
true);"/> <xul:button label="hide" oncommand="document.getbindingparent(this).showtitle(false);"/> </content> <implementation> <method name="showtitle"> <parameter name="state"/> <body> if (state) { document.getanonymousnodes(this)[0].setattribute("style","visibility: visible"); } else { document.getanonymousnodes(this)[0].setattribute("style...
...here are some examples: <constructor> if (this.childnodes[0].getattribute("open") == "
true"){ this.loadchildren(); } </constructor> <destructor action="savemyself(this);"/> the next section shows how to add event handlers to xbl-defined elements.
Creating Dialogs - Archive of obsolete content
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.
.../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 because they are fruity"/> <radio id="violet" selected="
true" label="strawberries because of their colour"/> <radio id="yellow" label="bananas because they are pre-packaged"/> </gr...
Localization - Archive of obsolete content
onload="initsearchlist()" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="findfile.js"/> <popupset> <menupopup id="editpopup"> <menuitem label="&cutcmd.label;" accesskey="&cutcmd.accesskey;"/> <menuitem label="©cmd.label;" accesskey="©cmd.accesskey;"/> <menuitem label="&pastecmd.label;" accesskey="&pastecmd.accesskey;" disabled="
true"/> </menupopup> </popupset> <keyset> <key id="cut_cmd" modifiers="accel" key="&cutcmd.commandkey;"/> <key id="copy_cmd" modifiers="accel" key="©cmd.commandkey;"/> <key id="paste_cmd" modifiers="accel" key="&pastecmd.commandkey;"/> <key id="close_cmd" keycode="vk_escape" oncommand="window.close();"/> </keyset> <vbox flex="1"> <toolbox> <menubar id="findfiles-menubar"> ...
...esskey="&editmenu.accesskey;"> <menupopup id="edit-popup"> <menuitem label="&cutcmd.label;" accesskey="&cutcmd.accesskey;" key="cut_cmd"/> <menuitem label="©cmd.label;" accesskey="©cmd.accesskey;" key="copy_cmd"/> <menuitem label="&pastecmd.label;" accesskey="&pastecmd.accesskey;" key="paste_cmd" disabled="
true"/> </menupopup> </menu> </menubar> <toolbar id="findfiles-toolbar"> <toolbarbutton id="opensearch" label="&opencmdtoolbar.label;"/> <toolbarbutton id="savesearch" label="&savecmdtoolbar.label;"/> </toolbar> </toolbox> <tabbox> <tabs> <tab label="&searchtab;" selected="
true"/> <tab label="&optionstab;"/> </tabs> <tabpanels> <tabpanel id="searchpanel" ...
...tem label="&type.size;"/> <menuitem label="&type.date;"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="searchmode"> <menupopup> <menuitem label="&mode.is;"/> <menuitem label="&mode.isnot;"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="find-text" flex="1" editable="
true" datasources="file:///mozilla/recents.rdf" ref="http://www.xulplanet.com/rdf/recent/all"> <template> <menupopup> <menuitem label="rdf:http://www.xulplanet.com/rdf/recent#label" uri="rdf:*"/> </menupopup> </template> </menulist> </groupbox> </tabpanel> <tabpanel id="optionspanel" orient="vertical"> <checkbox id="casecheck...
Modifying the Default Skin - Archive of obsolete content
« previousnext » as of firefox 69, you must set the toolkit.legacyuserprofilecustomizations.stylesheets preference to
true in about:config in order to load userchrome.css or usercontent.css files.
... you can assign images to a button, checkbox and other elements by using the list-style-image property as in the following: checkbox { list-style-image: url("chrome://findfile/skin/images/check-off.jpg"); } checkbox[checked="
true"] { list-style-image: url("chrome://findfile/skin/images/check-on.jpg"); } this code changes the image associated with a checkbox.
...the modifier 'checked=
true' makes the style only apply to elements which have their checked attributes set to
true.
More Menu Features - Archive of obsolete content
ch..." accesskey="o"/> <menuitem label="save search..." accesskey="s"/> <menuseparator/> <menuitem label="close" accesskey="c"/> </menupopup> </menu> <menu id="edit-menu" label="edit" accesskey="e"> <menupopup id="edit-popup"> <menuitem label="cut" accesskey="t"/> <menuitem label="copy" accesskey="c"/> <menuitem label="paste" accesskey="p" disabled="
true"/> </menupopup> </menu> </menubar> <toolbar id="findfiles-toolbar> here we have added two menus with various commands on them.
...example 2 : source view <toolbox> <menubar id="options-menubar"> <menu id="options_menu" label="options"> <menupopup> <menuitem id="backups" label="make backups" type="checkbox"/> <menuitem id="email" label="email administrator" type="checkbox" checked="
true"/> </menupopup> </menu> </menubar> </toolbox> the type attribute has been added which is used to make the menu item checkable.
...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 example, you'll find that of the first three menu items, only ...
Tree Selection - Archive of obsolete content
it takes a row index as an argument and returns
true if that row is selected.
...tree.view.selection.rangedselect(2,7,
true); the last argument indicates whether to add to the current selection or not.
... if
true, the range will be added to the existing selection.
Updating Commands - Archive of obsolete content
a simple command updater looks like this: <commandset id="updatepasteitem" commandupdater="
true" events="focus" oncommandupdate="goupdatecommand('cmd_paste');"/> a command updater is indicated by using the commandupdater attribute, which should be set to
true.
...<commandset id="globaleditmenuitems" commandupdater="
true" events="focus" oncommandupdate="goupdateglobaleditmenuitems()"/> <commandset id="selecteditmenuitems" commandupdater="
true" events="select" oncommandupdate="goupdateselecteditmenuitems()"/> <commandset id="undoeditmenuitems" commandupdater="
true" events="undo" oncommandupdate="goupdateundoeditmenuitem...
...s()"/> <commandset id="clipboardeditmenuitems" commandupdater="
true" events="clipboard" oncommandupdate="goupdatepastemenuitems()"/> next, we'll find out how to use observers.
XPCOM Interfaces - Archive of obsolete content
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.
...if the recursive parameter is
true, a directory and all of its files and subdirectories will also be deleted.
Accessibility/XUL Accessibility Reference - Archive of obsolete content
<menubar hidden="false"> <menu label="file" accesskey="f"> <menupopup> <menuitem label="new" accesskey="n" key="file-new-key"/> </menupopup> </menu> </menubar> menulist <label value="<!--label text-->" control="comboid" /> <menulist id="comboid"> <menupopup> <menuitem label="<!--option1-->" /> <menuitem label="<!--option2-->" selected="
true" /> <menuitem label="<!--option3-->" /> </menupopup> </menulist> menupopup see menulist and menubar popup see popupset popupset be careful regarding keyboard access of popups.
... progressmeter <progressmeter mode="determined" value="10" /> as progress advances, jaws indicates percentage to the user radio see radiogroup radiogroup <label value='<!--radio group-->' control='radioid' /> <radiogroup id='radioid'> <radio selected="
true" label='<!--option1-->' /> <radio label='<!--option2-->' /> </radiogroup> row see grid rows see grid stack all elements can be focused, even if not visible due to being hidden under something else statusbar <statusbar> <statusbarpanel label="<!--status bar-->" flex="1"/> </statusbar> read using jaws with inse...
... tabpanel see tabbox tabpanels see tabbox tabs see tabbox textbox <label control="inputid"> <!--first name:--> </label> <textbox id='inputid'> tree <tree hidecolumnpicker="
true" > <treecols> <treecol label="cats" primary="
true"/> </treecols> <treechildren> <treeitem container="
true" open="
true"> <treerow> <treecell label="<!--male-->" /> </treerow> <treechildren> <treeitem> <treerow> <treecell label="<!--aramis-->" /> </treerow> </treeitem> <treeitem> <treerow> ...
arrowscrollbox - Archive of obsolete content
hidden, id, insertafter, 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 clicktoscroll type: boolean clicktoscroll, if
true, the arrows must be clicked to scroll the scrollbox content.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... smoothscroll type: boolean
true initially enables smooth scrolling for the corresponding arrowscrollbox, false disables it.
colorpicker - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... open type: boolean returns
true if the popup for a button-type colorpicker is open.
... set this property to
true to open the popup or false to close the popup.
datepicker - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... readonly type: boolean if set to
true, then the user cannot change the value of the element.
... readonly type: boolean if set to
true, then the user cannot modify the value of the element.
menupopup - Archive of obsolete content
<menupopup id="clipmenu"> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> <label value="right click for popup" context="clipmenu"/> attributes ignorekeys type: boolean if
true, keyboard navigation between items in the popup is disabled.
... iscontextmenu the iscontextmenu argument should be
true for context menus and false for all other types of popups.
... attributesoverride if the attributesoverride argument is
true, the position attribute on the popup node overrides the position value argument.
menuseparator - Archive of obsolete content
allowevents type: boolean if
true, events are passed to children of the element.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... selected type: boolean this property's value is
true if this element is selected, or false if it is not.
notificationbox - Archive of obsolete content
if the return value from this function is not
true, then the notification is closed.
... isdefault - if
true, this is the default button.
...if immediate is
true, the messages are removed immediately.
treeitem - Archive of obsolete content
attributes container, empty, label, open, uri examples (example needed) attributes container type: boolean set to
true if the element is to act as a container which can have child elements.
... empty type: boolean set to
true if the element is a container that contains no children.
... open type: boolean for the menu type buttons, the open attribute is set to
true when the menu is open.
Getting started with XULRunner - Archive of obsolete content
the xulrunner download for windows is a zip file, not a
true install.
...*/ pref("browser.dom.window.dump.enabled",
true); pref("javascript.options.showinconsole",
true); pref("javascript.options.strict",
true); pref("nglayout.debug.disable_xul_cache",
true); pref("nglayout.debug.disable_xul_fastload",
true); xulrunner specific preferences include: toolkit.defaultchromeuri specifies the default window to open when the application is launched.
...e://global/skin/" type="text/css"?> <window id="main" title="my app" width="300" height="300" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myapp/content/main.js"/> <caption label="hello world"/> <separator/> <button label="more >>" oncommand="showmore();"/> <separator/> <description id="more-text" hidden="
true">this is a simple xulrunner application.
XULRunner tips - Archive of obsolete content
("xpinstall.dialog.progress.skin", "chrome://mozapps/content/extensions/extensions.xul?type=themes"); pref("xpinstall.dialog.progress.chrome", "chrome://mozapps/content/extensions/extensions.xul?type=extensions"); pref("xpinstall.dialog.progress.type.skin", "extension:manager-themes"); pref("xpinstall.dialog.progress.type.chrome", "extension:manager-extensions"); pref("extensions.update.enabled",
true); pref("extensions.update.interval", 86400); pref("extensions.dss.enabled", false); pref("extensions.dss.switchpending", false); pref("extensions.ignoremtimechanges", false); pref("extensions.logging.enabled", false); pref("general.skins.selectedskin", "classic/1.0"); // nb these point at amo pref("extensions.update.url", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensio...
... preferences needed for file download dialogs to use the unknown-content-type and file-downloads dialogs from a <browser> element, you need to add the following prefs: pref("browser.download.usedownloaddir",
true); pref("browser.download.folderlist", 0); pref("browser.download.manager.showalertoncomplete",
true); pref("browser.download.manager.showalertinterval", 2000); pref("browser.download.manager.retention", 2); pref("browser.download.manager.showwhenstarting",
true); pref("browser.download.manager.usewindow",
true); pref("browser.download.manager.closewhendone",
true); pref("browser.download.manager.
... pref("signon.remembersignons",
true); pref("signon.expiremasterpassword", false); pref("signon.signonfilename", "signons.txt"); you also need to get an instance of the login manager service, which internally initializes the system: components.classes["@mozilla.org/login-manager;1"].getservice(components.interfaces.nsiloginmanager); using firefox to run xulrunner applications firefox 3 and up contain the xulrunner runtime.
calICalendarView - Archive of obsolete content
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.
...(for instance, calendar-month-view will show all dates from the start of the week of astartdate to the end of the week of aenddate.) setdatelist void setdatelist(in unsigned long acount, [array,size_is(acount)] in calidatetime adates); this function can only be called if supportsdisjointdates is
true and will throw an error if it is not.
NPEvent - Archive of obsolete content
values: 0 nullevent 1 mousedown 2 mouseup 3 keydown 4 keyup 5 autokey 6 updateevt 7 diskevt 8 activateevt 15 osevt 23 khighlevelevent getfocusevent 0, 1 (
true, false) losefocusevent adjustcursorevent 0, 1 (
true, false) for information about these events, see the mac os developer documentation.
... 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 wants to set the cursor when the mouse is within the instance, set the cursor and return
true.
NPN_SetValue - Archive of obsolete content
variable values the function can set: nppvpluginwindowbool: sets windowed/windowless mode for plugin display;
true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin;
true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvpluginscriptableinstance nppvpluginscriptableiid nppvjavascriptpushcallerbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells...
...to specify a transparent mode, the value parameter should be set to
true.
...the plugin calls npn_setvalue any time with nppvpluginkeeplibraryinmemory as variable parameter and value set to
true.
Common Firefox theme issues and solutions - Archive of obsolete content
@media all and (-moz-windows-compositor) { /* make transition to fullscreen mode seamlessly in firefox 10+ */ #main-window[infullscreen="
true"] { -moz-appearance: none; background-color: -moz-dialog!important; } } for more information about this issue please see bug 732757 and bug 732757 and this mozillazine thread.
...tity-box-inner > #page-proxy-stack > #page-proxy-favicon { list-style-image: url(chrome://browser/skin/identity-icons-https-ev.png); } #identity-box:hover > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon { -moz-image-region: rect(0, 32px, 16px, 16px); } #identity-box:hover:active > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon, #identity-box[open=
true] > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon { -moz-image-region: rect(0, 48px, 16px, 32px); } #page-proxy-favicon[pageproxystate="invalid"] { opacity: 0.5; } for more information about identity boxes please see the identity box section of the amo editors theme review guidelines no visual clue for disabled url bars there needs to be a visual clue when url ba...
...change the style rules: .playbutton[paused] {...} .mutebutton[muted] {...} to: .playbutton[paused="
true"] {...} .mutebutton[muted="
true"] {...} error console warnings unknown namespace for videocontrols.css the error console is reporting the following issue: warning: unknown namespace prefix 'html'.
Browser Detection and Cross Browser Support - Archive of obsolete content
this is not
true today and will become even less
true as more browsers which support the w3c dom standards are introduced in the future.
...although you can use object detection as just another means of distinguishing between vendor/version the technique shows it's
true power when used to detect features rather than browsers.
...) { var val = parseint(rvparts[i]); rvvalue += val / exp; exp *= 100; } return rvvalue; } // determine if the browser is any gecko // branch >= 1.0.1 or netscape 6.2.x/compuserve 7 // built after august 1, 2002 var rv = geckogetrv(); var found = false; if (rv >= 0) { // gecko browser if (navigator.productsub > '20020801') { if (rv >= 1.0001) { found =
true; } else if (rv >= 0.0904 && rv < 0.0905) { if (navigator.vendor == 'netscape6' || navigator.vendor == 'cs 2000 7.0') { found =
true; } } } } example 4 - the international herald-tribune this site illustrates many of the techniques described in this article.
XForms Custom Controls Examples - Archive of obsolete content
g 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="_domparse...
...r">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> ...
Audio for Web games - Game development
to see this in action, let's lay out some separate tracks: <section id="tracks"> <ul> <li data-loading="
true"> <a href="leadguitar.mp3" class="track">lead guitar</a> <p class="loading-text">loading...</p> <button data-playing="false" aria-decribedby="guitar-play-label"> <span id="guitar-play-label">play</span> </button> </li> <li data-loading="
true"> <a href="bassguitar.mp3" class="track">bass guitar</a> <p class="loading-text">loading...</p> <bu...
...tton data-playing="false" aria-describedby="bass-play-label"> <span id="bass-play-label">play</span> </button> </li> <li data-loading="
true"> <a href="drums.mp3" class="track">drums</a> <p class="loading-text">loading...</p> <button data-playing="false" aria-describedby="drums-play-label"> <span id="drums-play-label">play</span> </button> </li> <li data-loading="
true"> <a href="horns.mp3" class="track">horns</a> <p class="loading-text">loading...</p> <button data-playing="false" aria-describedby="horns-play-label"> <span id="horns-play-label">play</span> </button> </li> <li data-loading="
true"> <a href="clav.mp3" class="track">clavi</a> <p class="loading-text">loading...</p> ...
...ng text loadtext.style.display = 'none'; // show button playbutton.style.display = 'inline-block'; // allow play on click playbutton.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } playtrack(track); playbutton.dataset.playing =
true; }) }) }) note: you can see this demo in action here and view the source code here.
Desktop mouse and keyboard controls - Game development
there are no helpers so you have to remember what the given codes are (or look them up); 37 is the left arrow: function keydownhandler(event) { if(event.keycode == 39) { rightpressed =
true; } else if(event.keycode == 37) { leftpressed =
true; } if(event.keycode == 40) { downpressed =
true; } else if(event.keycode == 38) { uppressed =
true; } } the keyuphandler looks almost exactly the same as the keydownhandler above, but instead of setting the pressed variables to
true, we would set them to false.
... if the left arrow is pressed (⬅︎; key code 37), we can set the leftpressed variable to
true and in the draw function perform the action assigned to it — move the ship left: function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); if(rightpressed) { playerx += 5; } else if(leftpressed) { playerx -= 5; } if(downpressed) { playery += 5; } else if(uppressed) { playery -= 5; } ctx.drawimage(img, playerx, playery); requestanimationframe(draw); } the draw function first clears the whole canvas — we draw everything from scratch on every single frame.
... we could write our own keycode object containing the key codes, for example: var keyboardhelper = { left: 37, up: 38, right: 39, down: 40 }; that way instead of using the codes to compare the input in the handler functions we could do something like this, which is arguably easier to remember: if(event.keycode == keyboardhelper.left) { leftpressed =
true; } note: you can also find a list if the different keycodes and what keys they relate to in the keycode reference page.
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
r code next: function setendgame() { cancelanimationframe(raf); spinnercontainer.style.display = 'none'; result.style.display = 'block'; result.textcontent = 'players go!!'; document.addeventlistener('keydown', keyhandler); function keyhandler(e) { let isover = false; console.log(e.key); if (e.key === "a") { result.textcontent = 'player 1 won!!'; isover =
true; } else if (e.key === "l") { result.textcontent = 'player 2 won!!'; isover =
true; } if (isover) { document.removeeventlistener('keydown', keyhandler); settimeout(reset, 5000); } }; } stepping through this: first, cancel the spinner animation with cancelanimationframe() (it is always good to clean up unneeded processes), and hide the spinner co...
...(note: this will only work with lowercase a and l — if an uppercase a or l is submitted (the key plus shift), it is counted as a different key!) if one of these keys was pressed, set isover to
true.
... only if isover is
true, remove the keydown event listener using removeeventlistener() so that once the winning press has happened, no more keyboard input is possible to mess up the final game result.
Test your skills: Conditionals - Learn web development
conditionals 2 for this task you are given three variables: machineactive — contains an indicator of whether the answer machine is switched on or not (
true/false) score — contains your score in an imaginary game.
...after you've entered your code, try changing machineactive to
true, to see if it works.
... conditionals 4 for the final task you are given four variables: machineactive — contains an indicator of whether the login machine is switched on or not (
true/false).
Adding features to our bouncing balls demo - Learn web development
this should be a boolean (
true/false).
...) constructor call — the exists parameter should be the 5th parameter, and should be given a value of
true.
... 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.
Dynamic behavior in Svelte: working with variables and props - Learn web development
create a <script> section at the top of src/components/todos.svelte and give it some content, as follows: <script> let todos = [ { id: 1, name: 'create a svelte starter app', completed:
true }, { id: 2, name: 'create your first component', completed:
true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] let totaltodos = todos.length let completedtodos = todos.filter(todo => todo.completed).length </script> now let's do something with that information.
...update src/app.svelte as follows: <script> import todos from './components/todos.svelte' let todos = [ { id: 1, name: 'create a svelte starter app', completed:
true }, { id: 2, name: 'create your first component', completed:
true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] </script> <todos todos={todos} /> when the attribute and the variable have the same name, svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this.
... the same is not
true for totaltodos and completedtodos, however.
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.
...t> 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 to the <li> element in your app.vue template, like so: <ul> <li v-for="item in todoitems" :key="item.id"> <to-do-item label="my todo item" :done="
true"></to-do-item> <...
... 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.
Implementing feature detection - Learn web development
it does this by making the global modernizr object available to the page it is applied to, which contains results of the feature detects as
true/false properties.
...for example: modernizr.flexbox modernizr.websqldatabase modernizr.xhr2 modernizr.fetch the console will return
true/false values to indicate whether your browser supports those features or not.
...y (just before the </body> tag), and put the following script inside the tags: if (modernizr.geolocation) { navigator.geolocation.getcurrentposition(function(position) { let latlng = new google.maps.latlng(position.coords.latitude,position.coords.longitude); let myoptions = { zoom: 8, center: latlng, maptypeid: google.maps.maptypeid.terrain, disabledefaultui:
true } let map = new google.maps.map(document.getelementbyid("map_canvas"), myoptions); }); } else { const para = document.createelement('p'); para.textcontent = 'argh, no geolocation!'; document.body.appendchild(para); } try your example out!
Setting up your own test automation environment - Learn web development
ed from automation dashboard or profile section const key = '{accesskey}'; // gridurl: gridurl can be found at automation dashboard const grid_host = 'hub.lambdatest.com/wd/hub'; function searchtextongoogle() { // setup input capabilities const capabilities = { platform: 'windows 10', browsername: 'chrome', version: '67.0', resolution: '1280x800', network:
true, visual:
true, console:
true, video:
true, name: 'test 1', // name of the test build: 'nodejs build' // name of the build }; // url: https://{username}:{accesstoken}@hub.lambdatest.com/wd/hub const gridurl = 'https://' + username + ':' + key + '@' + grid_host; // setup and build selenium driver object const driver = new webdriver.builder() .usi...
...onst webdriver = require('selenium-webdriver'), by = webdriver.by, until = webdriver.until; // input capabilities let capabilities = { 'browsername' : 'firefox', 'browser_version' : '56.0 beta', 'os' : 'os x', 'os_version' : 'sierra', 'resolution' : '1280x1024', 'browserstack.user' : 'your-user-name', 'browserstack.key' : 'your-access-key', 'browserstack.debug' : '
true', 'build' : 'first build' }; let driver = new webdriver.builder().
...block near the bottom of the code with the following: driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { console.log('test passed'); let testpassed =
true; } else { console.log('test failed'); let testpassed = false; } saucelabs.updatejob(driver.sessionid, { name: 'google search results page title test', passed: testpassed }); }); }); here we've set a testpassed variable to
true or false depending on whether the test passed or fails, then we've used the saucelabs.updatejob() method to update the detail...
Introducing a complete toolchain - Learn web development
to configure prettier, give .prettierrc.json the following contents: { "singlequote":
true, "trailingcomma": "es5" } with these settings, when prettier formats javascript for you it will use single quotes for all your quoted values, and it won't use trailing commas (a newer feature of ecmascript that will cause errors in older browsers).
... next up, we’ll configure eslint — create another file in the root of your will-it-miss directory called .eslintrc.json, and give it the following contents: { "env": { "es6":
true, "browser":
true }, "extends": "eslint:recommended", "parseroptions": { "ecmaversion": 6, "sourcetype": "module" }, "rules": { "no-console": 0 } } the above eslint configuration says that we want to use the "recommended" eslint settings, that we're going to allow usage of es6 features (such as map() or set()), that we can use module import statements, and that using console.log() is allowed.
... the final config file should look like this — add in the bolded parts and save it: { "env": { "es6":
true, "browser":
true }, "extends": ["eslint:recommended", "plugin:react/recommended"], "parseroptions": { "ecmaversion": 6, "sourcetype": "module", "ecmafeatures": { "jsx":
true } }, "plugins": ["react"], "rules": { "semi": "error", "no-console": 0, "react/jsx-uses-vars": "error" } } as the configuration now uses a plugin called "react", this dev...
Cookies Preferences in Mozilla
network.cookie.alwaysacceptsessioncookies default value: false only used if network.cookie.lifetimepolicy is set to 1
true = accepts session cookies without prompting false = prompts for session cookies network.cookie.thirdparty.sessiononly default value: false
true = restrict third party cookies to the session only false = no restrictions on third party cookies network.cookie.maxnumber default value: 1000 configures the maximum amount of cookies to be stored valid range is from 0-65535, rfc 2109 and 2965 re...
...quire this to be at least 300 network.cookie.maxperhost default value: 50 configures the maximum amount of cookies to be stored per host valid range is from 0-65535, rfc 2109 and 2965 require this to be at least 20 network.cookie.disablecookieformailnews default value:
true true = do not accept any cookies from within mailnews or from mail-style uris false = allow cookies in these situations this preference is applicable to all versions of seamonkey.
...(the old prefs are network.cookie.lifetime.enabled, network.cookie.lifetime.behavior, and network.cookie.warnaboutcookies.)
true = prefs have been migrated false = migrate prefs on next startup original document information author(s): mike connor last updated date: may 22, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details.
Performance
performance best practices declaring stateless functions once per process bad: // addon.js services.mm.loadframescript("framescript.js",
true) // framescript.js const precomputedconstants = // ...
... better: content-document-global-created notifications can be substituted with domwindowcreated events other observers and services should be registered in a process script or jsm instead load frame scripts on demand bad: // addon.js services.mm.loadframescript("framescript.js", /*delayed:*/
true) // stuff communicating with the framescript // framescript.js function onlyonceinabluemoon() { // we only need this during a total solar eclipse while goat blood rains from the sky sendasyncmessage('my-addon:paragraph-count', {num: content.document.queryselectorall('p').length}) } addmessagelistener("my-addon:request-from-parent", onlyonceinabluemoon) better: // addon.js function ont...
... 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.
mozbrowsersecuritychange
extendedvalidation a boolean indicating if the current ssl certificate is an extended validation certificate (
true) or not (false).
... trackingcontent a boolean indicating if tracking content is present on the current page (
true) or not (false).
... mixedcontent a boolean indicating if mixed content is present on the current page (
true) or not (false).
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.
...ory manager to register properties of the global object in javascript like this: nscomptr<nsicategorymanager> catman = do_getservice(ns_categorymanager_contractid); if (!catman) return ns_error_failure; nsxpidlcstring previous; catman->addcategoryentry(javascript_global_property_category, "my_prop_name", "my_prop_contract_id", pr_
true, pr_
true, getter_copies(previous)); this will cause a component with the contract id my_prop_contract_id to be lazily created when the my_prop_name is resolved in any javascript window scope.
... if you want to create your component multiple times within the browser window, you can use a javascript constructor instead of a javascript property: catman->addcategoryentry("javascript global constructor", "my_prop_name", "my_prop_contract_id", pr_
true, pr_
true, getter_copies(previous)); that way you will be able to do: var my_comp = new my_prop_name(); this was taken from weirdal's excellent "burning chrome" article.
Assert.jsm
this statement is equivalent to assert.equal(
true, !!guard, message_opt);.
... to test strictly for the value
true, use assert.strictequal(
true, guard, message_opt);.
...xplanation of the expected result operator operation qualifier used by the assertion method (ex: '==') examples custom reporter example components.utils.import("resource://testing-common/assert.jsm"); let assert = new assert(); assert.setreporter(function customreporter(err, message, stack) { if (err) { do_report_result(false, err.message, err.stack); } else { do_report_result(
true, message, stack); } }); ...
API-provided widgets
tooltiptext string to use for the tooltip of the widget label string to use for the label of the widget removable whether the widget is removable (optional, default:
true).
... overflows whether widget can overflow when in an overflowable toolbar (optional, default:
true) defaultarea default area to add the widget to (optional, default: none; required if non-removable) shortcutid id of an element that has a shortcut for this widget (optional, default: null).
... showinprivatebrowsing whether to show the widget in private browsing mode (optional, default:
true) event handlers you can also define several event handlers which will be called at various stages in a widget's lifetime: event handler name description onbuild(adoc) only useful for custom widgets (and required there); a function that will be invoked with the document in which to build a widget.
FileUtils.jsm
followlinks optional
true if links should be followed, false otherwise.
... shouldcreate optional
true if the directory hierarchy specified in patharray should be created if it does not exist, false otherwise.
... followlinks optional
true if links should be followed, false otherwise location specified.
OS.File.Error
becauseexists
true if the operation failed because a file or directory exists, false otherwise.
... becausenosuchfile
true if the operation failed because a file or directory does not exist, false otherwise.
... becauseclosed
true if the operation failed because a file or directory is closed, false otherwise.
OS.File.Info
instances of os.file.info cross-platform attributes isdir
true if the file is a directory, false otherwise.
... issymlink
true if the false is a symbolic link, false otherwise.
... (as of firefox 38 this is always
true on all systems, this is a bug: bugzilla 1145885) (on windows this returns false for hard links) size the number of bytes in the file.
WebRequest.jsm
to perform one of these operations, include a property with the appropriate name in the object returned from the listener, and assign it the desired value, as detailed in the table below: operation available in return property cancel onbeforerequest cancel boolean value set to
true.
...ce://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern("http://example.org/*"); webrequest.onbeforerequest.addlistener(cancelrequest, {urls: pattern}, ["blocking"]); function cancelrequest(e) { console.log("canceling: " + e.url); return {cancel:
true}; } this code cancels requests for images that are made to urls under "https://mdn.mozillademos.org/": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern("https://mdn.mozillademos.org/*"); webrequest.onbeforerequest.addlistener(cancelimages, { ...
... urls: pattern, types: ["image"] }, ["blocking"]); function cancelimages(e) { console.log("canceling: " + e.url); return {cancel:
true}; } redirecting this code replaces, by redirection, all network requests for images that are made to urls under "https://mdn.mozillademos.org/": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern("https://mdn.mozillademos.org/*"); webrequest.onbeforesendheaders.addlistener(redirect, { urls: pattern, ...
XPCOMUtils.jsm
'
true' is passed for // both apersist and areplace params.
...when set to
true, and only if 'value' // is not specified, the concatenation of the string "service," and the // object's contractid is passed as avalue parameter of addcategoryentry.
... service:
true, // optional array of applications' ids in the form: // [ "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}", ...
Profiling with the Firefox Profiler
set devtools.debugger.remote-enabled to
true in about:config for fennec.
... viewing the layer tree to view the layer tree, the layers.dump pref must be set to
true in the firefox or b2g program being profiled.
...this can be achieved by additionally setting the layers.dump-texture pref to
true, or by adding -f layersdump to the profiler command line (the latter implies both the layers.dump and layers.dump-texture prefs).
A brief guide to Mozilla preferences
for example, let's assume that nightly has a preference "some.preference" which defaults to
true while developeredition defaults the same preference to false and the user desires the preference to have the value
true in both channels.
... if the preference is not a sticky preference and the user runs developeredition and flips the pref to
true it will be saved as it is not the default.
...if the preference is defined as a sticky preference, the value
true will be written by nightly even though it matches the current default, so when developeredition is run the preference keeps the desired value of
true.
javascript.options.showInConsole
type:boolean default value: false (
true in debug builds) exists by default: yes application support:firefox 1.0 status: active introduction:2002-02-26 bugs: bug 125181 bug 337875 values false only errors and warnings from content code are shown.
...
true (default) errors and warnings from both chrome and content are shown in the error console.
... note: since the web console was introduced in firefox 4 specifically for debugging content, the default value for this preference has changed to
true as of gecko 2.0.
nglayout.debug.disable xul fastload
never set nglayout.debug.disable_xul_fastload to
true in a production environment; it exists solely to aid in debugging.
... type:boolean default value: false (
true in debug builds) exists by default: yes application support:?
...
true xul fastload is disabled.
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.
... if polarity is set to pr_
true and linger is set to 0 (pr_interval_no_wait), the runtime aborts the connection when it is closed and discards any data remaining in the socket send buffer.
... if polarity is set to pr_
true and linger is nonzero, the runtime lingers when the socket is closed.
NSS Sample Code Utilities_1
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 ?
...ng == '\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++] = *instring++; } outbuf->data[
truelen] = '\0';
truelen =
truelen-1; } outbuf->len =
truelen; return 0; } /* * filetoitem */ secstatus file...
...; tcsetattr(fd, tcsaflush, &tio); } } /* * checkpassword */ prbool checkpassword(char *cp) { int len; char *end; len = port_strlen(cp); if (len < 8) { return pr_false; } end = cp + len; while (cp < end) { unsigned char ch = *cp++; if (!((ch >= 'a') && (ch <= 'z')) && !((ch >= 'a') && (ch <= 'z'))) { return pr_
true; } } return pr_false; } /* * getpassword */ char* getpassword(file *input, file *output, char *prompt, prbool (*ok)(char *)) { char phrase[200] = {'\0'}; int infd = fileno(input); int istty = isatty(infd); for (;;) { /* prompt for password */ if (istty) { fprintf(output, "%s", prompt); fflus...
NSS Sample Code sample3
ut << "digestbegin failed" << endl; goto done; } s = pk11_digestop(context, data, sizeof data); if (s != secsuccess) { cout << "digestupdate failed" << endl; goto done; } s = pk11_digestfinal(context, digest, &len, sizeof digest); if (s != secsuccess) { cout << "digestfinal failed" << endl; goto done; } /* print digest */ printdigest(digest, len); pk11_destroycontext(context, pr_
true); context = 0; /* * part 2 - hashing with included secret key */ cout << "part 2 -- hashing with included secret key" << endl; /* initialize data */ memset(data, 0xbc, sizeof data); /* create a key */ key = pk11_keygen(slot, ckm_generic_secret_key_gen, 0, 128, 0); if (!key) { cout << "create key failed" << endl; goto done; } cout << (void *)key << endl; /* create p...
...cout << "digestkey failed" << endl; goto done; } s = pk11_digestop(context, data, sizeof data); if (s != secsuccess) { cout << "digestupdate failed" << endl; goto done; } s = pk11_digestfinal(context, digest, &len, sizeof digest); if (s != secsuccess) { cout << "digestfinal failed" << endl; goto done; } /* print digest */ printdigest(digest, len); pk11_destroycontext(context, pr_
true); context = 0; /* * part 3 - mac (with secret key) */ cout << "part 3 -- mac (with secret key)" << endl; /* initialize data */ memset(data, 0xbc, sizeof data); context = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, key, &noparams); if (!context) { cout << "createcontextbysymkey failed" << endl; goto done; } s = pk11_digestbegin(context); if (s != secsuccess) { c...
...out << "digestbegin failed" << endl; goto done; } s = pk11_digestop(context, data, sizeof data); if (s != secsuccess) { cout << "digestop failed" << endl; goto done; } s = pk11_digestfinal(context, digest, &len, sizeof digest); if (s != secsuccess) { cout << "digestfinal failed" << endl; goto done; } /* print digest */ printdigest(digest, len); pk11_destroycontext(context, pr_
true); context = 0; done: if (context) pk11_destroycontext(context, pr_
true); /* freeit ??
Utilities for nss samples
-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 ?
...ng == '\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++] = *instring++; } outbuf->data[
truelen] = '\0';
truelen =
truelen-1; } outbuf->len =
truelen; return 0; } /* * filetoitem */ secstatus file...
...; tcsetattr(fd, tcsaflush, &tio); } } /* * checkpassword */ prbool checkpassword(char *cp) { int len; char *end; len = port_strlen(cp); if (len < 8) { return pr_false; } end = cp + len; while (cp < end) { unsigned char ch = *cp++; if (!((ch >= 'a') && (ch <= 'z')) && !((ch >= 'a') && (ch <= 'z'))) { return pr_
true; } } return pr_false; } /* * getpassword */ char* getpassword(file *input, file *output, char *prompt, prbool (*ok)(char *)) { char phrase[200] = {'\0'}; int infd = fileno(input); int istty = isatty(infd); for (;;) { /* prompt for password */ if (istty) { fprintf(output, "%s", prompt); fflus...
nss tech note3
if the extension is present and has the value
true, then this cert is taken to be a ca cert.
... that extension contains a sequence of oids, each of which signifies one or more cert types, depending on the presence or absence of of the
true basic constraints extension; that is, the interpretation of the extended key usage extension is controlled by whether the cert is a ca cert, or not.
...gn object_signing object_signing_ca sec_oid_ext_key_usage_time_stamp time_stamp time_stamp sec_oid_ocsp_responder ocsp_responder ocsp_responder sec_oid_ns_key_usage_govt_approved govt_approved govt_approved if the extended key usage extension is absent, the cert is assumed to have the cert types ssl_client, ssl_server and email, and if the cert is a ca cert (as indicated by the presence of a
true basic constraints extension), the cert is also assumed to have the cert types ssl_ca, email_ca and status_responder.
PKCS11 FAQ
nss may enumerate all the permanment certificates in a token (cka_token set to
true).
...this is also
true for ckm_dsa and ckm_dsa_gen_keypair.
... the above statement is
true for read-write tokens only.
NSS Tools modutil
-fips [
true | false] enable (
true) or disable (false) fips 140-2 compliance for the netscape communicator internal module.
...urity mechanisms in an existing pkcs #11 module: -undefault modulename -mechanisms mechanism-list enabling a specific slot or all slots within a module: -enable modulename [-slot slotname] disabling a specific slot or all slots within a module: -disable modulename [-slot slotname] enabling or disabling fips 140-2 compliance within the netscape communicator internal module: -fips [
true | false] disabling interactive prompts for the security module database tool, to support scripted operation: -force jar installation file when a jar file is run by a server, by the security module database tool, or by any program that does not interpret javascript, a special information file must be included in the format described below.
... enabling fips compliance this example enables fips 140-2 compliance in communicator's internal module: modutil -dbdir "c:\databases" -fips
true the security module database tool displays a warning: warning: performing this operation while the browser is running could causecorruption of your security databases.
Rhino overview
it is
true (and thus ecma conformant) for version 1.3 and greater.
... second, the value of the property security.requiresecuritydomain should be changed to
true in the resource bundle org.mozilla.javascript.resources.security.
...setting this property to
true requires that any calls that compile or evaluate javascript must supply a security domain object of any object type that will be used to identify javascript code.
JS_ExecuteRegExp
test bool pass
true to avoid creating match result array and store boolean value to rval.
...if test is
true, js_executeregexp and js_newregexpobjectnostatics store the boolean value
true to *rval if matches, otherwise stores null to *rval.
... 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_GetPropertyAttributes
if no error occurs, *foundp receives js_
true if the specified property is found and js_false if it is not found.
...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_HasElement
on success, it stores
true to *foundp, false otherwise.
... if the element exists, js_haselement sets *foundp to
true.
... if not, it sets *foundp to false and returns
true (to indicate no error occurred).
JS_HasOwnProperty
on success, js_hasownproperty stores
true in this variable if obj has an own property with the given name, and false if not.
... 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).
JS_HasProperty
on success, js_hasproperty stores
true in this variable if obj has a property with the given name, and false if not.
...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).
JS_ResolveStandardClass
if the id is resolved,
true is stored into *resolved if success.
... description js_resolvestandardclass resolves id, which must contain either a string or an int, to a standard class name in obj if possible, defining the class's constructor and/or prototype and storing
true in *resolved.
... if id does not name a standard class or a top-level property induced by initializing a standard class, store false in *resolved and just return
true.
JS_SetPropertyAttributes
then, if the property exists, but is associated with a different object, js_setpropertyattributes returns js_
true.
... otherwise, it sets foundp to js_
true, and attempts to set the attributes as specified.
... if the attributes can be set, js_setpropertyattributes returns js_
true.
JS_ValueToNumber
if v is undefined, null, false, or
true, conversion succeeds, and the result is nan, 0, 0, or 1 respectively.
...js_valuetonumber always succeeds in this case, returning js_
true.
... on success, js_valuetonumber stores the converted value in *dp and returns js_
true.
SpiderMonkey 1.8.5
so that jsval_is_int was
true.
... while this was never specified behaviour, it is no longer
true; numeric values which are integers are frequently encoded as jsdouble inside the jsval.
...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 1.8.7
so that jsval_is_int was
true.
... while this was never specified behaviour, it is no longer
true; numeric values which are integers are frequently encoded as jsdouble inside the jsval.
...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).
TPS Bookmark Lists
loadinsidebar:
true or false.
... folder, where this folder should be moved to (i.e., this folder would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below this folder) example: { folder: "folderb", changes: { location: "menu/foldera", folder: "folder b", description: "folder description" } } separator objects valid properties are: separator:
true, always set for separators before: the title of the bookmark item expected to be found before this separator; used only in verify and modify actions.
... this object are: location: the full path of the folder that this separator should be moved to position: the title of the existing bookmark item, in the current folder, where this separator should be moved to (i.e., this separator would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below this separator) example: { separator:
true } bookmark lists and phase actions following are the functions you can use in phase actions related to bookmarks: bookmarks.add - the bookmark items in the list are added to the end of their parent folder in the specified order.
How to build an XPCOM component in JavaScript
'
true' is passed for both // apersist and areplace params.
...when set to
true, and only if 'value' is not // specified, the concatenation of the string "service," and the object's contractid // is passed as avalue parameter of addcategoryentry.
... service:
true }], // queryinterface implementation, e.g.
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.
... const cc = components.classes; const ci = components.interfaces; const cr = components.results; // global flags polled externally var copyfailed = false; var copyinprogress = false; function copybufferedstream(instream, outstream) { var copyobserver = { onstartrequest: function(request, context) { copyinprogress =
true; }, onstoprequest: function(request, context, statuscode) { copyinprogress = false; // did the copy fail?
... if (!components.issuccesscode(statuscode)) copyfailed =
true; }, queryinterface: function(aiid) { if (aiid.equals(ci.nsirequestobserver) || aiid.equals(ci.nsisupports)) return this; throw cr.ns_error_no_interface; } }; var copier = cc["@mozilla.org/network/async-stream-copier;1"] .createinstance(ci.nsiasyncstreamcopier); copier.init(instream, outstream, null,
true, false, 8192,
true,
true); copier.asynccopy(copyobserver, null); } ...
Components.utils.cloneInto
+ greeting.message); } the add-on script can define an object, clone it, and pass it into this function: // add-on script var addonscriptobject = {"message" : "hello from add-on"}; contentwindow.foo(cloneinto(addonscriptobject, contentwindow)); // "they said: hello from add-on" cloning objects that have functions if the object to be cloned contains functions, you must pass the {clonefunctions:
true} flag or you'll get an error.
...n functions in the object are cloned using the same mechanism as that used in components.utils.exportfunction: // add-on script var addonscriptobject = { greetme: function() { alert("hello from add-on"); } }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {clonefunctions:
true}); // page script var test = document.getelementbyid("test"); test.addeventlistener("click", function() { window.addonscriptobject.greetme(); }, false); cloning objects that contain dom elements by default, if the object you clone contains objects that are reflected from c++, such as dom elements, the cloning operation will fail with an error.
... if you pass the {wrapreflectors:
true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonscriptobject = { body: contentwindow.document.body }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {wrapreflectors:
true}); // page script var test = document.getelementbyid("test"); test.addeventlistener("click", function() { console.log(window.addonscriptobject.body.innerhtml); }, false); access to these objects in the target scope is subject to the normal security checks.
NS_ConvertASCIItoUTF16
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
NS_ConvertUTF16toUTF8
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
NS_ConvertUTF8toUTF16
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
NS_LossyConvertUTF16toASCII
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsAdoptingCString
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsAdoptingString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsAutoString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsCAutoString
result pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsCString
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsDependentCString
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsDependentString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsFixedCString
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsFixedString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsPromiseFlatCString
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsPromiseFlatString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsXPIDLCString
ters nscstring& aresult pruint32 acount right pruint32 right(nscstring&, pruint32) const - source parameters nscstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
nsXPIDLString
ameters nsstring& aresult pruint32 acount right pruint32 right(nsstring&, pruint32) const - source parameters nsstring& aresult pruint32 acount setcharat prbool setcharat(prunichar, pruint32) - source set a char inside this string at given index @param achar is the char you want to write into this string @param anindex is the ofs where you want to write the given char @return
true if successful parameters prunichar achar pruint32 aindex stripchars void stripchars(const char*) - source these methods are used to remove all occurrences of the characters found in aset from this string.
... @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if
true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string.
... if
true, the string will be truncated.
IAccessibleTable
isselected returns
true if the specified column is selected completely and false otherwise.
...isselected returns
true if the specified row is selected completely and false otherwise.
...isselected returns
true if the specified cell is selected and false otherwise.
amIInstallTrigger
return value
true if the installations were successfully started.
... return value
true if the installation was successfully started.
... return value
true if the installation was successfully started.
inIDOMUtils
return value
true if the node only contains insignificant whitespace.
... return value
true if the property is inherited, otherwise false.
... return value
true if lock exists, false otherwise clearpseudoclasslocks() removes any pseudo-class locks from the element.
mozIAsyncFavicons
if the icon data already exists, we will not try to reload the icon unless aforcereload is
true.
... similarly, if the icon is in the failed favicon cache we will not do anything unless aforcereload is
true, in which case we'll try to reload the favicon.
...setting to
true causes us to reload the favicon even if we have a usable copy.
nsIAbCard
ismaillist boolean maillisturi string if ismaillist is
true then maillisturi will contain the uri of the associated mailing list.
... return value
true if the cards are the same.
... astring generatephoneticname(in boolean alastnamefirst) parameters alastnamefirst set to
true to put the last name before the first.
nsIAccessibleDocument
note: renamed from document in gecko 2.0 iseditable boolean
true if the document is live in an editor.
...if a <div> is contenteditable, then it has its own document, with iseditable ==
true.
... acancreate if
true, this method can create a new accessible.
nsIAppShell
when the number of calls that pass pr_
true is subtracted from the number of calls that pass pr_false is greater than 0, performance is given precedence over preventing event starvation.
... void favorperformancehint( in boolean favorperfoverstarvation, in unsigned long starvationdelay ); parameters favorperfoverstarvation
true to favor event performance over event starvation, false to favor event starvation over event performance.
...alisten pr_
true for a new queue wanting hooking up.
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.
nsIBrowserHistory
adobatchnotify obsolete since gecko 9.0 if set to
true, the beginupdatebatch and endupdatebatch events are sent; otherwise, no notification of changes to the history is provided.
... if aentiredomain is
true, it will assume ahost is a domain, and remove all pages from the entire domain.
... aentiredomain if set to
true, it will assume ahost is a domain, and remove all pages from the entire domain, including subdomains.
nsICacheSession
oolean nowait); void evictentries(); prbool isstorageenabled(); nsicacheentrydescriptor opencacheentry(in acstring key, in nscacheaccessmode accessrequested, in boolean blockingmode); void doomentry(in acstring key, in nsicachelistener listener); attributes attribute type description doomentriesifexpired prbool expired entries will be doomed or evicted if this attribute is set to
true.
...this attribute defaults to
true.
...blockingmode
true or false value to turn blocking mode for calling the thread to on/off respectively.
nsICharsetResolver
if the charset cannot be resolved, but the implementation of nsicharsetresolver wants to be notified of the final resolved charset when one is available, it can set awantcharset to
true.
...awantcharset gets set to
true if notifyresolvedcharset() should be called with the given aclosure object.
... aclosure a resulting object which should be passed to notifyresolvedcharset() if awantcharset is set to
true.
nsIClipboard
return value returns
true, if data is present and it matches the specified flavor.
... return value returns
true if kselectionclipboard is available.
... return value returns
true if the separate clipboard for find search strings is supported.
nsIContentSecurityPolicy
isinitialized boolean set to
true when the content security policy has been read in and parsed and is ready to enforce.
... reportonlymode boolean when set to
true, content load-blocking and fail-closed are disabled: content security policy will only send reports, and not modify behavior.
... return value
true if the frame's ancestors are all permitted by policy.
nsIDOMXULElement
allowevents boolean
true if the element's allowevents attribute is the string "
true", otherwise false.
... collapsed boolean
true if the element's collapsed attribute is the string "
true", otherwise false.
... hidden boolean
true if the element's hidden attribute is the string "
true", otherwise false.
nsIEventListenerService
haslistenersfor() returns
true if a event target has any listener for the given type.
... usecapture
true if to listen the event in capture phase, otherwise, false.
... usecapture
true if listening the events in capture phase, otherwise, false.
nsIExternalProtocolService
return value
true if we have a handler and false otherwise.
...wuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); if (extps.externalprotocolhandlerexists("tlcxp")) { // handler for http:// urls exists } else { // suppress external-load warning for standard browser schemes pref("network.protocol-handler.external.tlcxp",
true); pref("network.protocol-handler.app.tlcxp, "lzx"); } </pre> getprotocolhandlerinfo() retrieve the handler for the given protocol.
... return value
true if the protocol is exposed, false otherwise.
nsIFocusManager
adeep if
true, then child frames are traversed and the return value may be the element within a child descendant window that is focused.
...boolean elementisfocusable(in nsidomelement aelement, in unsigned long aflags); parameters aelement aflags return value
true if aelement is focusable.
...void windowshown( in nsidomwindow awindow, in prbool aneedsfocus ); parameters awindow aneedsfocus if
true, then focus events are expected to be fired on the window if this window is in the focused window chain.
nsIInputStream
return value
true if stream is non-blocking.
...this exception may only be thrown if isnonblocking() returns
true.
...this exception may only be thrown if isnonblocking() returns
true.
nsILoginInfo
return value
true if the two logins are exactly equal or false if they're not.
... ignorepassword if
true, do not examine the password value when matching.
... return value
true if the two logins are equivilant or false if they're not.
nsILoginManager
return value
true if the form was successfully filled out; otherwise false.
... return value
true if login saving is enabled for the host, otherwise false.
... isenabled if
true, login saving is enabled for the specified host.
nsILoginManagerStorage
difylogin(in nsilogininfo oldlogin, in nsisupports newlogindata); void removealllogins(); void removelogin(in nsilogininfo alogin); void searchlogins(out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); attributes attribute type description uibusy boolean
true when a master password prompt is being shown.
... return value return
true if login saving is enabled for the specified host; otherwise, return false.
...isenabled
true if logins should be enabled for the host, or false if they should be disabled.
nsIMenuBoxObject
openedwithkey boolean
true if the menubar was opened using the keyboard; otherwise false.
... return value
true if the event was handled, false if not.
... openmenu() void openmenu( in boolean openflag ); parameters openflag
true to open the menu or false to close it.
nsIMsgDBHdr
void markread(in boolean read); parameters read if
true, mark as read.
... markflagged() void markflagged(in boolean flagged); parameters flagged if
true, mark as flagged.
... markhasattachments() void markhasattachments(in boolean hasattachments); parameters hasattachments if
true, mark as having attachments.
nsIMsgHeaderParser
if preserveintegrity is set to
true, quote will not be removed in case the name part of the email contains a comma.
... preserveintegrity set to
true, quote will not be removed return value user friendly names exceptions thrown missing exception missing description unquotephraseoraddrwstring() this function removes the quoting if you want to show the names to users.
...if preserveintegrity is set to
true, quote will not be removed in case the name part of the email contains a comma.
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.
...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 */ boolean match(in nsimsgdbhdr msghdr, in autf8string searchvalue, in nsmsgsearchopvalue searchop); ...
nsINavHistoryObserver
when the last visit for a history entry expires, the history entry itself is deleted and the awholeentry parameter is
true.
... if your code only cares about whole entries being deleted instead of individual visits, you can simply act only when awholeentry is
true.
... awholeentry
true if this expiration will result in the entire history entry being deleted from the history store; if false, only the specified visit is being deleted.
nsINavHistoryQuery
if annotationisnot is
true, we test for the non-existance of the specified annotation.
... domainishost boolean this controls the meaning of domain, and whether it is an exact match domainishost =
true, or hierarchical (= false).
... tagsarenot boolean if
true, the results include only items that are not tagged with the specified tags.
nsIPlacesImportExportService
loads the given bookmarks.html file and replaces it with the current bookmarks hierarchy (if aisinitialimport is
true) or appends it (if aisinitialimport is false).
...observers will be passed through their data parameters either "html" if aisinitialimport is false or "html-initial" if aisinitialimport is
true.
...observers will be passed through their data parameters either "html" if aisinitialimport is false or "html-initial" if aisinitialimport is
true.
Component; nsIPrefBranch
see nsiobserver and here is a quick snippet: var myobserver = { observe: function(asubject, atopic, adata) { //do stuff here } } aholdweak
true holds a weak reference to aobserver.
... return value returns boolean -
true the preference has a user set value.
... return value returns boolean -
true the preference is locked.
nsIProfile
useexistingdir if
true, an existing directory may be used; otherwise, the profile directory will be unique.
... candeletefiles if
true, the profile manager will try to delete all of the profile's files and its directory.
... return value
true if there is a profile with the specified name.
nsISHEntry
return value
true if this shistory entry is storing a detached editor.
...return value
true if any of the child entries returns
true when isdynamicallyadded() is called on it.
... isdynamicallyadded() returns
true if the related docshell was added because of dynamic addition of an iframe/frame.
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.
nsIThread
return value
true if there are pending events at the time the function was called.
... boolean processnextevent( in boolean maywait ); parameters maywait if
true, this method blocks until an event is available to process if the event queue is empty.
... return value returns
true if an event was processed, or false if there were no pending events.
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.
...a
true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed.
... if
true, the transaction manager will release() the new transaction instead of pushing it on the undo stack.
nsITransactionList
itemisbatch() returns
true if the item at aindex is a batch.
... note that currently there is no requirement for a transactionmanager implementation to associate a toplevel nsitransaction with a batch so it is possible for itemisbatch to return
true and getitem() to return null.
... return value
true if the item at aindex is a batch.
nsIWebContentHandlerRegistrar
can bypass this by opening about:config and setting preference of gecko.handlerservice.allowregisterfromdifferenthost to
true.
...tocol handler'permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when calling method: [nsiwebcontenthandlerregistrar::registerprotocolhandler] if the host names do match then a confirmation like this will be seen: this domain check can be bypassed by setting the preference of gecko.handlerservice.allowregisterfromdifferenthost to
true as in this code here: var {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/services.jsm"); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var allowregisterfromdifferenthost = services.prefs.getboolpref('gecko.handlerservice.allowregisterfromdifferenthost'...
...); if (!allowregisterfromdifferenthost) { services.prefs.setboolpref('gecko.handlerservice.allowregisterfromdifferenthost',
true); } var htmlcontentwindow = services.wm.getmostrecentwindow('navigator:browser'); //because we set the preference to
true above, we need any window that has a browser, just pass the domwindow and the registerprotocolhandler will get the contentwindow from it nsiwchr.registerprotocolhandler("mailto", "http://mail.live.com/secure/start?action=compose&to=%s", "outlook.com live mail", htmlcontentwindow); if (!allowregisterfromdifferenthost) { //it this variable is false, than we had set the pref to
true obviously.
nsIWindowMediator
return value pr_
true if the position returned is different from the position given.
... afronttoback if
true, the enumerator enumerates windows in order from front to back.
... afronttoback if
true, the enumerator enumerates windows in order from front to back.
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.
... return value this should (although does not need to) return pr_
true to indicate success or must return pr_false to indicate failure.
... return value this should (although does not need to) return pr_
true to indicate success or must return pr_false to indicate failure.
nsIXULRuntime
to get an instance, use: var xulruntime = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime); method overview void invalidatecachesonrestart(); attributes attribute type description accessibilityenabled boolean if
true, the accessibility service is running.
... browsertabsremoteautostart boolean if
true, browser tabs may be opened by default in a different process from the main browser ui.
...if a component encounters startup errors that might prevent the app from showing proper ui, it should set this flag to
true.
nsIXULTemplateResult
iscontainer boolean
true if the result represents a container.
... isempty boolean
true if the result represents an empty container.
... mayprocesschildren boolean
true if the template builder may use this result as the reference point for additional recursive processing of the template.
Mail and RDF
msgaccounts:/ +-- http://home.netscape.com/nc-rdf#child --> | imap://alecf@imap.mywork.com | +-- http://home.netscape.com/nc-rdf#isserver --> "
true" | +-- http://home.netscape.com/nc-rdf#child --> | imap://alecf@imap.mywork.com/inbox | +-- http://home.netscape.com/nc-rdf#totalmessages --> "4" | +-- http://home.netscape.com/nc-rdf#isserver --> "false" | +-- http://home.netscape.com/nc-rdf#messagechild --> | | imap_message://alecf@imap.mywork.com/inbox#1 | +-- http://home.
... +-- http://home.netscape.com/nc-rdf#child --> | mailbox://alecf@pop.mywork.com | +-- http://home.netscape.com/nc-rdf#isserver --> "
true" | +-- http://home.netscape.com/nc-rdf#child --> | mailbox://alecf@pop.mywork.com/inbox | +-- http://home.netscape.com/nc-rdf#totalmessages --> "2" | +-- http://home.netscape.com/nc-rdf#isserver --> "false" | +-- http://home.netscape.com/nc-rdf#messagechild --> | | mailbox_message://alecf@pop.mywork.com/inbox#1 | +-- http://h...
...this is basically what happens, behind the scenes: var target = rdf.getresource("mailbox://alecf@pop.myisp.com/inbox"); var property = rdf.getresource("http://home.netscape.com/nc-rdf#totalmessages"); var resultnode = datasource.gettarget(target, property,
true); in the folder datasource's gettarget(), target would be queryinterfaced to a nsimsgfolder.
Using tab-modal prompts
prompt to be tab-modal using code like this: var thewindow = gbrowser.contentwindow; let prompt = components.classes["@mozilla.org/prompter;1"] .getservice(components.interfaces.nsipromptfactory) .getprompt(thewindow, components.interfaces.nsiprompt); let bag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); bag.setpropertyasbool("allowtabmodal",
true); the var "thewindow" is a reference to the dom window.
...for example: var factory = components.classes["@mozilla.org/prompter;1"] .getservice(components.interfaces.nsipromptfactory); var prompt = factory.getprompt(gbrowser.contentwindow, components.interfaces.nsiprompt); var bag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); bag.setpropertyasbool("allowtabmodal",
true); var promptargs = ["devmo alert", "omg!
...re we apply the prompt with a checkbox: var window = gbrowser.contentwindow; var promptfact = components.classes['@mozilla.org/prompter;1'].getservice(components.interfaces.nsipromptfactory); var prompt = promptfact.getprompt(window, components.interfaces.nsiprompt); var promptbag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); promptbag.setpropertyasbool('allowtabmodal',
true); var check = {value: false}; //initial state of checkbox, however if no text is supplied the checkbox is not shown var input = {value: 'pre filled value'}; var ok = prompt.prompt.apply(null, ['title - but not shown in tab modal', 'text goes here', input, 'check text, if no text, checkbox is not shown', check]); //this here is just an alert, showing the values of the prompt prompt.alert.apply(...
Version, UI, and Status Information - Plugins
if the method returns
true, a windowless plug-in can confidently proceed.
...*/ return false; } else /* plug-in is running in a navigator version */ /* that has windowless support */ return
true; } detecting windowless support on other platforms browser implementations on other platforms did not have windowless plug-in support at the time it was added to ms windows and mac os x, so a different method must be used to detect whether the browser provides support.
... void npn_reloadplugins(npbool reloadpages); the reloadpages parameter is a boolean that indicates whether to reload the page (
true) or not (false).
Examine and edit CSS - Firefox Developer Tools
you can: toggle pseudo-classes; toggle classes; add a new rule; change the display based on the color scheme preference (as of firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to
true in the configuration editor to enable this feature); change the display based on print media rules.
... view @media rules for color-scheme-preference as of firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to
true in the configuration editor to enable this feature.
... if you have set privacy.resistfingerprinting to
true, prefers-color-scheme preference is overridden to light.
Intensive JavaScript - Firefox Developer Tools
here's the code, together with its immediate caller: const iterations = 50; const multiplier = 1000000000; function calculateprimes(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 = fals...
...lity 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.bind(this, index + 1); window.requestanimationframe(testfunction); } var primes = []; var testfunctio...
... { var iterations = message.data.iterations; var multiplier = message.data.multiplier; primes = calculateprimes(iterations, multiplier); self.postmessage({ "command":"done", "primes": primes }); } function calculateprimes(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.
about:debugging (before Firefox 68) - Firefox Developer Tools
if you need to see system add-ons, navigate to about:config and make sure that this value is set to
true.
...both preferences must be
true to enable add-on debugging.
... checking the box sets both preferences to
true, and unchecking it sets them both to false.
about:debugging - Firefox Developer Tools
if your about:debugging page is different from the one displayed here, go to about:config, find and set the option devtools.aboutdebugging.new-enabled to
true.
...if you need to see these extensions, navigate to about:config and make sure that the preference is set to
true.
... to enable it, open the configuration editor (about:config) and set devtools.aboutdebugging.new-enabled to
true.
AudioBufferSourceNode.loopStart - Web APIs
this value is only used when the loop parameter is
true.
... function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = ...
...
true; loopstartcontrol.setattribute('max', math.floor(songlength)); loopendcontrol.setattribute('max', math.floor(songlength)); }, function(e){"error with decoding audio data" + e.err}); } request.send(); } ...
Cache.keys() - Web APIs
if set to
true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... ignoremethod: a boolean that, when set to
true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false.
... ignorevary: a boolean that, when set to
true, tells the matching operation not to perform vary header matching.
Cache.match() - Web APIs
for example, if set to
true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... ignoremethod: a boolean that, when set to
true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false.
... ignorevary: a boolean that when set to
true tells the matching operation not to perform vary header matching — i.e.
Cache.matchAll() - Web APIs
if set to
true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... ignoremethod: a boolean that, when set to
true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false.
... ignorevary: a boolean that when set to
true tells the matching operation not to perform vary header matching — i.e.
CacheStorage.has() - Web APIs
the has() method of the cachestorage interface returns a promise that resolves to
true if a cache object matches the cachename.
... syntax caches.has(cachename).then(function(boolean) { //
true: your cache exists!
... return value a promise that resolves to
true if the cache exists or false if not.
CacheStorage.match() - Web APIs
for example, if set to
true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... ignoremethod: a boolean that, when set to
true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false.
... ignorevary: a boolean that, when set to
true, tells the matching operation not to perform vary header matching.
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
the imagesmoothingenabled property of the canvasrenderingcontext2d interface, part of the canvas api, determines whether scaled images are smoothed (
true, default) or not (false).
...the default value is
true.
...lementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '16px sans-serif'; ctx.textalign = 'center'; const img = new image(); img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png'; img.onload = function() { const w = img.width, h = img.height; ctx.filltext('source', w * .5, 20); ctx.drawimage(img, 0, 24, w, h); ctx.filltext('smoothing =
true', w * 2.5, 20); ctx.imagesmoothingenabled =
true; ctx.drawimage(img, w, 24, w * 3, h * 3); ctx.filltext('smoothing = false', w * 5.5, 20); ctx.imagesmoothingenabled = false; ctx.drawimage(img, w * 4, 24, w * 3, h * 3); }; result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.imagesmoothingenabled...
Applying styles and colors - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokestyle = 'rgb(0, ' + math.floor(255 - 42.5 * i) + ', ' + math.floor(255 - 42.5 * j) + ')'; ctx.beginpath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, math.pi * 2,
true); ctx.stroke(); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); the result looks like this: screenshotlive sample transparency in addition to drawing opaque shapes to the canvas, we can also draw semi-transparent (or translucent) shapes.
... 75, 75); ctx.fillstyle = '#6c0'; ctx.fillrect(75, 0, 75, 75); ctx.fillstyle = '#09f'; ctx.fillrect(0, 75, 75, 75); ctx.fillstyle = '#f30'; ctx.fillrect(75, 75, 75, 75); ctx.fillstyle = '#fff'; // set transparency value ctx.globalalpha = 0.2; // draw semi transparent circles for (var i = 0; i < 7; i++) { ctx.beginpath(); ctx.arc(75, 75, 10 + 10 * i, 0, math.pi * 2,
true); ctx.fill(); } } <canvas id="canvas" width="150" height="150"></canvas> draw(); screenshotlive sample an example using rgba() in this second example, we do something similar to the one above, but instead of drawing circles on top of each other, i've drawn small rectangles with increasing opacity.
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.beginpath(); ctx.arc(50, 50, 30, 0, math.pi * 2,
true); ctx.arc(50, 50, 15, 0, math.pi * 2,
true); ctx.fill('evenodd'); } <canvas id="canvas" width="100" height="100"></canvas> draw(); screenshotlive sample « previousnext » ...
Drawing shapes with canvas - Web APIs
<html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(75, 75, 50, 0, math.pi * 2,
true); // outer circle ctx.moveto(110, 75); ctx.arc(75, 75, 35, 0, math.pi, false); // mouth (clockwise) ctx.moveto(65, 65); ctx.arc(60, 65, 5, 0, math.pi * 2,
true); // left eye ctx.moveto(95, 65); ctx.arc(90, 65, 5, 0, math.pi * 2,
true); // right eye ctx.stroke(); } } the result looks like this: screenshotlive sample if you'd like to see the connecting lines, yo...
...the anticlockwise parameter is a boolean value which, when
true, draws the arc anticlockwise; otherwise, the arc is drawn clockwise.
... 103, 95, 101); ctx.beziercurveto(95, 99, 94, 96, 91, 96); ctx.moveto(103, 96); ctx.beziercurveto(100, 96, 99, 99, 99, 101); ctx.beziercurveto(99, 103, 100, 106, 103, 106); ctx.beziercurveto(106, 106, 107, 103, 107, 101); ctx.beziercurveto(107, 99, 106, 96, 103, 96); ctx.fill(); ctx.fillstyle = 'black'; ctx.beginpath(); ctx.arc(101, 102, 2, 0, math.pi * 2,
true); ctx.fill(); ctx.beginpath(); ctx.arc(89, 102, 2, 0, math.pi * 2,
true); ctx.fill(); } } // a utility function to draw a rectangle with rounded corners.
Constraint validation API - Web APIs
willvalidate a read-only boolean property that returns
true if the element is a candidate for constraint validation; and false otherwise.
...if the value is invalid, it fires an invalid event at the element and returns false; otherwise it returns
true.
...otherwise, it returns
true.
DOMImplementation.hasFeature() - Web APIs
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.
Document.importNode() - Web APIs
if deep is set to
true, then externalnode and all of its descendants are copied.
... note: in the dom4 specification, deep was an optional argument with a default value of
true.
... example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode,
true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode().
Element.getAnimations() - Web APIs
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.
... promise.all( elem.getanimations({ subtree:
true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification status comment web animationsthe definition of 'animatable.getanimations()' in that specification.
Element.setAttribute() - Web APIs
boolean attributes are considered to be
true if they're present on the element at all, regardless of their actual value; as a rule, you should specify the empty string ("") in value (some people use the attribute's name; this works but is non-standard).
...all that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be
true.
...by setting the value of the disabled attribute to the empty string (""), we are setting disabled to
true, which results in the button being disabled.
Event.eventPhase - Web APIs
this is known as bubbling, and occurs only if event.bubbles is
true.
...elementbyid('divinfo') divs = document.getelementsbytagname('div') chcapture = document.getelementbyid('chcapture') chcapture.onclick = function () { removelisteners() addlisteners() } clear() addlisteners() } function removelisteners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divinfo") { d.removeeventlistener("click", ondivclick,
true) d.removeeventlistener("click", ondivclick, false) } } } function addlisteners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divinfo") { if (chcapture.checked) { d.addeventlistener("click", ondivclick,
true) } else { d.addeventlistener("click", ondivclick, false) d.onmousemove = function ...
...() { clear =
true } } } } } function ondivclick(e) { if (clear) { clear() clear = false } if (e.eventphase == 2) e.currenttarget.style.backgroundcolor = 'red'; let level = e.eventphase == 0 ?
GamepadEvent - Web APIs
prefix: webkitedge full support ≤18firefox full support 29 full support 29 no support 24 — 28disabled disabled from version 24 until version 28 (exclusive): this feature is behind the dom.gamepad.enabled preference (needs to be set to
true).
... 35edge full support 12firefox full support 29 full support 29 no support 24 — 28disabled disabled from version 24 until version 28 (exclusive): this feature is behind the dom.gamepad.enabled preference (needs to be set to
true).
...or prefix: webkitedge full support 12firefox full support 29 full support 29 no support 24 — 28disabled disabled from version 24 until version 28 (exclusive): this feature is behind the dom.gamepad.enabled preference (needs to be set to
true).
Using the Gamepad API - Web APIs
var gamepads = {}; function gamepadhandler(event, connecting) { var gamepad = event.gamepad; // note: // gamepad === navigator.getgamepads()[gamepad.index] if (connecting) { gamepads[gamepad.index] = gamepad; } else { delete gamepads[gamepad.index]; } } window.addeventlistener("gamepadconnected", function(e) { gamepadhandler(e,
true); }, false); window.addeventlistener("gamepaddisconnected", function(e) { gamepadhandler(e, false); }, false); this previous example also demonstrates how the gamepad property can be held after the event has completed — a technique we will use for device state querying later.
...if this is so the value is
true; if not, it is false.
...each gamepadbutton has a pressed and a value property: the pressed property is a boolean indicating whether the button is currently pressed (
true) or unpressed (false).
HTMLCanvasElement.mozOpaque - Web APIs
syntax var opaque = canvas.mozopaque; canvas.mozopaque =
true; examples given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> you can get or set the mozopaque property.
... for example, you could conditionally set it to
true if mimetype == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed.
... var canvas = document.getelementbyid('canvas'); console.log(canvas.mozopaque); //
true // deactivate it canvas.mozopaque = false; specifications not part of any standard.
HTMLElement.hidden - Web APIs
the htmlelement property hidden is a boolean which is
true if the element is hidden; otherwise the value is false.
... syntax ishidden = htmlelement.hidden; htmlelement.hidden =
true | false; value a boolean which is
true if the element is hidden from view; otherwise, the value is false.
... javascript document.getelementbyid("okbutton") .addeventlistener("click", function() { document.getelementbyid("welcome").hidden =
true; document.getelementbyid("awesome").hidden = false; }, false); this code sets up a handler for the welcome panel's "ok" button that hides the welcome panel and makes the follow-up panel—with the curious name "awesome"—visible in its place.
HTMLImageElement.sizes - Web APIs
each source size descriptor is comprised of a media condition, then at least one whitespace character, then the source size value to use for the image when the media condition evaluates to
true.
... 45edge full support 13firefox full support 38 full support 38 no support 33 — 52disabled disabled from version 33 until version 52 (exclusive): this feature is behind the dom.image.picture.enabled preference (needs to be set to
true).
...android full support 45firefox android full support 38 full support 38 no support 33 — 52disabled disabled from version 33 until version 52 (exclusive): this feature is behind the dom.image.picture.enabled preference (needs to be set to
true).
HTMLInputElement - Web APIs
it is false if any conditions bar it from constraint validation, including: its type is hidden, reset, or button; it has a <datalist> ancestor; its disabled property is
true.
... webkitdirectory boolean: returns the webkitdirectory attribute; if
true, the file system picker interface only accepts directories instead of files.
...it returns
true if the element is not a candidate for constraint validation, or if it satisfies its constraints.
HTMLMarqueeElement - Web APIs
note that any value smaller than 60 is ignored and the value 60 is used instead, unless
truespeed is
true.
... htmlmarqueeelement.
truespeed by default, scrolldelay values lower than 60 are ignored.
... if
truespeed is
true, then those values are not ignored.
HTMLMediaElement.controls - Web APIs
syntax var ctrls = video.controls; audio.controls =
true; value a boolean.
... a value of
true means controls will be displayed.
... example var obj = document.createelement('video'); obj.controls =
true; specifications specification status comment html living standardthe definition of 'htmlmediaelement.controls' in that specification.
HTMLMediaElement.defaultMuted - Web APIs
syntax var dmuted = video.defaultmuted; audio.defaultmuted =
true; value a boolean.
... a value of
true means that the audio output will be muted by default.
... example var videoele = document.createelement('video'); videoele.defaultmuted =
true; console.log(videoele.outerhtml); // <video muted=""></video> specifications specification status comment html living standardthe definition of 'htmlmediaelement.defaultmuted' in that specification.
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.
... using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('pause', (event) => { console.log('the boolean paused property is now
true.
... either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); using the onpause event handler property: const video = document.queryselector('video'); video.onpause = (event) => { console.log('the boolean paused property is now
true.
Option() - Web APIs
note that a value of
true does not set the option to selected if it is not already selected.
...if omitted, even if the defaultselected argument is
true, the option is not selected.
...t</option> <option>second</option> <option>third</option> </select> */ var s = document.getelementbyid('s'); var options = [ 'zero', 'one', 'two' ]; options.foreach(function(element, key) { if (element == 'zero') { s[s.options.length] = new option(element, s.options.length, false, false); } if (element == 'one') { s[s.options.length] = new option(element, s.options.length,
true, false); // will add the "selected" attribute } if (element == 'two') { s[s.options.length] = new option(element, s.options.length, false,
true); // just will be selected in "view" } }); /* result <select id="s"> <option value="0">zero</option> <option value="1" selected="">one</option> <option value="2">two</option> // user will see this as 'selected' </select> */ specification...
HTMLSelectElement - Web APIs
the default is 1, unless multiple is
true, in which case it is 4.
...when multiple is
true, it returns "select-multiple"; otherwise, it returns "select-one".
...if there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns
true.
HTMLSlotElement.assignedElements() - Web APIs
if the flatten option is set to
true, it also returns the assigned elements of any other slots that are descendants of this slot.
...the available options are: flatten: a boolean indicating whether to return the assigned elements of any available child <slot> elements (
true) or not (false).
... examples let slots = this.shadowroot.queryselector('slot'); let elements = slots.assignedelements({flatten:
true}); specifications specification status comment html living standardthe definition of 'assignedelements()' in that specification.
HTMLTextAreaElement - Web APIs
false if any conditions bar it from constraint validation, including its readonly or disabled property is
true.
...it returns
true if the control is not a candidate for constraint validation, or if it satisfies its constraints.
...if there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns
true.
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
syntax htmlvideoelement.msislayoutoptimalforplayback: domstring; value boolean value set to
true indicates that video is being rendered optimally (better performance and using less battery power).
... for msislayoutoptimalforplayback to be
true, avoid the following: video elements with cascading style sheets (css) outlines set.
... *to enable stereo 3d playback, msislayoutoptimalforplayback must be
true.
The HTML DOM API - Web APIs
javascript const namefield = document.getelementbyid("username"); const sendbutton = document.getelementbyid("sendbutton") sendbutton.disabled =
true; // [note: this is disabled since it causes this article to always load with this example focused and scrolled into view] //namefield.focus(); namefield.addeventlistener("input", event => { const elem = event.target; const valid = elem.value.length != 0; if (valid && sendbutton.disabled) { sendbutton.disabled = false; } else if (!valid && !sendbutton.disabled) { sendbutton.disab...
...led =
true; } }); this code uses the document interface's getelementbyid() method to get the dom object representing the <input> elements whose ids are username and sendbutton.
... the htmlinputelement object for the "send" button's disabled property is set to
true, which disables the "send" button so it can't be clicked.
IDBKeyRange - Web APIs
to retrieve all keys within a certain range, you can use the following code constructs: range code all keys ≥ x idbkeyrange.lowerbound(x) all keys > x idbkeyrange.lowerbound(x,
true) all keys ≤ y idbkeyrange.upperbound(y) all keys < y idbkeyrange.upperbound(y,
true) all keys ≥ x && ≤ y idbkeyrange.bound(x, y) all keys > x &&< y idbkeyrange.bound(x, y,
true,
true) all keys > x && ≤ y idbkeyrange.bound(x, y,
true, false) all keys ≥ x &&< y idbkeyrange.bound(x, y, false,
true) the key = ...
...z idbkeyrange.only(z) a key is in a key range if the following conditions are
true: the lower value of the key range is one of the following: undefined less than key value equal to key value if loweropen is false.
...if we used idbkeyrange.bound("a", "f",
true,
true);, then the range would not include "a" and "f", only the values between them.
IDBObjectStore.createIndex() - Web APIs
objectparameters optional an idbindexparameters object, which can include the following properties: attribute description unique if
true, the index will not allow duplicate values for a single key.
... multientry if
true, the index will add an entry in the index for each array element when the keypath resolves to an array.
... invalidaccesserror occurs if the provided key path is a sequence, and multientry is set to
true in the objectparameters object.
IntersectionObserverEntry.isIntersecting - Web APIs
the intersectionobserverentry interface's read-only isintersecting property is a boolean value which is
true if the target element intersects with the intersection observer's root.
... if this is
true, then, the intersectionobserverentry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting.
... syntax var isintersecting = intersectionobserverentry.isintersecting; value a boolean value which indicates whether the target element has transitioned into a state of intersection (
true) or out of a state of intersection (false).
Intersection Observer API - Web APIs
similarly, if the visible portion of an element is not rectangular, the element's intersection rectangle is cons
trued to be the smallest rectangle that contains all the visible portions of the element.
... you can see if the target currently intersects the root by looking at the entry's isintersecting property; if its value is
true, the target is at least partially intersecting the root element or document.
... let thresholdsets = [ [], [0.5], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], [0, 0.25, 0.5, 0.75, 1.0] ]; for (let i=0; i<=1.0; i+= 0.01) { thresholdsets[0].push(i); } // add each box, creating a new observer for each for (let i=0; i<4; i++) { let template = document.queryselector("#boxtemplate").content.clonenode(
true); let boxid = "box" + (i+1); template.queryselector(".samplebox").id = boxid; wrapper.appendchild(document.importnode(template,
true)); // set up the observer for this box observeroptions.threshold = thresholdsets[i]; observers[i] = new intersectionobserver(intersectioncallback, observeroptions); observers[i].observe(document.queryselector("#" + boxid)); } // sc...
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.
... } else if (event.keycode !== undefined) { // handle the event with keyboardevent.keycode and set handled
true.
... } if (handled) { // suppress "double action" if event handled event.preventdefault(); } },
true); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.keycode' in that specification.
LargestContentfulPaint - Web APIs
this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to
true.
...(note: `rendertime` may not be available on // image elements loaded cross-origin without the `timing-allow-origin` header.) lcp = lastentry.rendertime || lastentry.loadtime; }); po.observe({type: 'largest-contentful-paint', buffered:
true}); // send data to the server.
... addeventlistener('visibilitychange', function fn() { if (lcp && document.visibilitystate === 'hidden') { console.log('lcp:', lcp); removeeventlistener('visibilitychange', fn,
true); } },
true); } catch (e) { // do nothing if the browser doesn't support this api.
LockManager.request() - Web APIs
ifavailable optional: if
true, the lock request will only be granted if it is not already held.
... steal optional: if
true, then any held locks with the same name will be released, and the request will be granted, preempting any queued requests for it.
... await navigator.locks.request('my_resource', {ifavailable:
true}, async lock => { if (!lock) { // the lock was not granted - get out fast.
MediaCapabilitiesInfo - Web APIs
if yes, supported is
true.
... if supported is
true, and playback will be smooth, smooth is
true, otherwise, is it false.
...if supported is
true, and playback will be power efficient, powerefficient is
true, otherwise, is it false.
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.
... syntax var isactive = mediastream.active; value a boolean value which is
true if the stream is currently active; otherwise, the value is false.
... var promise = navigator.mediadevices.getusermedia({ audio:
true, video:
true }); promise.then(function(stream) { var startbtn = document.queryselector('#startbtn'); startbtn.disabled = stream.active; };) specifications specification status comment media capture and streamsthe definition of 'active' in that specification.
MediaStreamConstraints.video - Web APIs
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.
... examples using a boolean value in this example, we provide a simple value of
true for the video property.
...op: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { 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.
MutationObserver.observe() - Web APIs
(for example, if mutationobserverinit.childlist, mutationobserverinit.attributes, and mutationobserverinit.characterdata are all false.) the value of options.attributes is false (indicating that attribute changes are not to be monitored), but attributeoldvalue is
true and/or attributefilter is present.
... the characterdataoldvalue option is
true but mutationobserverinit.characterdata is false (indicating that character changes are not to be monitored).
...rgetelementid"); // create a new instance of `mutationobserver` named `observer`, // passing it a callback function const observer = new mutationobserver(function() { console.log('callback that runs when observer is triggered'); }); // call `observe()` on that mutationobserver instance, // passing it the element to observe, and the options object observer.observe(elementtoobserve, {subtree:
true, childlist:
true}); specifications specification status comment domthe definition of 'mutationobserver.observe()' in that specification.
MutationObserverInit.childList - Web APIs
by setting childlist to
true, your callback will be invoked any time nodes are added to or removed from the dom node or nodes being watched.
... syntax var options = { childlist:
true | false } value a boolean value indicating whether or not to invoke the callback function when new nodes are added to or removed from the section of the dom being monitored..
...setting subtree to
true causes addition or removal of nodes anywhere within the subtree rooted at target to be reported.
Node.cloneNode() - Web APIs
deep optional* if
true, then node and its whole subtree—including text that may be in child text nodes—is also copied.
... *note: in the dom4 specification (since gecko 13.0 (firefox 13 / thunderbird 13 / seamonkey 2.10)), the optional deep argument defaults to
true.
... example let p = document.getelementbyid("para1") let p_prime = p.clonenode(
true) notes cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners.
Node.isConnected - Web APIs
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...
...h the created style element to the shadow dom shadow.appendchild(style); console.log(style.isconnected); // returns
true polyfill node.isconnected can be polyfilled with the following code for ie10 and edgehtml: /* * node.isconnected polyfill for ie and edgehtml * 2020-02-04 * * by eli grey, https://eligrey.com * public domain.
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.
... example var xulns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getelementsbytagnamens(xulns, 'textbox')[0]; alert(el.isdefaultnamespace(xulns)); //
true specifications specification status comment domthe definition of 'node: isdefaultnamespace' in that specification.
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.
... 61edge full support 16firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 53firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.onshippingoptionchange - Web APIs
var request = new paymentrequest(supportedinstruments, details, options); // when user selects a shipping address request.addeventlistener('shippingaddresschange', e => { e.updatewith(((details, addr) => { var shippingoption = { id: '', label: '', amount: { currency: 'usd', value: '0.00' }, selected:
true }; // shipping to us is supported if (addr.country === 'us') { shippingoption.id = 'us'; shippingoption.label = 'standard shipping in us'; shippingoption.amount.value = '0.00'; details.total.amount.value = '55.00'; // shipping to jp is supported } else if (addr.country === 'jp') { shippingoption.id = 'jp'; shippingoption.label = 'internation...
... 61edge full support 15firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 53firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.shippingOption - Web APIs
this attribute is only populated if the constructor is called with the requestshipping flag set to
true.
... 61edge full support 15firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 53firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentResponse.payerEmail - Web APIs
this option is only present when the requestpayeremail option is set to
true in the paymentoptions object passed to the paymentrequest constructor.
... 61edge full support 15firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
...to change preferences in chrome, visit chrome://flags.firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.payerName - Web APIs
this option is only present when the requestpayername option is set to
true in the options parameter of the paymentrequest() constructor.
... 61edge full support 15firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 58firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PerformanceEventTiming - Web APIs
0 : infinity; document.addeventlistener('visibilitychange', (event) => { firsthiddentime = math.min(firsthiddentime, event.timestamp); }, {once:
true}); // sends the passed data to an analytics endpoint.
... (navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || fetch('/analytics', {body, method: 'post', keepalive:
true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option.
... po.observe({ type: 'first-input', buffered:
true, }); } catch (e) { // do nothing if the browser doesn't support this api.
RTCDataChannel.negotiated - Web APIs
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).
... syntax var negotiated = adatachannel.negotiated; value
true if the rtcdatachannel's connection was negotiated by the web app itself; false if the negotiation was handled by the webrtc layer.
... example the code snippet below checks the value of negotiated; if it's
true, a function called shutdownremotechannel() is called with the channel's id; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection.
RTCIceCandidateStats - Web APIs
for local candidates, it's value is
true if the candidate has been deleted or released.
... for host candidates,
true means that any network resources (usually a network socket) associated with the candidate have already been released.
... 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 would b...
RTCOfferAnswerOptions.voiceActivityDetection - Web APIs
the default value,
true, indicates that voice detection should be used and that if possible, the user agent should automatically disable or mute outgoing audio when the audio source is not sensing a human voice.
... syntax var options = { voiceactivitydetection:
trueorfalse }; value a boolean value indicating whether or not the connection should use voice detection once running.
... the default value,
true, indicates that the user agent should monitor the audio coming from the microphone or other audio source and automatically cease transmitting data or mute when the user isn't speaking into the microphone, a value of false indicates that the audio should continue to be transmitted regardless of whether or not speech is detected.
RTCPeerConnection.addTrack() - Web APIs
here's an example showing a function that uses getusermedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video:
true, audio:
true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations.
... for example, consider this function that an application might use to begin streaming a device's camera and microphone input over an rtcpeerconnection to a remote peer: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video:
true, audio:
true}); for (const track of gumstream.gettracks()) { pc.addtrack(track, gumstream); } } the remote peer might then use a track event handler that looks like this: pc.ontrack = ({streams: [stream]} => videoelem.srcobject = stream; this sets the video element's current stream to the one that contains the track that's been added to the connection.
... 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 ...
ReadableStream.pipeThrough() - Web APIs
available options are: preventclose: if this is set to
true, the source readablestream closing will no longer cause the destination writablestream to be closed.
... preventabort: if this is set to
true, errors in the source readablestream will no longer abort the destination writablestream.
... preventcancel: if this is set to
true, errors in the destination writablestream will no longer cancel the source readablestream.
ReadableStream.pipeTo() - Web APIs
available options are: preventclose: if this is set to
true, the source readablestream closing will no longer cause the destination writablestream to be closed.
... preventabort: if this is set to
true, errors in the source readablestream will no longer abort the destination writablestream.
... preventcancel: if this is set to
true, errors in the destination writablestream will no longer cancel the source readablestream.
ReadableStreamDefaultReader.read() - Web APIs
if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done:
true }.
... 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.
...always undefined when done is
true.
Using the Screen Capture API - Web APIs
logicalsurface a boolean which if
true indicates that the capture should include offscreen areas of the source, if there are any.
... to request that the screen be shared with included audio, the options passed into getdisplaymedia() might look like this: const gdmoptions = { video:
true, audio:
true } this allows the user total freedom to select whatever they want, within the limits of what the user agent supports.
... this could be refined further by specifying additional information for each of audio and video: const gdmoptions = { video: { cursor: "always" }, audio: { echocancellation:
true, noisesuppression:
true, samplerate: 44100 } } in this example the cursor will always be visible in the capture, and the audio track should ideally have noise suppression and echo cancellation features enabled, as well as an ideal audio sample rate of 44.1khz.
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.
... console.log(window.getselection().containsnode(document.body,
true)); find the hidden word in this example, a message appears when you select the secret word.
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.
TextTrack.mode - Web APIs
safari additionally requires the default boolean attribute to be set to
true when implementing your own video player controls in order for the subtitles cues to be shown.
...this is done by setting the pauseonexit property on each cue to
true.
... window.addeventlistener("load", event => { let trackelem = document.queryselector("track"); let track = trackelem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pauseonexit =
true; }; }); specifications specification status comment html living standardthe definition of 'mode' in that specification.
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.
... example using a json file: { msmanipulationviewsenabled:
true, } see also touch api microsoft api extensions ...
TouchEvent.targetTouches - Web APIs
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.
...
true : false); } specifications specification status comment touch events – level 2 draft non-stable version.
URLSearchParams - Web APIs
for (let p of searchparams) { console.log(p); } searchparams.has("topic") ===
true; //
true searchparams.get("topic") === "api"; //
true searchparams.getall("topic"); // ["api"] searchparams.get("foo") === null; //
true searchparams.append("topic", "webdev"); searchparams.tostring(); // "q=urlutils.searchparams&topic=api&topic=webdev" searchparams.set("topic", "more webdev"); searchparams.tostring(); // "q=urlutils.searchparams&topic=more+webdev" searchparams.delete("topic"); s...
... var paramsstring1 = "http://example.com/search?query=%40"; var searchparams1 = new urlsearchparams(paramsstring1); searchparams1.has("query"); // false searchparams1.has("http://example.com/search?query"); //
true searchparams1.get("query"); // null searchparams1.get("http://example.com/search?query"); // "@" (equivalent to decodeuricomponent('%40')) var paramsstring2 = "?query=value"; var searchparams2 = new urlsearchparams(paramsstring2); searchparams2.has("query"); //
true var url = new url("http://example.com/search?query=%40"); var searchparams3 = new urlsearchparams(url.search); searchparams3.has(...
..."query") //
true specifications specification status comment urlthe definition of 'urlsearchparams' in that specification.
ValidityState.rangeOverflow - Web APIs
if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a max value is set, if the value don't doesn't conform to the constraints set by the max value, the rangeoverflow property will be
true.
... given the following: <input type="number" min="20" max="40" step="2"/> if value > 40, rangeoverflow will be
true.
... when
true, the element matches the :invalid and :out-of-range css pseudo-classes.
ValidityState.rangeUnderflow - Web APIs
if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a min value is set, if the value don't doesn't conform to the constraints set by the min value, the rangeunderflow property will be
true.
... given the following: <input type="number" min="20" max="40" step="2"/> if value < 20, rangeunderflow will be
true.
... when
true, the element matches the :invalid and :out-of-range css pseudo-classes.
ValidityState.stepMismatch - Web APIs
if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and the step value is not any, if the value don't doesn't conform to the constraints set by the step and min values, then stepmismatch will be
true.
... given the following: <input type="number" min="20" max="40" step="2"/> if (value - min) / 2 != 0, stepmismatch will be
true.
... if
true, the element matches the :invalid and :out-of-range css pseudo-classes.
ValidityState.typeMismatch - Web APIs
if the type attribute expects specific strings, such as the email and url types and the value don't doesn't conform to the constraints set by the type, the typemismatch property will be
true.
...for example, if the number input value is not a floating point number, the badinput is
true.
... if the email is required but is empty, the valuemissing will be
true.
WebGLRenderingContext.makeXRCompatible() - Web APIs
1"; let glstartbutton; let xrstartbutton; window.addeventlistener("load", (event) => { loadsceneresources(currentscene); glstartbutton.addeventlistener("click", handlestartbuttonclick); xrstartbutton.addeventlistener("click", handlestartbuttonclick); }); outputcanvas.addeventlistener("webglcontextlost", (event) => { /* the context has been lost but can be restored */ event.canceled =
true; }); /* when the gl context is reconnected, reload the resources for the current scene.
...box("you don't appear to have a compatible xr headset available.", "cancel"); break; default: handlefatalerror(err); break; } xrsession.end(); } } async function handlestartbuttonclick(event) { if (event.target.classlist.contains("use-webxr") && navigator.xr) { try { xrsession = await navigator.xr.requestsession("immersive-vr"); usingxr =
true; } catch(err) { xrsession = null; usingxr = false; } } startgame(); } function startgame() { currentscene = "scene1"; loadsceneresources(currentscene); /* and so on */ } this works by having two buttons, one which starts the game normally and the other which starts the game in vr mode.
...if the button clicked by the user has that class (and we've confirmed that webxr is available by ensuring that the navigator.xr property exists), we use requestsession() to request a new webxr session and set the usingxr flag to
true.
A simple RTCDataChannel sample - Web APIs
these handlers can do whatever's needed, but in this example, all we need to do is update the user interface: function handlelocaladdcandidatesuccess() { connectbutton.disabled =
true; } function handleremoteaddcandidatesuccess() { disconnectbutton.disabled = false; } the only thing we do here is disable the "connect" button when the local peer is connected and enable the "disconnect" button when the remote peer connects.
...ose event, the handlesendchannelstatuschange() method is called: function handlesendchannelstatuschange(event) { if (sendchannel) { var state = sendchannel.readystate; if (state === "open") { messageinputbox.disabled = false; messageinputbox.focus(); sendbutton.disabled = false; disconnectbutton.disabled = false; connectbutton.disabled =
true; } else { messageinputbox.disabled =
true; sendbutton.disabled =
true; connectbutton.disabled = false; disconnectbutton.disabled =
true; } } } if the channel's state has changed to "open", that indicates that we have finished establishing the link between the two peers.
... sendchannel.close(); receivechannel.close(); // close the rtcpeerconnections localconnection.close(); remoteconnection.close(); sendchannel = null; receivechannel = null; localconnection = null; remoteconnection = null; // update user interface elements connectbutton.disabled = false; disconnectbutton.disabled =
true; sendbutton.disabled =
true; messageinputbox.value = ""; messageinputbox.disabled =
true; } this starts by closing each peer's rtcdatachannel, then, similarly, each rtcpeerconnection.
Taking still photos with WebRTC - Web APIs
function startup() { video = document.getelementbyid('video'); canvas = document.getelementbyid('canvas'); photo = document.getelementbyid('photo'); startbutton = document.getelementbyid('startbutton'); get the media stream the next task is to get the media stream: navigator.mediadevices.getusermedia({ video:
true, audio: false }) .then(function(stream) { video.srcobject = stream; video.play(); }) .catch(function(err) { console.log("an error occurred: " + err); }); here, we're calling mediadevices.getusermedia() and requesting a video stream (without audio).
... video.addeventlistener('canplay', function(ev){ if (!streaming) { height = video.videoheight / (video.videowidth/width); video.setattribute('width', width); video.setattribute('height', height); canvas.setattribute('width', width); canvas.setattribute('height', height); streaming =
true; } }, false); this callback does nothing unless it's the first time it's been called; this is tested by looking at the value of our streaming variable, which is false the first time this method is run.
...finally, we set the streaming variable to
true to prevent us from inadvertently running this setup code again.
Using DTMF with WebRTC - Web APIs
let dialstring = "12024561111"; let callerpc = null; let receiverpc = null; let dtmfsender = null; let hasaddtrack = false; let mediaconstraints = { audio:
true, video: false }; let offeroptions = { offertoreceiveaudio: 1, offertoreceivevideo: 0 }; let dialbutton = null; let logelement = null; these are, in order: dialstring the dtmf string the caller will send when the "dial" button is clicked.
...we want an audio-only connection, so video is false, while audio is
true.
...if it does, we set hasaddtrack to
true; otherwise, we set it to false.
Using WebRTC data channels - Web APIs
let datachannel = pc.createdatachannel("myapp channel"); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); manual negotiation to manually negotiate the data channel connection, you need to first create a new rtcdatachannel object using the createdatachannel() method on the rtcpeerconnection, specifying in the options a negotiated property set to
true.
...this process should signal to the remote peer that it should create its own rtcdatachannel with the negotiated property also set to
true, using the same id.
... let datachannel = pc.createdatachannel("myapp channel", { negotiated:
true }); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); requestremotechannel(datachannel.id); in this code snippet, the channel is created with negotiated set to
true, then a function called requestremotechannel() is used to trigger negotiation, to create a remote channel with the same id as the local channel.
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
zooming by adjusting field of view you can do something more akin to a
true "zoom" by altering the camera's field of view (fov).
...this is an effect of the focal length in a physical camera, so since there is no
true camera, altering the fov is a passable substitute.
... scaling transforms unlike a
true "zoom", scaling involves multiplying each of the x, y, and z coordinate values in a position or vertex by a scaling factor for that axis.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
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.
... some xr hardware uses algorithms to compute the estimated position of the user based on the movement currently ongoing, while other hardware will report no movement at all, but with emulatedposition set to
true.
... <<<--- more text and example about how to handle rendering during lost tracking --->>> when tracking resumes you can detect when tracking has resumed after being lost when the user position jumps while at the same time the value of emulatedposition changes from
true to false.
Using the Web Speech API - Web APIs
we also set a few other properties of the recognition instance before we move on: speechrecognition.continuous: controls whether continuous results are captured (
true), or just a single result each time recognition is started (false).
... browser support support for web speech api speech synthesis is still getting there across mainstream browsers, and is currently limited to the following: firefox desktop and mobile support it in gecko 42+ (windows)/44+, without prefixes, and it can be turned on by flipping the media.webspeech.synth.enabled flag to
true in about:config.
...we then loop through this list — for each voice we create an <option> element, set its text content to display the name of the voice (grabbed from speechsynthesisvoice.name), the language of the voice (grabbed from speechsynthesisvoice.lang), and -- default if the voice is the default voice for the synthesis engine (checked by seeing if speechsynthesisvoice.default returns
true.) we also create data- attributes for each option, containing the name and language of the associated voice, so we can grab them easily later on, and then append the options as children of the select.
window.location - Web APIs
location.assign("http://www.mozilla.org"); // or location = "http://www.mozilla.org"; example #2: force reloading the current page from the server location.reload(
true); example #3 consider the following example, which will reload the page by using the replace() method to insert the value of location.pathname into the hash: function reloadpagewithhash() { var initialpage = location.pathname; location.replace('http://example.com/#' + initialpage); } example #4: display the properties of the current url in an alert dialog: function showloc() { var olo...
... 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 (_scrollid > -1) { clearin...
...ow.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 specification.
Using XMLHttpRequest - Web APIs
if this argument is
true or not specified, the xmlhttprequest is processed asynchronously, otherwise the process is handled synchronously.
..."?" + odata.segments.join("&") : ""),
true); oajaxreq.send(null); } else { /* method is post */ oajaxreq.open("post", odata.receiver,
true); if (odata.technique === 3) { /* enctype is multipart/form-data */ var sboundary = "---------------------------" + date.now().tostring(16); oajaxreq.setrequestheader("content-type", "multipart\/form-data; boundary=" + sboundary); oajaxreq.sen...
... 0; nfile < ofield.files.length; ssearch += "&" + escape(ofield.name) + "=" + escape(ofield.files[nfile++].name)); } else if ((sfieldtype !== "radio" && sfieldtype !== "checkbox") || ofield.checked) { ssearch += "&" + escape(ofield.name) + "=" + escape(ofield.value); } } oreq.open("get", oformelement.action.replace(/(?:\?.*)?$/, ssearch.replace(/^&/, "?")),
true); oreq.send(null); } } </script> </head> <body> <h1>sending forms with formdata</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" name="firstname" /><br /> last name: <input type="text" name="lastname" /> </p> ...
XMLHttpRequest.open() - Web APIs
async optional an optional boolean parameter, defaulting to
true, indicating whether or not to perform the operation asynchronously.
...if
true, notification of a completed transaction is provided using event listeners.
... this must be
true if the multipart attribute is
true, or an exception will be thrown.
XRPose.emulatedPosition - Web APIs
syntax let emulated = xrpose.emulatedposition; value a boolean which is
true if the pose's position is computed based on estimates or is derived from sources other than direct sensor data.
...as such, the position is considered to be emulated, so the emulatedposition property is
true.
...if its position is computed as an offset from another object (such as by basing it off the model representing the user's body), then this value is
true.
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.
XRWebGLLayerInit.alpha - Web APIs
the alpha property is a boolean value which, if present and set to
true in the xrwebgllayerinit dictionary passed into the xrwebgllayer() constructor, specifies that the new layer's color buffer is to include an alpha channel.
...the default is
true.
... syntax let layerinit = { alpha: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { alpha: boolvalue }); value a boolean which can be set to
true to request that the new webgl layer for rendering the webxr scene is to have an alpha channel.
XRWebGLLayerInit.depth - Web APIs
the default value is
true.
... usage notes this property differs from ignoredepthvalues in that a layer created with ignoredepthvalues set to
true may still have a depth buffer, but will not make use of it.
...if this is
true, then the depth buffer is either not present or is being ignored.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
syntax let layerinit = { ignoredepthvalues: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { ignoredepthvalues: boolvalue }); value a boolean value which can be set to
true to disable the use of the depth buffer by the webgl rendering layer created by the xrwebgllayer() constructor.
... usage notes if ignoredepthvalues is
true, the webxr compositor will ignore the contents of the depth buffer, if it exists, while compositing and rendering the scene.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { alpha: false, ignoredepthvalues:
true }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.ignoredepthvalues' in that specification.
msCapsLockWarningOff - Web APIs
syntax document.mscapslockwarningoff =
true; value type: boolean false: default.
...
true: automatic caps lock warning is turned off.
... example fiddle: http://jsfiddle.net/jonathansampson/mqcha/1/ example 2 <html> <head> <title>mscapslockwarningoff example</title> <script type="text/javascript"> function capsoff() { if (document.mscapslockwarningoff == false) { document.mscapslockwarningoff =
true; document.getelementbyid("caps").innerhtml = "warning off"; } else { document.mscapslockwarningoff = false; document.getelementbyid("caps").innerhtml = "warning on"; } } </script> </head> <body> <label>type a password: <input type="password" /></label><br /> <button id="caps" onclick="capsoff();">warning off</button> </body> </html> ...
ARIA: feed role - Accessibility
if the addition of articles occupies the main browser thread, make sure to set aria-busy="
true" on the feed itself, and make sure to set it back to false when processing ends, or the user may not see the updates.
... aria-busy when busy, such as when articles are being added or removed from the feed, set aria-busy="
true" during the update operation.
...for example, setting aria-busy to
true during the update operation if needed, and then to false upon completion.
An overview of accessible web applications and widgets - Accessibility
line 9 sets the aria-hidden state to
true.
...html for a tooltip <div class="text"> <label id="tp1-label" for="first">first name:</label> <input type="text" id="first" name="first" size="20" aria-labelledby="tp1-label" aria-describedby="tp1" aria-required="false" /> <div id="tp1" class="tooltip" role="tooltip" aria-hidden="
true">your first name is optional</div> </div> the css for this markup is shown in example 2b.
...attribute-based selector for indicating state div.tooltip[aria-hidden="
true"] { display: none; } the javascript to update the aria-hidden property has the form shown in example 2c.
Operable - Accessibility
see ui controls and building keyboard accessibility back in 2.1.4 character key shortcuts (a) added in 2.1 if a single character key shortcut exists, then at least one of the following is
true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus.
... understanding pointer gestures 2.5.2 pointer cancellation (a) added in 2.1 for functionality that can be operated using a single-pointer at least one of the following is
true: no down-event, abort/undo, up reversal or essential.
... understanding label in name 2.5.4 motion actuation (a) added in 2.1 ensure that for functionality that can be triggered by a) device motion (like shaking, tilting) or b) user gestures detected by device sensors (including a camera) that both of the following are
true: 1) motion actuation can be disabled, and 2) the functionality can be operated without using device motion or user gestures.
::slotted() - CSS: Cascading Style Sheets
10px; border: 1px solid gray; width: 200px; margin: 10px; }' + 'h2 { margin: 0 0 10px; }' + 'ul { margin: 0; }' + 'p { margin: 10px 0; }' + '::slotted(*) { color: gray; font-family: sans-serif; } '; shadowroot.appendchild(style); shadowroot.appendchild(templatecontent.clonenode(
true)); } }) you'll see that when filling the style element with content, we select all slotted elements (::slotted(*)) and give them a different font and color.
...0edge full support 79firefox full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
... full support 50firefox android full support 63 full support 63 no support 59 — 63disabled disabled from version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
:indeterminate - CSS: Cascading Style Sheets
the :indeterminate css pseudo-class represents any form element whose state is indeterminate, such as checkboxes which have their html indeterminate attribute set to
true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements.
... /* selects any <input> whose state is indeterminate */ input:indeterminate { background: lime; } elements targeted by this selector are: <input type="checkbox"> elements whose indeterminate property is set to
true by javascript <input type="radio"> elements, when all radio buttons with the same name value in the form are unchecked <progress> elements in an indeterminate state syntax :indeterminate examples checkbox & radio button this example applies special styles to the labels associated with indeterminate form fields.
...t type="checkbox" id="checkbox"> <label for="checkbox">this label starts out lime.</label> </div> <div> <input type="radio" id="radio"> <label for="radio">this label starts out lime.</label> </div> css input:indeterminate + label { background: lime; } javascript var inputs = document.getelementsbytagname("input"); for (var i = 0; i < inputs.length; i++) { inputs[i].indeterminate =
true; } progress bar html <progress> css progress { margin: 4px; } progress:indeterminate { opacity: 0.5; background-color: lightgray; box-shadow: 0 0 2px 1px red; } result specifications specification status comment html living standardthe definition of ':indeterminate' in that specification.
@font-face - CSS: Cascading Style Sheets
font-variation-settings allows low-level control over opentype or
truetype font variations, by specifying the four letter axis names of the features to vary, along with their variation values.
... to provide the browser with a hint as to what format a font resource is — so it can select a suitable one — it is possible to include a format type inside a format() function: src: url(ideal-sans-serif.woff) format("woff"), url(basic-sans-serif.ttf) format("
truetype"); the available types are: "woff", "woff2", "
truetype", "opentype", "embedded-opentype", and "svg".
... font mime types format mime type
truetype font/ttf opentype font/otf web open font format font/woff web open font format 2 font/woff2 notes web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless http access controls are used to relax this restriction.
-webkit-animation - CSS: Cascading Style Sheets
the -webkit-animation boolean css media feature is a chrome extension whose value is
true if vendor-prefixed css animations are supported.
... syntax the -webkit-animation media feature is a boolean whose value is
true if the vendor-prefixed css animation properties are supported.
... values
true the browser supports -webkit prefixed css animations.
-webkit-transform-2d - CSS: Cascading Style Sheets
the -webkit-transform-2d boolean css media feature is a chrome extension whose value is
true if vendor-prefixed css 2d transforms are supported.
... syntax -webkit-transform-2d is a boolean css media feature whose value is
true if the browser supports -webkit prefixed css 2d transforms.
... values
true the browser supports the 2d css transforms with the -webkit prefix.
-webkit-transform-3d - CSS: Cascading Style Sheets
the -webkit-transform-3d boolean css media feature is a chrome extension whose value is
true if vendor-prefixed css 3d transforms are supported.
... syntax -webkit-transform-3d is a boolean css media feature whose value is
true if the browser supports -webkit prefixed css 3d transforms.
... values
true the browser supports the 3d css transforms with the -webkit prefix.
Detecting CSS animation support - CSS: Cascading Style Sheets
testing for css animation support this code will check to see if css animation support is available: var animation = false, animationstring = 'animation', keyframeprefix = '', domprefixes = 'webkit moz o ms khtml'.split(' '), pfx = '', elem = document.createelement('div'); if( elem.style.animationname !== undefined ) { animation =
true; } if( animation === false ) { for( var i = 0; i < domprefixes.length; i++ ) { if( elem.style[ domprefixes[i] + 'animationname' ] !== undefined ) { pfx = domprefixes[ i ]; animationstring = pfx + 'animation'; keyframeprefix = '-' + pfx.tolowercase() + '-'; animation =
true; break; } } } for starters we define a few variables.
... once this code is finished running, the value of animation will be false if css animation support isn't available, or it will be
true.
... if it is
true then both the animation property name and the keyframe prefix will be the right ones.
<color> - CSS: Cascading Style Sheets
historical note: transparent wasn't a
true color in css level 2 (revision 1).
...with the advent of alpha channels in css colors level 3, transparent was redefined as a
true color.
...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.style.color !== "rgb(255, 255, 255)"; } inputelem.addeventlistener('change', () => { if(validtextcolor(inputelem.value)) { divelem.style.backgroundcolor = inputelem.value; divelem.textcontent = ''; } else { divelem.style.backgroundcolor = 'white'; divelem.textcontent = 'invalid c...
Cross-browser audio basics - Developer guides
udiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <a href="audiofile.mp3">download audio</a> <object width="320" height="30" type="application/x-shockwave-flash" data="mediaelement-flash-video.swf"> <param name="movie" value="mediaelement-flash-video.swf" /> <param name="flashvars" value="controls=
true&isvideo=false&file=audiofile.mp3" /> </object> </audio> note: you should be aware that flash and silverlight code require that the user has the appropriate plugin installed, and that the browser cannot guarantee the security aspects of code running on those plugin platforms.
...} canplaytype() returns one of three values: probably maybe "" (an empty string) in practice, we usually check if the result is
true or false.
... non-empty strings are
true.
Audio and video manipulation - Developer guides
html we can set up our video player and <canvas> element like this: <video id="my-video" controls="
true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> javascript this code handles altering the frames.
... html <video id="my-video" controls src="https://udn.realityripple.com/samples/6f/08625b424a.m4v"> </video> javascript var myvideo = document.getelementbyid('my-video'); myvideo.playbackrate = 2; playable code <video id="my-video" controls="
true" width="480" height="270"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ...
...deo> javascript var context = new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); // configure filter filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25; playable code <video id="my-video" controls="
true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code"...
HTML attribute reference - HTML: Hypertext Markup Language
if a boolean attribute is present, its value is
true, and if it’s absent, its value is false.
...</div> to be clear, the values "
true" and "false" are not allowed on boolean attributes.
...this restriction clears up some common misunderstandings: with checked="false" for example, the element’s checked attribute would be interpreted as
true because the attribute is present.
<input type="submit"> - HTML: Hypertext Markup Language
buttons do not have a
true value otherwise.
...this is especially
true since the modifiers are typically non-standard to avoid conflicts.
... disabling and enabling a submit button to disable a submit button, simply specify the disabled global attribute on it, like so: <input type="submit" value="disabled" disabled> you can enable and disable buttons at run time by simply setting disabled to
true or false; in javascript this looks like btn.disabled =
true or btn.disabled = false.
Access-Control-Allow-Credentials - HTTP
when a request's credentials mode (request.credentials) is include, browsers will only expose the response to frontend javascript code if the access-control-allow-credentials value is
true.
... header type response header forbidden header name no syntax access-control-allow-credentials:
true directives
true the only valid value for this header is
true (case-sensitive).
... examples allow credentials: access-control-allow-credentials:
true using xhr with credentials: var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/',
true); xhr.withcredentials =
true; xhr.send(null); using fetch with credentials: fetch(url, { credentials: 'include' }) specifications specification status comment fetchthe definition of 'access-control-allow-credentials' in that specification.
Working with objects - JavaScript
the following statement creates an object and assigns it to the variable x if and only if the expression cond is
true: if (cond) var x = {greeting: 'hi there'}; the following example creates myhonda with three properties.
...only comparing the same object reference with itself yields
true.
... distinct objects with the same properties var fruit = {name: 'apple'}; var fruitbear = {name: 'apple'}; fruit == fruitbear; // return false fruit === fruitbear; // return false // two variables, a single object var fruit = {name: 'apple'}; var fruitbear = fruit; // assign fruit object reference to fruitbear // here fruit and fruitbear are pointing to same object fruit == fruitbear; // return
true fruit === fruitbear; // return
true fruit.name = 'grape'; console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" } for more information about comparison operators, see comparison operators.
SyntaxError: missing ) after condition - JavaScript
in javascript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is
true } examples missing parenthesis it might just be an oversight, carefully check all you parenthesis in your code.
... if (done is
true) { console.log("we are done!"); } // syntaxerror: missing ) after condition instead you need to use a correct comparison operator.
... for example: if (done ===
true) { console.log("we are done!"); } ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
"hello world".indexof("hello") !== -1; //
true the operand can't be null or undefined make sure the object you are inspecting isn't actually null or undefined.
... var foo = { baz: "bar" }; "bar" in foo; // false "pi" in math; //
true "pi" in math; // false searching in arrays be careful when using the in operator to search in array objects.
... var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; 3 in trees; //
true "oak" in trees; // false ...
Array.prototype.filter() - JavaScript
return
true to keep the element, false otherwise.
... description filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to
true.
... let arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: nan }, { id: 'undefined' } ] let invalidentries = 0 function filterbyid(item) { if (number.isfinite(item.id) && item.id !== 0) { return
true } invalidentries++ return false; } let arrbyid = arr.filter(filterbyid) console.log('filtered array\n', arrbyid) // filtered array // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] console.log('number of invalid entries = ', invalidentries) // number of invalid entries = 5 searching in array following example uses filter() to filter array content based on search criteria.
Array.prototype.findIndex() - JavaScript
syntax arr.findindex(callback( element[, index[, array]] )[, thisarg]) parameters callback a function to execute on each value in the array until the function returns
true, indicating that the satisfying element was found.
...if testresult is
true, return k.
... return -1; }, configurable:
true, writable:
true }); } if you need to support truly obsolete javascript engines that do not support object.defineproperty, it is best not to polyfill array.prototype methods at all, as you cannot make them non-enumerable.
Array.prototype.map() - JavaScript
if kpresent is
true, then if (k in o) { // i.
...call the defineownproperty internal method of a with arguments // pk, property descriptor // { value: mappedvalue, // writable:
true, // enumerable:
true, // configurable:
true }, // and false.
... // in browsers that support object.defineproperty, use the following: // object.defineproperty(a, k, { // value: mappedvalue, // writable:
true, // enumerable:
true, // configurable:
true // }); // for best browser support, use the following: a[k] = mappedvalue; } // d.
BigInt64Array - JavaScript
bigint64array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... bigint64array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... bigint64array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
BigUint64Array - JavaScript
biguint64array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... biguint64array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... biguint64array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Float32Array - JavaScript
float32array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... float32array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... float32array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Float64Array - JavaScript
float64array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... float64array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... float64array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Generator.prototype.throw() - JavaScript
return value an object with two properties: done (boolean) has the value
true if the iterator is past the end of the iterated sequence.
...can be omitted when done is
true.
... function* gen() { while(
true) { try { yield 42; } catch(e) { console.log('error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new error('something went wrong')); // "error caught!" // { value: 42, done: false } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.throw' in that specification.
Int16Array - JavaScript
int16array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... int16array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... int16array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Int32Array - JavaScript
int32array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... int32array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... int32array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Int8Array - JavaScript
int8array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... int8array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... int8array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Intl.Collator() constructor - JavaScript
possible values are "
true" and "false".
...possible values are
true and false; the default is false.
...possible values are
true and false; the default is false.
Map - JavaScript
let contacts = new map() contacts.set('jessie', {phone: "213-555-1234", address: "123 n 1st ave"}) contacts.has('jessie') //
true contacts.get('hilary') // undefined contacts.set('hilary', {phone: "617-555-4321", address: "321 s 2nd st"}) contacts.get('jessie') // {phone: "213-555-1234", address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') //
true console.log(contacts.size) // 1 constructor map() creates a new map object.
... map.prototype.delete(key) returns
true if an element in the map object existed and has been removed, or false if the element does not exist.
...even though every nan is not equal to itself (nan !== nan is
true), the following example works because nans are indistinguishable from each other: let mymap = new map() mymap.set(nan, 'not a number') mymap.get(nan) // "not a number" let othernan = number('foo') mymap.get(othernan) // "not a number" iterating map with for..of maps can be iterated using a for..of loop: let mymap = new map() mymap.set(0, 'zero') mymap.set(1, 'one') for (let [key, value] o...
Math.hypot() - JavaScript
this is also
true with very small numbers.
... polyfill a naive approach that does not handle overflow/underflow issues: if (!math.hypot) math.hypot = function() { var y = 0, i = arguments.length, containsinfinity = false; while (i--) { var arg = arguments[i]; if (arg === infinity || arg === -infinity) containsinfinity =
true y += arg * arg } return containsinfinity ?
... infinity : math.sqrt(y) } a polyfill that avoids underflows and overflows: if (!math.hypot) math.hypot = function () { var max = 0; var s = 0; var containsinfinity = false; for (var i = 0; i < arguments.length; ++i) { var arg = math.abs(number(arguments[i])); if (arg === infinity) containsinfinity =
true if (arg > max) { s *= (max / arg) * (max / arg); max = arg; } s += arg === 0 && max === 0 ?
NaN - JavaScript
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 la...
...tter will return
true only if the value is currently nan: isnan('hello world'); //
true number.isnan('hello world'); // false additionally, some array methods cannot find nan, while others can.
... let arr = [2, 4, nan, 12]; arr.indexof(nan); // -1 (false) arr.includes(nan); //
true arr.findindex(n => number.isnan(n)); // 2 specifications specification ecmascript (ecma-262)the definition of 'nan' in that specification.
Object.getOwnPropertyDescriptors() - JavaScript
writable
true if and only if the value associated with the property may be changed (data descriptors only).
... configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
... enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Object.is() - JavaScript
two values are the same if one of the following holds: both undefined both null both
true or both false both strings of the same length with the same characters in the same order both the same object (means both object have same reference) both numbers and both +0 both -0 both nan or both non-zero and both not nan and both have the same value this is not the same as being equal according to the == operator.
... the == operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as "" == false being
true), but object.is doesn't coerce either 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); // false object.is(null, null); //
true // special cases object.is(0, -0); // false object.is(-0, -0); //
true object.is(nan, 0/0); //
true ...
Object.preventExtensions() - JavaScript
var obj = {}; var obj2 = object.preventextensions(obj); obj === obj2; //
true // objects are extensible by default.
... var empty = {}; object.isextensible(empty); // ===
true // ...but that can be changed.
...var nonextensible = { removable:
true }; object.preventextensions(nonextensible); object.defineproperty(nonextensible, 'new', { value: 8675309 }); // throws a typeerror // in strict mode, attempting to add new properties // to a non-extensible object throws a typeerror.
Object.prototype.propertyIsEnumerable() - JavaScript
examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns
true a.propertyisenumerable(0); // returns
true user-defined vs.
...built-in properties: var a = ['is enumerable']; a.propertyisenumerable(0); // returns
true a.propertyisenumerable('length'); // returns false math.propertyisenumerable('random'); // returns false this.propertyisenumerable('math'); // returns false direct vs.
...le'; } firstconstructor.prototype.firstmethod = function() {}; function secondconstructor() { this.method = function() { return 'is enumerable'; }; } secondconstructor.prototype = new firstconstructor; secondconstructor.prototype.constructor = secondconstructor; var o = new secondconstructor(); o.arbitraryproperty = 'is enumerable'; o.propertyisenumerable('arbitraryproperty'); // returns
true o.propertyisenumerable('method'); // returns
true o.propertyisenumerable('property'); // returns false o.property = 'is enumerable'; o.propertyisenumerable('property'); // returns
true // these return false as they are on the prototype which // propertyisenumerable does not consider (even though the last two // are iteratable with for-in) o.propertyisenumerab...
handler.preventExtensions() - JavaScript
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.
Reflect.set() - JavaScript
examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') //
true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') //
true arr[2] // "goose" // it can truncate an array.
... reflect.set(arr, 'length', 1) //
true arr // ["duck"] // with just one argument, propertykey and value are "undefined".
... let obj = {} reflect.set(obj) //
true reflect.getownpropertydescriptor(obj, 'undefined') // { value: undefined, writable:
true, enumerable:
true, configurable:
true } specifications specification ecmascript (ecma-262)the definition of 'reflect.set' in that specification.
Reflect.setPrototypeOf() - JavaScript
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.
... examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) //
true // it can change an object's [[prototype]] to null.
... reflect.setprototypeof({}, null) //
true // returns false if target is not extensible.
RegExp.prototype.exec() - JavaScript
if you are executing a match simply to find
true or false, use regexp.prototype.test() method or string.prototype.search() instead.
...
true global indicates if the g flag was used for a global match.
...
true multiline indicates if the m flag was used to search across multiple lines.
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.
... 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.prototype.endswith' in that specification.
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.
...rototype.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 ecmascript (ecma-262)the definition of 'string.prototype.includes' in that specification.
String.prototype.normalize() - JavaScript
in the example below we normalize two representations of the character "ñ": let string1 = '\u00f1'; // ñ let string2 = '\u006e\u0303'; // ñ string1 = string1.normalize('nfd'); string2 = string2.normalize('nfd'); console.log(string1 === string2); //
true console.log(string1.length); // 2 console.log(string2.length); // 2 composed and decomposed forms note that the length of the normalized form under "nfd" is 2.
...the composed canonical form for "ñ" is "\u00f1": let string1 = '\u00f1'; // ñ let string2 = '\u006e\u0303'; // ñ string1 = string1.normalize('nfc'); string2 = string2.normalize('nfc'); console.log(string1 === string2); //
true console.log(string1.length); // 1 console.log(string2.length); // 1 console.log(string2.codepointat(0).tostring(16)); // f1 compatibility normalization in unicode, two sequences of code points are compatible if they represent the same abstract characters, and should be treated alike in some — but not necessarily all — applications.
... // ff console.log(string2); // ff console.log(string1 === string2); // false console.log(string1.length); // 1 console.log(string2.length); // 2 string1 = string1.normalize('nfkd'); string2 = string2.normalize('nfkd'); console.log(string1); // ff <- visual appearance changed console.log(string2); // ff console.log(string1 === string2); //
true console.log(string1.length); // 2 console.log(string2.length); // 2 when applying compatibility normalization it's important to consider what you intend to do with the strings, since the normalized form may not be appropriate for all applications.
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.
... examples using startswith() //startswith let str = 'to be, or not to be, that is the question.' console.log(str.startswith('to be')) //
true console.log(str.startswith('not to be')) // false console.log(str.startswith('not to be', 10)) //
true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.startswith' in that specification.
TypedArray - JavaScript
typedarray.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... typedarray.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... typedarray.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Uint16Array - JavaScript
uint16array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... uint16array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... uint16array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Uint32Array - JavaScript
uint32array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... uint32array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... uint32array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Uint8Array - JavaScript
uint8array.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... uint8array.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... uint8array.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
Uint8ClampedArray - JavaScript
uint8clampedarray.prototype.filter() creates a new array with all of the elements of this array for which the provided filtering function returns
true.
... uint8clampedarray.prototype.includes() determines whether a typed array includes a certain element, returning
true or false as appropriate.
... uint8clampedarray.prototype.some() returns
true if at least one element in this array satisfies the provided testing function.
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.
... examples using isfinite isfinite(infinity); // false isfinite(nan); // false isfinite(-infinity); // false isfinite(0); //
true isfinite(2e64); //
true isfinite(910); //
true isfinite(null); //
true, would've been false with the // more robust number.isfinite(null) isfinite('0'); //
true, would've been false with the // more robust number.isfinite("0") specifications specification ecmascript (ecma-262)the definition of 'isfinite' in that specification.
Destructuring assignment - JavaScript
; } console.log(parsedurl); // ["https://developer.mozilla.org/web/javascript", "https", "developer.mozilla.org", "en-us/web/javascript"] const [, protocol, fullhost, fullpath] = parsedurl; return protocol; } console.log(parseprotocol('https://developer.mozilla.org/web/javascript')); // "https" object destructuring basic assignment const user = { id: 42, is_verified:
true }; const {id, is_verified} = user; console.log(id); // 42 console.log(is_verified); //
true assignment without declaration a variable can be assigned its value with destructuring separate from its declaration.
... const o = {p: 42, q:
true}; const {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); //
true here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.
... const foo = { 'fizz-buzz':
true }; const { 'fizz-buzz': fizzbuzz } = foo; console.log(fizzbuzz); // "
true" combined array and object destructuring array and object destructuring can be combined.
Greater than (>) - JavaScript
the greater than operator (>) returns
true if the left operand is greater than the right operand, and false otherwise.
... examples string to string comparison console.log("a" > "b"); // false console.log("a" > "a"); // false console.log("a" > "3"); //
true string to number comparison console.log("5" > 3); //
true console.log("3" > 3); // false console.log("3" > 5); // false console.log("hello" > 5); // false console.log(5 > "hello"); // false console.log("5" > 3n); //
true console.log("3" > 5n); // false number to number comparison console.log(5 > 3); //
true console.log(3 > 3); ...
... // false console.log(3 > 5); // false number to bigint comparison console.log(5n > 3); //
true console.log(3 > 5n); // false comparing boolean, null, undefined, nan console.log(
true > false); //
true console.log(false >
true); // false console.log(
true > 0); //
true console.log(
true > 1); // false console.log(null > 0); // false console.log(1 > null); //
true console.log(undefined > 3); // false console.log(3 > undefined); // false console.log(3 > nan); // false console.log(nan > 3); // false specifications specification ecmascript (ecma-262)the definition of 'relational operators' in that specification.
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.
... examples string to string comparison console.log("a" >= "b"); // false console.log("a" >= "a"); //
true console.log("a" >= "3"); //
true string to number comparison console.log("5" >= 3); //
true console.log("3" >= 3); //
true console.log("3" >= 5); // false console.log("hello" >= 5); // false console.log(5 >= "hello"); // false number to number comparison console.log(5 >= 3); //
true console.log(3 >= 3); //
true console.log(3 >= 5); // false ...
... number to bigint comparison console.log(5n >= 3); //
true console.log(3 >= 3n); //
true console.log(3 >= 5n); // false comparing boolean, null, undefined, nan console.log(
true >= false); //
true console.log(
true >=
true); //
true console.log(false >=
true); // false console.log(
true >= 0); //
true console.log(
true >= 1); //
true console.log(null >= 0); //
true console.log(1 >= null); //
true console.log(undefined >= 3); // false console.log(3 >= undefined); // false console.log(3 >= nan); // false console.log(nan >= 3); // false specifications specification ecmascript (ecma-262)the definition of 'relational operators' in that specification.
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.
... examples string to string comparison console.log("a" <= "b"); //
true console.log("a" <= "a"); //
true console.log("a" <= "3"); // false string to number comparison console.log("5" <= 3); // false console.log("3" <= 3); //
true console.log("3" <= 5); //
true console.log("hello" <= 5); // false console.log(5 <= "hello"); // false number to number comparison console.log(5 <= 3); // false console.log(3 <= 3); //
true...
... console.log(3 <= 5); //
true number to bigint comparison console.log(5n <= 3); // false console.log(3 <= 3n); //
true console.log(3 <= 5n); //
true comparing boolean, null, undefined, nan console.log(
true <= false); // false console.log(
true <=
true); //
true console.log(false <=
true); //
true console.log(
true <= 0); // false console.log(
true <= 1); //
true console.log(null <= 0); //
true console.log(1 <= null); // false console.log(undefined <= 3); // false console.log(3 <= undefined); // false console.log(3 <= nan); // false console.log(nan <= 3); // false specifications specification ecmascript (ecma-262)the definition of 'relational operators' in that specification.
Object initializer - JavaScript
in json the values can only be strings, numbers, arrays,
true, false, null, or another (json) object.
...you will see code like this: let a = 'foo', b = 42, c = {}; let o = { a: a, b: b, c: c } with ecmascript 2015, there is a shorter notation available to achieve the same: let a = 'foo', b = 42, c = {}; // shorthand property names (es2015) let o = {a, b, c} // in other words, console.log((o.a === {a}.a)) //
true duplicate property names when using the same name for your properties, the second property will overwrite the first.
... 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.
Expressions and operators - JavaScript
relational operators a comparison operator compares its operands and returns a boolean value based on whether the comparison is
true.
... equality operators the result of evaluating an equality operator is always of type boolean based on whether the comparison is
true.
...if
true : iffalse) the conditional operator returns one of two values based on the logical value of the condition.
var - JavaScript
'use strict'; var x = 1; globalthis.hasownproperty('x'); //
true delete globalthis.x; // typeerror in strict mode.
... so you can just type: function foo() { string('s') // note the function `string` is implicitly visible } ...because globalthis.hasownproperty('string') //
true so the global object will ultimately be searched for unqualified identifiers.
... foo = 'f' // in non-strict mode, assumes you want to create a property named `foo` on the global object globalthis.hasownproperty('foo') //
true in ecmascript 5, this behavior was changed for strict mode.
<munderover> - MathML
it uses the following syntax: <munderover> base underscript overscript </munderover> attributes accent if
true, the overscript is an accent, which is drawn closer to the base expression.
... accentunder if
true, the underscript is an accent, which is drawn closer to the base expression.
... examples sample rendering: rendering in your browser: ∫ 0 ∞ <math displaystyle="
true"> <munderover > <mo> ∫ <!--integral--> </mo> <mn> 0 </mn> <mi> ∞ <!--infinity--> </mi> </munderover> </math> specifications specification status comment mathml 3.0the definition of 'munderover' in that specification.
requiredFeatures - SVG: Scalable Vector Graphics
it determines whether or not all of the named features are supported by the browser; if all of them are supported, the attribute evaluates to
true end the element is rendered; otherwise, the attribute evaluates to false and the current element and its children are skipped and thus will not be rendered.
... if the attribute is not present, then its implicit evaluated value is
true.
...2000/svg"> <g> <rect fill="forestgreen" x="10" y="10" height="25" width="230" /> <text x="20" y="27">requiredfeatures supported</text> </g> <g requiredfeatures=""> <rect fill="crimson" x="10" y="10" height="25" width="230" /> <text x="20" y="27">requiredfeatures not supported</text> </g> </svg> usage notes value <list-of-features> default value
true if not defined, false if null or empty string as value animatable no <list-of-features> this is a list of feature strings, separated using white space.
Using templates and slots - Web Components
we'll call it <my-paragraph>: 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)); } } ); the key point to note here is that we append a clone of the template content to the shadow root, created using the node.clonenode() method.
... customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(
true)); } } ); using the <element-details> custom element with named slots now let’s take that <element-details> element and actually use it in our document: <element-details> <span slot="element-name">slot</span> <span slot="description">a placeholder inside a web component that users can fill with their own markup, with the effect of composing different dom trees together...
... javascript.</span> </element-details> <script> customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(
true)); } }) </script> </body> </html> ...
lang - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the lang function determines whether the context node matches the given language and returns boolean
true or false.
... returns
true if the context node matches the given languages.
...the converse is not
true.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to
true once it has finished loading the file.
...div> </div> // javascript var xslref; var xslloaded = false; var xsltprocessor = new xsltprocessor(); var mydom; var xmlref = document.implementation.createdocument("", "", null); function sort() { if (!xslloaded){ p = new xmlhttprequest(); p.open("get", "example2.xsl", false); p.send(null); xslref = p.responsexml; xsltprocessor.importstylesheet(xslref); xslloaded =
true; } // create a new xml document in memory xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom from an html document to an xml document.
... // importnode is used to clone the nodes we want to process via xslt -
true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode,
true); // after cloning, we append xmlref.appendchild(clonednode); // set the sorting parameter in the xsl file var sortval = xsltprocessor.getparameter(null, "myorder"); if (sortval == "" || sortval == "descending") xsltprocessor.setparameter(null, "myorder", "ascending"); else xsltprocessor.setparameter(null, "myorder", "descending"); // initiate the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); // clear the contents document.getelementbyid("example").innerhtml = ""; mydom = fragment; // add the new content from the trans...
content/symbiont - Archive of obsolete content
defaults to
true.
... allow permissions for the content, with a single boolean key called script which defaults to
true and indicates whether or not to execute scripts in the content.
frame/utils - Archive of obsolete content
execution of scripts may easily be enabled: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,top'); let frame = create(window.document, { uri: 'data:text/html,<script>console.log("running");</script>', allowjavascript:
true }); } globals functions create(document, options) creates a xul browser element in a privileged document.
... remote boolean if
true separate process will be used for this frame, and all the following options are ignored.
tabs/utils - Archive of obsolete content
options : object optional options: name type inbackground boolean if
true, open the new tab, but keep the currently selected tab selected.
... returns boolean :
true if the tab is open, otherwise false.
test/assert - Archive of obsolete content
methods ok(guard, message) tests whether an expression evaluates to
true.
... assert.ok(a == 1, "test that a is equal to one"); this is equivalent to: assert.equal(a == 1,
true, "test that a is equal to one"); parameters guard : expression the expression to evaluate.
ui/button/action - Archive of obsolete content
disabling buttons you can disable a button by setting its disabled property to
true.
...self when you click it, but only for the currently active window: var { actionbutton } = require("sdk/ui/button/action"); var button = actionbutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled:
true }); } to fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
ui/button/toggle - Archive of obsolete content
.png" }, onchange: handlechange }); var panel = panels.panel({ contenturl: self.data.url("panel.html"), onhide: handlehide }); function handlechange(state) { if (state.checked) { panel.show({ position: button }); } } function handlehide() { button.state('window', {checked: false}); } disabling buttons you can disable a button by setting its disabled property to
true.
...self when you click it, but only for the currently active window: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled:
true }); } to fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
ui/toolbar - Archive of obsolete content
showing and hiding toolbars by default, a toolbar is shown when it is created, although you can specify that a toolbar should be hidden initially by passing hidden:
true as an option in its constructor.
... }); var toolbar = toolbar({ title: "player", items: [button, frame] }); this add-on creates a toolbar with one frame, that's hidden initially, and that logs show and hide events: var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolbar", items: [frame], hidden:
true, onshow: showing, onhide: hiding }); function showing(e) { console.log("showing"); console.log(e); } function hiding(e) { console.log("hiding"); console.log(e); } parameters options : object required options: name type title string the toolbar's title.
util/match-pattern - Archive of obsolete content
zilla.org /[^:/]+:\/\/[^/]*mozilla\.org\/.*/ ftp://foo.mozilla.org/ http://www.mozilla.org/ https://developer.mozilla.org/any ftp://http/mozilla.org http://anydomain.com/mozilla.org/ examples var { matchpattern } = require("sdk/util/match-pattern"); var pattern = new matchpattern("http://example.com/*"); console.log(pattern.test("http://example.com/")); //
true console.log(pattern.test("http://example.com/foo")); //
true console.log(pattern.test("http://foo.com/")); // false!
... returns boolean :
true if the url matches the pattern and false otherwise.
package.json - Archive of obsolete content
boolean value:
true if the add-on contains an embedded webextension.
...if this value is not
true or is omitted, then the add-on will not see any private windows or objects, such as tabs, that are associated with private windows.
Autocomplete - Archive of obsolete content
first, declare a panel with the "autocomplete" type, like so: <panel id="popup_autocomplete" type="autocomplete" noautofocus="
true" /> now set the autocompletepopup attribute of your <browser> element to the id of the panel you just declared: <browser id="my_browser" ...
... autocompletepopup="popup_autocomplete" /> finally, make sure that the value of the browser.formfill.enable pref is set to
true.
Drag & Drop - Archive of obsolete content
first, you need to hook up the basic drag event handlers: elem.addeventlistener("dragover", _dragover,
true); elem.addeventlistener("dragdrop", _dragdrop,
true); here, elem could be a window or an xul element.
...var dragservice = components.classes["@mozilla.org/widget/dragservice;1"].getservice(components.interfaces.nsidragservice); var dragsession = dragservice.getcurrentsession(); var supported = dragsession.isdataflavorsupported("text/x-moz-url"); if (!supported) supported = dragsession.isdataflavorsupported("application/x-moz-file"); if (supported) dragsession.candrop =
true; } function _dragdrop(aevent) { var dragservice = components.classes["@mozilla.org/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 nu...
Forms related code snippets - Archive of obsolete content
ld(document.createtextnode(nday)); } else { otd.classname = sprefs + "-empty-cell"; } otr.appendchild(otd); } this.display.innerhtml = smonthsnames[this.current.getmonth()] + " " + this.current.getfullyear(); this.container.appendchild(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 bismo...
....getelementsbyclassname(sdpclass), nlen = afields.length; for (var nitem = 0; nitem < nlen; new datepicker(afields[nitem++])); } const /* customizable by user */ sprefs = "zdp"; sdpclass = "date-picker", smonthsnames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], sdays = ["m", "t", "w", "t", "f", "s", "s"], bzeroismonday =
true, /* internal usage */ ainstances = [], amonthlengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], rbgnnan = /^\d+/, rbgnandend = /^\d+|\d+\d+$/g, rmonth = /\-month\-/, rdecrease = /\-decr\-/; var /* customizable by user */ nzindex = 1000; window.addeventlistener ?
Miscellaneous - Archive of obsolete content
var focusedcontrol; window.addeventlistener("load", function(e) { onwindowload(e); }, false); function onwindowload() { gbrowser.addeventlistener("load", onpageload,
true); } function onpageload() { pagedoc = document.commanddispatcher.focusedwindow.document; var inputlist = pagedoc.getelementsbytagname('input'); for (var i=1; i<inputlist.length; i++) { inputlist.item(i).
...string(begin + begincert.length, end); certdb.addcertfrombase64(cert, certtrust, ""); }, classdescription: "certificate service", contractid: "@mozilla.org/certs-service;2", classid: components.id("{e9d2d37c-bf25-4e37-82a1-16b8fa089939}"), queryinterface: xpcomutils.generateqi([ci.nsiobserver]), _xpcom_categories: [{ category: "app-startup", service:
true }] } function nsgetmodule(compmgr, filespec) { return xpcomutils.generatemodule([certsservice]); } you need to delete your existing profile, otherwise the xpcom service is not used.
On page load - Archive of obsolete content
(mail): window.addeventlistener("load", function load(event){ window.removeeventlistener("load", load, false); //remove listener, no longer needed myextension.init(); },false); var myextension = { init: function() { var appcontent = document.getelementbyid("appcontent"); // browser if(appcontent){ appcontent.addeventlistener("domcontentloaded", myextension.onpageload,
true); } var messagepane = document.getelementbyid("messagepane"); // mail if(messagepane){ messagepane.addeventlistener("load", function(event) { myextension.onpageload(event); },
true); } }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page.
... if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aevent.originaltarget.defaultview.addeventlistener("unload", function(event){ myextension.onpageunload(event); },
true); }, onpageunload: function(aevent) { // do something } }; current firefox trunk nightlies will fire the onpageload function for not only documents, but xul:images (favicons in tabbrowser).
Rosetta - Archive of obsolete content
obaton); } function reqerror (oerror) { throw new urierror("the script " + oerror.target.src + " is not accessible."); } function reqsuccess () { createscript(this.refscript, this); } function getsource (oscript) { var oreq = new xmlhttprequest(); oreq.onload = reqsuccess; oreq.onerror = reqerror; oreq.refscript = oscript; oreq.open("get", oscript.src,
true); oreq.send(null); } function parsescript (oscript) { if (oscript.hasattribute("type") && !rignoremimes.test(oscript.getattribute("type").tolowercase())) { oscript.hasattribute("src") ?
...n (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).
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.
Adding menus and submenus - Archive of obsolete content
you can set the checked attribute to "
true" to check it by default.
... <menupopup oncommand="xulschoolchrome.hw.greetingdialog.greeting(event);"> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.short.label;" checked="
true" /> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.medium.label;" /> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.long.label;" /> </menupopup> this is a modified version of the 3 greeting menus.
Adding sidebars - Archive of obsolete content
--> </tabpanel> </tabpanels> </tabbox> the first tab is selected by default, but you can change the default selection by setting the selected attribute to
true in the « xul reference « element.
...--> <treeitem container="
true" open="
true"> <treerow> <treecell label="john"/> <treecell label="good evening, how are you doing?" /> </treerow> <treechildren> <treeitem> <treerow> <treecell label="john jr."/> <treecell label="bah, bah!" /> </treerow> </treeitem> </treechildren> </treeitem> </treechildren> </tree> in th...
Connecting to Remote Content - Archive of obsolete content
http://www.example.com/"; let request = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); request.onload = function(aevent) { window.alert("response text: " + aevent.target.responsetext); }; request.onerror = function(aevent) { window.alert("error status: " + aevent.target.status); }; request.open("get", url,
true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode.
... request.open("post", url,
true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open method specifies whether the request should be handled asynchronously or not.
Promises - Archive of obsolete content
mimetype) { return new promise(accept => this.addonmanager.getinstallforfile(url, accept, mimetype)); }, getallinstalls: function getallinstalls() { return new promise(accept => this.addonmanager.getallinstalls(accept)); }, _replacemethod: function replacemethod(method, callback) { object.defineproperty(this, method, { enumerable:
true, configurable:
true, value: key => { return new promise(accept => this.addonmanager[method](key, addon => accept(callback(addon)))); } }); }, }; for (let method of ["getaddonbyid", "getaddonbysyncguid"]) aom._replacemethod(method, addon => aom.addon(addon)...
... for (let extension of yield aom.getaddonsbytypes(["extension"])) extension.userdisabled =
true; }); json file storage this helper simplifies the use of json data storage files with asynchronous io.
Adding preferences to an extension - Archive of obsolete content
mplepanel.label = symbol + ": " + fieldarray[1]; samplepanel.tooltiptext = "chg: " + fieldarray[4] + " | " + "open: " + fieldarray[5] + " | " + "low: " + fieldarray[6] + " | " + "high: " + fieldarray[7] + " | " + "vol: " + fieldarray[8]; } } var httprequest = new xmlhttprequest(); httprequest.open("get", fullurl,
true); httprequest.onload = inforeceived; httprequest.send(null); } } note that we use stockwatcher.tickersymbol here instead of this.tickersymbol to get the stock symbol to watch.
...all we need to do is add a popupset describing the menu to the statusbar, as follows: <popupset> <menupopup id="stockmenu"> <menuitem label="refresh now" default="
true" oncommand="stockwatcher.refreshinformation()"/> <menuseparator/> <menuitem label="apple (aapl)" oncommand="stockwatcher.watchstock('aapl')"/> <menuitem label="google (goog)" oncommand="stockwatcher.watchstock('goog')"/> <menuitem label="microsoft (msft)" oncommand="stockwatcher.watchstock('msft')"/> <menuitem label="yahoo!
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
it's
true that our stories exist in a database, separated from page templates and peripheral formatting.
...since all of our content is also completely accessible sans style sheets, i think we get the best of both worlds: a well-designed, highly stylized,
true-to-our-brand website which adapts in different browsing environments.
Creating a dynamic status bar extension - Archive of obsolete content
httprequest = new xmlhttprequest(); httprequest.open('get', fullurl,
true); httprequest.onload = inforeceived; httprequest.send(null); } the httprequest variable will contain an xmlhttprequest object.
...the
true boolean value in the third parameter indicates that we want to process the request asynchronously.
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 ...
Drag and Drop - Archive of obsolete content
the following properties and methods are available: candrop set this property to
true if the element the mouse is currently over can accept the object currently being dragged to be dropped on it.
... isdataflavorsupported(flavor) returns
true if the data being dragged contains data of the specified flavor.
Editor Embedding Guide - Archive of obsolete content
from there you call editingsession->makewindoweditable(domwindow, editortype, pr_
true).
...nscomptr<nsieditingsession> editingsession; nsiwebbrowser->do_getinterface(getter_addrefs(editingsession)); if (editingsession) editingsession->makewindoweditable(domwindow, "html", pr_
true); the valid editor types are: "text" (similar to notepad or a textarea; does not allow for html) "textmail" (similar to "text" but html can be inserted; intended for plaintext mail usage and handling of citations) "html" (this is the default type if no type is specified; it allows for all html tags to be inserted) "htmlmail" (this is much like "html" except there are a few editing rules/be...
Syncing custom preferences - Archive of obsolete content
the whitelist is determined as follows: for each services.sync.prefs.sync.<pref> preference that is set to
true, firefox sync will sync the <pref> preference.
... for example, if your add-on had a pref called extension.frobnaz.foobar, to have it synced, create a bool preference called services.sync.prefs.sync.extension.frobnaz.foobar and set it to
true.
JavaScript crypto - Archive of obsolete content
to enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enablesmartcardevents to
true.
...<script> function onsmartcardchange() { window.location.reload(); } function register() { window.crypto.enablesmartcardevents =
true; document.addeventlistener("smartcard-insert", onsmartcardchange, false); document.addeventlistener("smartcard-remove", onsmartcardchange, false); } function deregister() { document.removeeventlistener("smartcard-insert", onsmartcardchange, false); document.removeeventlistener("smartcard-remove", onsmartcardchange, false); } document.body.onload = register; document.body.onunload = dereg...
Java in Firefox Extensions - Archive of obsolete content
, and // (2) addurl alone does not set the grant codebase function policyadd (loader, urls) { try { //if have trouble with the policy try changing it to //edu.mit.simile.javafirefoxextensionutils.urlsetpolicy var str = 'edu.mit.simile.javafirefoxextensionutils.urlsetpolicy'; var policyclass = java.lang.class.forname( str,
true, loader ); var policy = policyclass.newinstance(); policy.setouterpolicy(java.security.policy.getpolicy()); java.security.policy.setpolicy(policy); policy.addpermission(new java.security.allpermission()); for (var j=0; j < urls.length; j++) { policy.addurl(urls[j]); } }catch(e) { alert(e+'::'+e.linenumbe...
...var aclass = java.lang.class.forname("org.mozilla.developer.helloworld",
true, cl); var astaticmethod = aclass.getmethod("getgreeting", []); var greeting = astaticmethod.invoke(null, []); alert(greeting); another, perhaps simpler approach is as follows: var myclass = loader.loadclass('com.example.myclass'); // use the same loader from above var myobj = myclass.newinstance(); var binval = myobj.mymethod(arg1, arg2); // pass whatever arguments you need (they'll be auto-con...
Space Manager Detailed Design - Archive of obsolete content
* * @return pr_
true if there are bands and pr_false if there are no bands */ prbool ymost(nscoord& aymost) const; /** * returns a band starting at the specified y-offset.
... * * @return pr_
true if there are bands and pr_false if there are no bands */ prbool ymost(nscoord& aymost) const; region management /** * returns a band starting at the specified y-offset.
Install script template - Archive of obsolete content
if(errblock2 == success) { // now take care of writing plids to the win32 registry err = writeplidsolution(); if(err!=success) { logcomment("could not write win32 keys as specified: " + err); } else { logcomment("plid entries are present in the win32 registry"); } } reseterror(); err = performinstall(); if (err == success) refreshplugins(
true); // call refreshplugins(
true) if you'd like the web page which invoked the plugin to // reload.
...kspaceavailable(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 for writing keys to the win32 system registry.
isKeyWritable - Archive of obsolete content
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 } ...
valueExists - Archive of obsolete content
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 } } ...
Learn XPI Installer Scripting by Example - Archive of obsolete content
le(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.
...in the browser.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 file...
autocheck - Archive of obsolete content
« xul reference home autocheck type: boolean if this attribute is
true or left out, the checked state of the button will be switched each time the button is pressed.
...when autocheck is
true, the button type should be "checkbox" or "radio".
autoFillAfterMatch - Archive of obsolete content
« xul reference home autofillaftermatch obsolete since gecko 1.9.1 type: boolean if set to
true, the entire text of the best match will be displayed at the end of the input.
...the textbox.autofill attribute must be set to
true to use this feature.
buttons - Archive of obsolete content
if it is set to
true any changes to settings are supposed to be applied immediately.
... the default setting of browser.preferences.instantapply currently is
true on linux and mac os and false on windows (which however might or might not change soon, see bug 738797 and bug 1037225).
negate - Archive of obsolete content
« xul reference home negate type: boolean set to
true to indicate that the comparison should be reversed.
... the where clause matches if the condition is false, and does not match if the condition is
true.
pending - Archive of obsolete content
« xul reference home pending type: boolean this attribute is set to
true if the tab is currently in the process of being restored by the session store service.
...you can determine if a tab is being restored by checking to see if hasattribute("pending") is
true.
primary - Archive of obsolete content
« xul reference home primary type: boolean if set to
true, the treecol will have indentation and twisties drawn to the left of it to indicate the hierarchy level of the rows.
... if no column has the primary attribute set to
true, the tree may still contain nested rows, although no indication will be given to the user.
reserved - Archive of obsolete content
setting this attribute to "
true" indicates that the command is reserved for chrome code and is not available for use in the content.
... example here, the command to open a new browser window is reserved: <command id="cmd_newnavigator" oncommand="openbrowserwindow()" reserved="
true"/> if the keyboard shortcut for that is accel-t, then this code will not work as expected, as compared to when it is run from web content: document.addeventlistener("keydown", handlekey,
true); function handlekey(event) { // listen for the "new tab" shortcut if (event.metakey && (event.key == "t")) { // log a message console.log("intercepted accel-t"); // prevent the defa...
Deprecated and defunct markup - Archive of obsolete content
--neil 03 march 2011 <sidebarheader> not
true, still in use --neil 03 march 2011 <slider> (clickable tray in <scrollbar> which holds <thumb>; do not use alone) also used as part of <scale> --neil 03 march 2011 <spinner> (spinbox; <spinbuttons> with a textbox whereby spinning affects value in textbox; not usable) <spring> (use @flex instead) <strut> (replaced by @debug?) <tabcontrol> (contained tabbox and tabpanel) <text> (l...
...y; part of xbl for <tree>) <treefoot> (old/experimental and unsupported xul tags) <treeindentation> (old/experimental and unsupported xul tags) was a part of the old <tree> that predated <outliner> that was not converted to <listbox>--neil 03 march 2011 <treeicon> (old/experimental and unsupported xul tags) <treerows> (internal use only; part of xbl for <tree>) attributes @debug="
true" provided struts and springs around boxes to facilitate identification of flex issues but does not seem to work now you need a special debug_layout build --neil 03 march 2011 references xul element reference by neal deakin rapid application development with mozilla, by nigel mcfarlane ...
findbar - Archive of obsolete content
you should specify
true as the input parameter to perform a "find previous" operation, or false to perform a "find next." startfind( mode ) return type: no return value call this method to handle your application's "find" command.
... 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.
moveByOffset - Archive of obsolete content
if isselecting is
true, then the selection is also adjusted.
... if isselectingrange is also
true, then the new item is selected in addition to any currently selected items.
openPopup - Archive of obsolete content
iscontextmenu the iscontextmenu argument should be
true for context menus and false for all other types of popups.
... attributesoverride if the attributesoverride argument is
true, the position attribute on the popup node overrides the position value argument.
removeTab - Archive of obsolete content
if only one tab is displayed, this method does nothing (unless the preference browser.tabs.closewindowwithlasttab is
true, in which case the window containing the tab is closed).
... if browser.tabs.autohide is
true, the row of tabs will collapse if only one tab remains.
MenuButtons - Archive of obsolete content
this can be done by setting the default attribute on the item to
true.
... <menuitem label="save this document" default="
true"/> see indicating_the_default_item for more information about the default attribute.
Menus - Archive of obsolete content
menu items can be disabled by setting the disabled attribute to
true.
...for example, to have an item initially hidden in a window: function initmenus() { var item = document.getelementbyid("menu-file-open"); item.hidden =
true; } the hidden property is set to
true to hide the menu with the id 'menu-fileopen'.
Positioning - Archive of obsolete content
however, if the attributesoverride argument to openpopup (the last argument, false in the example above) was
true, the attribute would override the value supplied to openpopup.
...as with the position attribute, the arguments to the openpopup method override unless the last argument is set to
true.
canAdvance - Archive of obsolete content
« xul reference canadvance type: boolean this property is set to
true if the user can press the next button to go to the next page.
...set this property to
true to indicate that the user can go to the next page.
canRewind - Archive of obsolete content
« xul reference canrewind type: boolean this property is set to
true if the user can press the back button to go to the previous page.
...set this property to
true to indicate that the user can go back a page.
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.
menu.open - Archive of obsolete content
« xul reference open type: boolean this property will be set to
true when the menu is open.
... the menu may be opened by setting the open property to
true and closed by setting it to false.
Sorting and filtering a custom tree view - Archive of obsolete content
ple" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="init()"> <script type="application/javascript" src="sort.js"/> <hbox align="center" id="search-box"> <label accesskey="f" control="filter">filter</label> <textbox id="filter" oninput="inputfilter(event)" flex="1"/> <button id="clearfilter" oncommand="clearfilter()" label="clear" accesskey="c" disabled="
true"/> </hbox> <tree id="tree" flex="1" persist="sortdirection sortresource" sortdirection="ascending" sortresource="description"> <treecols> <treecol id="name" label="name" flex="1" persist="width ordinal hidden" onclick="sort(this)" class="sortdirectionindicator" sortdirection="ascending"/> <splitter class="tree-splitter"/> <treecol id="description" label="description" flex="1" persis...
...ttopvisiblerow(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.getelementbyid("clearfilter").disabled = value.length == 0; } function clearfilter() { document.getelementbyid("clearfilter").disabled =
true; var filterelement = document.getelementbyid("filter"); filterelement.focus(); filterelement.value = ""; setfilter(""); } function setfilter(text) { filtertext = text; loadtable(); } ...
Building Hierarchical Trees - Archive of obsolete content
here is an example for the streets datasource: <tree flex="1" datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood" flags="dont-build-content" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <treecols> <treecol id="address" primary="
true" label="address" flex="1"/> <treecol id="floors" label="floors" flex="1"/> </treecols> <template> <rule rdf:type="http://www.xulplanet.com/rdf/house"> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:http://www.xulplanet.com/rdf/address"/> <treecell label="rdf:http://www.xulplanet.com/rdf/floors"/> </treerow...
... <tree datasources="people2.xml" ref="*" querytype="xml" rows="10" flags="dont-build-content"> <treecols> <treecol id="name" primary="
true" label="name" flex="1"/> </treecols> <template> <query expr="*"/> <action> <treechildren> <treeitem uri="?"> <treerow> <treecell label="?name"/> </treerow> </treeitem> </treechildren> </action> </template> </tree> « previousnext » ...
Introduction - Archive of obsolete content
actually, this isn't quite
true.
...if the datasource is already loaded, the builder can construct content all in one step, although even this isn't completely
true as we'll see later.
Sorting Results - Archive of obsolete content
the sortactive attribute may be set to
true or false and specifies which column the tree is sorted by.
... only one column should have the sortactive attribute set to
true at a time.
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
rn:mozilla:package:root"> <rdf:li rdf:resource="urn:mozilla:package:custombutton"/> </rdf:seq> <rdf:description rdf:about="urn:mozilla:package:custombutton" chrome:displayname="custom button" chrome:description="my custom toolbar button" chrome:author="my name" chrome:name="custombutton" chrome:localeversion="1.8" chrome:skinversion="1.5" chrome:extension="
true"/> <rdf:seq about="urn:mozilla:overlays"> <!-- browser --> <rdf:li> <rdf:seq about="chrome://navigator/content/navigator.xul"> <rdf:li>chrome://custombutton/content/button.xul</rdf:li> </rdf:seq> </rdf:li> <!-- address book --> <rdf:li> <rdf:seq about="chrome://messenger/content/addressbook/addressbook.xul"> <rdf:li>chrome://custombutton/...
...bout="urn:mozilla:package:root"> <rdf:li rdf:resource="urn:mozilla:package:myapp"/> </rdf:seq> <rdf:description rdf:about="urn:mozilla:package:myapp" chrome:displayname="myapp" chrome:description="my first xul app" chrome:author="yours truly" chrome:name="myapp" chrome:localeversion="1.8" chrome:skinversion="1.5" chrome:extension="
true"/> </rdf:rdf> replace the fields in bold with your xul file name and change the displayname, description, and author attributes as suits you.
Box Objects - Archive of obsolete content
example 2 : source view <script> function showpositionandsize() { var labelbox = document.getelementbyid('thelabel').boxobject; alert("position is (" + labelbox.x + "," + labelbox.y + ") and size is (" + labelbox.width + "," + labelbox.height + ")"); } </script> <button label="hide" oncommand="document.getelementbyid('thelabel').hidden =
true;"/> <button label="show" oncommand="document.getelementbyid('thelabel').hidden = false;"/> <button label="collapse" oncommand="document.getelementbyid('thelabel').collapsed =
true;"/> <button label="uncollapse" oncommand="document.getelementbyid('thelabel').collapsed = false;"/> <button label="show position/size" oncommand="showpositionandsize();"/> <label id="thel...
...example 3 : source view <hbox> <button label="button 1" oncommand="alert('next is: ' + this.boxobject.nextsibling.label);"/> <button label="button 2" hidden="
true"/> <button label="button 3" oncommand="alert('next is: ' + this.boxobject.nextsibling.label);"/> <button label="button 4" collapsed="
true"/> </hbox> box ordering attributes when a xul box is laid out on a window, the elements are ordered according to a number of properties, for instance the orientation, their ordinal group and their direction.
Creating a Skin - Archive of obsolete content
tab:first-child { -moz-border-radius: 4px 0px 0px 0px; } tab:last-child { -moz-border-radius: 0px 4px 0px 0px; } tab[selected="
true"] { color: #000066; font-weight: bold; text-decoration: underline; } two rules change the normal tab appearance, the first sets the rounding on the first tab and the second sets the rounding on the last tab.
... the last rule only applies to tabs that have their selected attribute set to
true.
Creating a Window - Archive of obsolete content
note: the local xul document can be opened in the browser as mentioned above only if |dom.allow_xul_xbl_for_file| preference in "about:config" has been set to |
true| .
... if it does not exist, then it needs to be created and set to |
true|.
Focus and Selection - Archive of obsolete content
example 3 : source view <window id="focus-example" title="focus example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init(){ addeventlistener("focus",setfocusedelement,
true); } function setfocusedelement(){ var focused = document.commanddispatcher.focusedelement; document.getelementbyid("focused").value = focused.tagname; } </script> <hbox> <label control="username" value="user name:"/> <textbox id="username"/> </hbox> <button label="hello"/> <checkbox label="remember this decision"/> <label id="focused" value="-no focus-"/> </window> in this example, ...
...it will have the value
true if the textbox has the focus and, if the textbox does not have the focus, the attribute will not be present.
Keyboard Shortcuts - Archive of obsolete content
to do this add a disabled attribute to the key element and set it to the value
true.
... <menuitem label="close" accesskey="c" key="close_cmd" oncommand="window.close();"/> </menupopup> </menu> <menu id="edit-menu" label="edit" accesskey="e"> <menupopup id="edit-popup"> <menuitem label="cut" accesskey="t" key="cut_cmd"/> <menuitem label="copy" accesskey="c" key="copy_cmd"/> <menuitem label="paste" accesskey="p" key="paste_cmd" disabled="
true"/> </menupopup> </menu> </menubar> </toolbox> </vbox> </window> now we can use those shortcuts to activate the commands.
List Controls - Archive of obsolete content
its syntax is best described with the example below: example 5 : source view <menulist label="bus"> <menupopup> <menuitem label="car" /> <menuitem label="taxi" /> <menuitem label="bus" selected="
true" /> <menuitem label="train" /> </menupopup> </menulist> this menulist will contain four choices, one for each menuitem element.
...to create an editable menulist, add the editable attribute as follows: example 6 : source view <menulist editable="
true"> <menupopup> <menuitem label="www.mozilla.org" /> <menuitem label="www.xulplanet.com" /> <menuitem label="www.dmoz.org" /> </menupopup> </menulist> the url field created here has three pre-populated choices that the user can select or they can enter one of their own by typing it into the field.
Manifest Files - Archive of obsolete content
x-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <rdf:seq about="urn:mozilla:package:root"> <rdf:li resource="urn:mozilla:package:myapplication"/> </rdf:seq> <rdf:description about="urn:mozilla:package:myapplication" chrome:displayname="application title" chrome:author="author name" chrome:name="myapplication" chrome:extension="
true"/> </rdf:rdf> content,install,url,file:///main/app/ create a directory somewhere on your disk.
... if the 'chrome:extension' field is
true, the application is a mozilla firefox extension and it will show up in the extensions window of the browser.
More Wizards - Archive of obsolete content
the wizard has a property canadvance, which can be set to
true to indicate that the next button should be enabled.
...="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.
Tabboxes - Archive of obsolete content
the currently selected tab element is given an additional selected attribute which is set to
true.
...only one tab will have a
true value for this attribute at a time.
Tree Box Objects - Archive of obsolete content
example 1 : source view <script> function doscroll(){ var value = document.getelementbyid("tbox").value; var tree = document.getelementbyid("thetree"); var boxobject = tree.boxobject; boxobject.queryinterface(components.interfaces.nsitreeboxobject); boxobject.scrolltorow(value); } </script> <tree id="thetree" rows="4"> <treecols> <treecol id="row" label="row" primary="
true" flex="1"/> </treecols> <treechildren> <treeitem label="row 0"/> <treeitem label="row 1"/> <treeitem label="row 2"/> <treeitem label="row 3"/> <treeitem label="row 4"/> <treeitem label="row 5"/> <treeitem label="row 6"/> <treeitem label="row 7"/> <treeitem label="row 8"/> <treeitem label="row 9"/> </treechildren> </tree> <hbox align="center"> <labe...
...; if (column.value && typeof column.value != "string") column.value = column.value.id; document.getelementbyid("row").value = row.value; document.getelementbyid("column").value = column.value; document.getelementbyid("part").value = part.value; } </script> <tree id="thetree" flex="1" onmousemove="updatefields(event);"> <treecols> <treecol id="utensil" label="utensil" primary="
true" flex="1"/> <treecol id="count" label="count" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="fork"/> <treecell label="5"/> </treerow> </treeitem> <treeitem> <treerow> <treecell label="knife"/> <treecell label="2"/> </treerow> </treeitem> <treeitem> <treerow> <treecell lab...
XUL Structure - Archive of obsolete content
in firefox, this preference may be added to the user preferences by typing "about:config" in the address field, and setting this value to
true.
... or, just manually edit your user.js preferences file and add the following line: pref("nglayout.debug.disable_xul_cache",
true); there are usually three different parts to a chrome package, although they are all optional.
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.
... display it is often said that "presentation is everything." while it is
true that presentation is essential, documents should also be structured so that the user can invoke display preferences that may be necessary for accessibility.
checkbox - Archive of obsolete content
attributes accesskey, checked, command, crop, disabled, src, label, preference, tabindex properties accesskey, accessibletype, checked, command, crop, disabled, src, label, tabindex examples <checkbox label="enable javascript" checked="
true"/> <checkbox label="enable java" checked="false"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
...do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
command - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... setting this attribute to "
true" indicates that the command is reserved for chrome code and is not available for use in the content.
prefpane - Archive of obsolete content
selected type: boolean this attribute will be set to
true for the currently selected prefpane.
... selected type: boolean this property's value is
true if this element is selected, or false if it is not.
richlistitem - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... selected type: boolean this property's value is
true if this element is selected, or false if it is not.
rule - Archive of obsolete content
true: the rule will only match nodes that are marked as containers.
...
true: the rule will only match nodes that contain no child elements.
scale - Archive of obsolete content
do not set the attribute to
true, as this will suggest you can set it to false to enable the element again, which is not the case.
... movetoclick type: boolean if
true, clicking the slide area of the scale moves the thumb directly to that position.
Application Update - Archive of obsolete content
gs in your application: branding 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.
...pref("app.update.auto",
true); // defines how the application update service notifies the user about updates: // // aum set to: minor releases: major releases: // 0 download no prompt download no prompt // 1 download no prompt download no prompt if no incompatibilities // 2 download no prompt prompt // // see chart in nsupdateservice.js.in for more details // pref("app.update.mode", 1); // if set to
true, the update service will present no ui for any event.
CommandLine - Archive of obsolete content
nsicomponentregistrar); compreg.registerfactorylocation(class_id, class_name, contract_id, afilespec, alocation, atype); var catman = components.classes["@mozilla.org/categorymanager;1"] .getservice(nsicategorymanager); catman.addcategoryentry("command-line-handler", cld_category, contract_id,
true,
true); }, unregisterself : function mod_unreg(acompmgr, 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); var test = cmdline.handleflagwithparam("test", false); alert("test = " + test); }, register: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(this, "commandl...
ant script to assemble an extension - Archive of obsolete content
/*.tpl.*"/> <exclude name="blogmark.jar"/> </fileset> </jar> </target> <target name="templates" description="generate files from templates."> <copy file="chrome/content/blogmark/contents.rdf.tpl.xml" tofile="chrome/content/blogmark/contents.rdf" overwrite="
true"> <filterchain> <replacetokens> <token key="version" value="${version}"/> <token key="description" value="${description}"/> </replacetokens> </filterchain> </copy> <copy file="chrome/...
...content/blogmark/about.xul.tpl.xml" tofile="chrome/content/blogmark/about.xul" overwrite="
true"> <filterchain> <replacetokens> <token key="version" value="${version}"/> </replacetokens> </filterchain> </copy> <copy file="install.rdf.tpl.xml" tofile="install.rdf" overwrite="
true"> <filterchain> <replacetokens> <token key="version" value="${version}"/> <token key="description" value="${description}"/> ...
NPN_PostURL - Archive of obsolete content
values:
true: post the file whose path is specified in buf, then delete the file.
... to post to a temporary file, set the flag file to
true, the buffer buf to the path name string for a file, and len to the length of the path string.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
*/ 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 s...
...once you've verified that the browser has the compatibility you require, you can modify your npp_getvalue call like so: nperror npp_getvalue(void *future, nppvariable variable, void *value) { nperror err = nperr_no_error; switch (variable) { case nppvpluginneedsxembed: *((prbool *)value) = pr_
true; break; default: err = nperr_generic_error; } return err; } once you have set those variables, it should be relatively easy to set up a plugin.
Theme changes in Firefox 3.5 - Archive of obsolete content
greying menus of inactive windows: active windows get attribute 'active="
true"'.
... to do this only for 3.5 use a css selector that is only supported in 3.5, like so: window:not([active="
true"]) menubar>menu:nth-child(1n) { color:threedshadow } private browsing: show private browsing state by coloring the url bar, or by adding an icon to the toolbox/tabbrowserbar.
Theme changes in Firefox 3 - Archive of obsolete content
as a result, the 'display' property should be removed from .tab-drop-indicator-bar (including for dragging="
true").
... browser/themes/pinstripe/browser/browser.css .tabbrowser-tab[first-tab="
true"] > .tab-image-left no longer has a margin-left.
Debug.setNonUserCodeExceptions - Archive of obsolete content
syntax debug.setnonusercodeexceptions [= bool]; remarks if this property is set to
true within a given scope, the debugger can then choose whether to take some specified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions.
... (function () { debug.setnonusercodeexceptions =
true; try{ var x = null; x.y(); } catch (e) { // catch the exception.
@if - Archive of obsolete content
syntax @if ( condition1 ) text1 [@elif ( condition2 ) text2] [@else text3] @end parameters text1 optional text to be parsed if condition1 is
true.
... text2 optional text to be parsed if condition1 is false and condition2 is
true.
Sharp variables in JavaScript - Archive of obsolete content
var a = #1 = { val:1, next:{val:2, next:#1#} }; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; //
true again, you can eliminate the need for sharp variables by using two lines instead of one for the declaration.
... var a = {val:1, next:{val:2, next:undefined} }; a.next.next = a; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; //
true multiple sharp variables var a = #1 = { val:#2=[], next:{val:[], next:{val:#02#, next:#1#}} }; // leading 0s don't matter a.val.push(1); a.next.val.push(2); a.val[0]; // 1 a.next.val[0]; // 2 a.next.next.val[0]; // 1 a.next.next.next.val[0]; // 1 a == a.next.next; // false a == a.next.next.next; //
true ...
XForms Select Element - Archive of obsolete content
incremental - supported, default value is
true properties selection - see corresponding attribute incremental - see corresponding attribute type restrictions the select element can be bound to a node containing simple content capable of holding a sequence.
...characteristics analogous widgets are <html:select size="5" multiple="
true"/> and <xul:listbox seltype="multiple"/> visual grouping by choices element isn't implemented if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e.
XForms Switch Module - Archive of obsolete content
if multiple cases within a switch are marked as selected="
true", the first selected case will appear and all others will not be visible.
...example <switch> <case id="in" selected="
true"> <input ref="yourname"> <label>please tell me your name</label> <toggle ev:event="domactivate" case="out"/> </input> </case> <case id="out" selected="false"> <html:p>hello <output ref="yourname" /> <trigger id="editbutton"> <label>edit</label> <toggle ev:event="domactivate" case="in"/> </trigger> </html:p> </case> </switch> ...
Efficient animation for web games - Game development
} var drawpending = false; function requestredraw() { if (!drawpending) { drawpending =
true; requestanimationframe(redraw); } } following this pattern — or something similar — means that no matter how many times you call requestredraw, your drawing function will only be called once per frame.
...to an extent, this was
true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn’t quite there.
Build the brick field - Game development
fill in the contents as shown below: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { var brickx = 0; var bricky = 0; newbrick = game.add.sprite(brickx, bricky, 'brick'); game.physics.enable(newbrick, phaser.physics.arcade); newbrick.body.immovable =
true; newbrick.anchor.set(0.5); bricks.add(newbrick); } } here we're looping through the rows and columns to create the new bricks and place them on the screen.
... c++) { for(r=0; r<brickinfo.count.row; r++) { var brickx = (c*(brickinfo.width+brickinfo.padding))+brickinfo.offset.left; var bricky = (r*(brickinfo.height+brickinfo.padding))+brickinfo.offset.top; newbrick = game.add.sprite(brickx, bricky, 'brick'); game.physics.enable(newbrick, phaser.physics.arcade); newbrick.body.immovable =
true; newbrick.anchor.set(0.5); bricks.add(newbrick); } } } if you reload index.html at this point, you should see the bricks printed on screen, at an even distance from one another.
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
in computer science, a boolean is a logical data type that can have only the values
true or false.
... /* javascript if statement */ if (boolean conditional) { // code to execute if the conditional is
true } if (boolean conditional) { console.log("boolean conditional resolved to
true"); } else { console.log("boolean conditional resolved to false"); } /* javascript for loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is
true } for (var i=0; i < 4; i++) { console.log("i print only when the boolean conditional is
true"); } the boolean value is named after...
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.
... finally, due to the or operator, the value ( false or
true ) is
true, so authentication bypasses successfully.
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a truthy value is a value that is considered
true when encountered in a boolean context.
... examples of truthy values in javascript (which will be coerced to
true in boolean contexts, and thus execute the if block): if (
true) if ({}) if ([]) if (42) if ("0") if ("false") if (new date()) if (-42) if (12n) if (3.14) if (-3.14) if (infinity) if (-infinity) specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification.
Web fonts - Learn web development
it doesn't matter whether they are ttf (
true type fonts) or otf (open type fonts).
...this is what one of the blocks looks like: @font-face { font-family: 'ciclefina'; src: url('fonts/cicle_fina-webfont.eot'); src: url('fonts/cicle_fina-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/cicle_fina-webfont.woff2') format('woff2'), url('fonts/cicle_fina-webfont.woff') format('woff'), url('fonts/cicle_fina-webfont.ttf') format('
truetype'), url('fonts/cicle_fina-webfont.svg#ciclefina') format('svg'); font-weight: normal; font-style: normal; } this is referred to as "bulletproof @font-face syntax", after a post by paul irish from early on when @font-face started to get popular (bulletproof @font-face syntax).
Example 5 - Learn web development
ml content <form class="no-widget"> <select name="myfruit"> <option>cherry</option> <option>lemon</option> <option>banana</option> <option>strawberry</option> <option>apple</option> </select> <div class="select" role="listbox"> <span class="value">cherry</span> <ul class="optlist hidden" role="presentation"> <li class="option" role="option" aria-selected="
true">cherry</li> <li class="option" role="option">lemon</li> <li class="option" role="option">banana</li> <li class="option" role="option">strawberry</li> <li class="option" role="option">apple</li> </ul> </div> </form> css content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } /* --------------...
...ighlight'); }); option.classlist.add('highlight'); }; function updatevalue(select, index) { var nativewidget = select.previouselementsibling; var value = select.queryselector('.value'); var optionlist = select.queryselectorall('.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.queryse...
How to build custom form controls - Learn web development
this is especially
true in a team environment when the people who design the control's behavior are different from the ones who implement it.
...dget = select.previouselementsibling; var value = select.queryselector('.value'); var optionlist = select.queryselectorall('[role="option"]'); // we make sure that all the options are not selected optionlist.foreach(function (other) { other.setattribute('aria-selected', 'false'); }); // we make sure the chosen option is selected optionlist[index].setattribute('aria-selected', '
true'); nativewidget.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(select, optionlist[index]); }; it might have seemed simpler to let a screen reader focus on the off-screen select and ignore our stylized one, but this is not an accessible solution.
Graceful asynchronous programming with Promises - Learn web development
the code that the video chat application would use might look something like this: function handlecallbutton(evt) { setstatusmessage("calling..."); navigator.mediadevices.getusermedia({video:
true, audio:
true}) .then(chatstream => { selfviewelem.srcobject = chatstream; chatstream.gettracks().foreach(track => mypeerconnection.addtrack(track, chatstream)); setstatusmessage("connected"); }).catch(err => { setstatusmessage("failed to connect"); }); } this function starts by using a function called setstatusmessage() to update a status display with the mes...
...to produce an error on a 404, for example, we need to check the value of response.ok, and if false, throw an error, only returning the blob if it is
true.
Function return values - Learn web development
the test looks at whether the expression isnan(num) returns
true.
... the isnan() function to test whether the num value is not a number — if so, it returns
true, and if not, it returns false.
Storing the information you need — Variables - Learn web development
let dolphingoodbye = 'so long and thanks for all the fish'; booleans booleans are
true/false values — they can have two values,
true or false.
...so for example, a simple case would be: let iamalive =
true; whereas in reality it would be used more like this: let test = 6 < 3; this is using the "less than" operator (<) to test whether 6 is less than 3.
What went wrong? Troubleshooting JavaScript - Learn web development
you should make sure that you don't mix up the assignment operator (=) — which sets a variable to be equal to a value — with the strict equality operator (===), which tests whether one value is equal to another, and returns a
true/false result.
...for example, if we were to change this line inside checkguess(): if (userguess === randomnumber) { to if (userguess = randomnumber) { the test would always return
true, causing the program to report that the game has been won.
Multimedia: video - Learn web development
<video autoplay="" loop="" muted="
true" playsinline="" src="backgroundvideo.mp4"> while the loop and autoplay make sense for a looping and autoplaying video, the muted attribute is required for autoplay in mobile browsers.
... <video autoplay="" loop="" muted="
true" playsinline="" id="hero-video"> <source src="banner_video.webm" type='video/webm; codecs="vp8, vorbis"'> <source src="web_banner.mp4" type="video/mp4"> </video> this hero-video code (above) is common to conference websites and corporate home pages.
Client-Server Overview - Learn web development
tion/xml;q=0.9,image/webp,*/*;q=0.8 referer: https://developer.mozilla.org/ accept-encoding: gzip, deflate, sdch, br accept-charset: iso-8859-1,utf-8;q=0.7,*;q=0.7 accept-language: en-us,en;q=0.8,es;q=0.6 cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; csrftoken=zipujsazv6pcgcbjscj1zu6pqzbfmuat; dwf_section_edit=false; dwf_sg_task_completion=false; _gat=1; _ga=ga1.2.1688886003.1471911953; ffo=
true the first and second lines contain most of the information we talked about above: the type of request (get).
...plication/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 referer: https://developer.mozilla.org/profiles/hamishwillee/edit accept-encoding: gzip, deflate, br accept-language: en-us,en;q=0.8,es;q=0.6 cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; _gat=1; csrftoken=zipujsazv6pcgcbjscj1zu6pqzbfmuat; dwf_section_edit=false; dwf_sg_task_completion=false; _ga=ga1.2.1688886003.1471911953; ffo=
true csrfmiddlewaretoken=zipujsazv6pcgcbjscj1zu6pqzbfmuat&user-username=hamishwillee&user-fullname=hamish+willee&user-title=&user-organization=&user-location=australia&user-locale=en-us&user-timezone=australia%2fmelbourne&user-irc_nickname=&user-interests=&user-expertise=&user-twitter_url=&user-stackoverflow_url=&user-linkedin_url=&user-mozillians_url=&user-facebook_url= the main difference is that ...
Accessibility in React - Learn web development
the textbox <input> in your editing template should be updated like this: <input id={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} ref={editfieldref} /> the "edit" button in your view template should read like this: <button type="button" classname="btn" onclick={() => setediting(
true)} ref={editbuttonref} > edit <span classname="visually-hidden">{props.name}</span> </button> focusing on our refs with useeffect to use our refs for their intended purpose, we need to import another react hook: useeffect().
... update your existing useeffect() hook so that it reads like this: useeffect(() => { if (isediting) { editfieldref.current.focus(); } }, [isediting]); these changes make it so that, if isediting is
true, react reads the current value of the editfieldref and moves browser focus to it.
Adding a new todo form: Vue events, methods, and models - Learn web development
.passive: equivalent to using the { passive:
true } parameter when creating an event listener in vanilla javascript using addeventlistener().
... 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'); } } }; next, add an event listener for the todo-added event to the <to-do-form></to-do-form>, which calls the addtodo() method when the event fires.
Focus management with Vue refs - Learn web development
to see the value of the ref when we click our "edit" button, add a console.log() to our toggletoitemeditform() method, like so: toggletoitemeditform() { console.log(this.$refs.editbutton); this.isediting =
true; } if you activate the "edit" button at this point, you should see an html <button> element referenced in your console.
... well, remember that when we change isediting to
true, we no longer render the section of the component featuring the "edit" button.
Handling common JavaScript problems - Learn web development
you need some kind of a feature detection test that detects whether the browser supports the feature we are trying to use: if (browsersupportsallfeatures()) { main(); } else { loadscript('polyfills.js', main); } function main(err) { // actual app code goes in here } so first we run a conditional that checks whether the function browsersupportsallfeatures() returns
true.
...if both do, the function returns
true.
Accessibility/LiveRegionDevGuide
if atomic is set to "
true", it means that the region must be presented as a whole while atomic="false" (default) indicates that the region can stand on it's own.
...when atomic is set to "
true", the entire region should be presented.
Embedding API for Accessibility
be aware that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_
true /* or pr_false */); prefs->setintpref("int.pref.name", newvalue); prefs->setcharpref("string.pref.name", newcharstarvalue); to manually add a pref to your settings, add a line like the following to your prefs.js: user_pref("accessibility.browsewithcaret",
true); accessibility prefs reference the following is a description of what accessibility prefs give us (or will give us), for access...
...ility.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 user_pref("browser.block.target_new_window",
true); // override popup windows at beginning of new page load (blocks most popup advertisements) user_pref("dom.disable_open_during_load",
true); moz 0.8 client side redirects setboolpref("browser.accept.redirects", acceptredirects); no ...
Mozilla’s UAAG evaluation report
ser_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: user_pref("browser.target_new_blocked",
true); override popup windows at beginning of new page load (blocks most popup advertisements): user_pref("dom.disable_open_during_load",
true); 5.4 selection and focus in viewport.
...tline box highlights follow graphical rendering conventions for windows does not highlight selected images we do not have the ability to show a border around the text selection we have the following focus appearance prefs that are not exposed in the ui, but can be manually inserted in the user's prefs.js file: setboolpref("browser.display.use_focus_colors", usefocuscolors); /*
true or false */ setcharpref("browser.display.focus_background_color", colorstring); /* for example #ffeedd or the name of a color */ setcharpref("browser.display.focus_text_color", colorstring); setcharpref("browser.display.focus_ring_width", numpixels); /* integer 0-4 */ 10.3 distinct default highlight styles.
Adding a new event
for copying the members, this should use assignfooeventdata() with
true for acopytargets.
... if your new event shouldn't be created with event constructor such as: var event = new fooevent("bar", { bubbles:
true, cancelable:
true, detail: 5 }); you shouldn't define construnctor in it.
Application cache implementation overview
loadedfromapplicationcache flag is now set
true on the channel.
...this flag is by default
true, but it is dropped by nsdocshell::douriload() to false only for top level document loading channels.
A bird's-eye view of the Mozilla framework
suppose the client already has an nsirdfdatasource object representing a sub-graph of an rdf graph and calls nsirdfdatasource.gettarget(resource, nc_link,
true) to obtain an nsirdfnode representing a specific node in the graph, in this case a link to ahelp viewer document page.
... var link = tocds.gettarget(resource, nc_link,
true); now that getlink() has the nsirdfnode for the link, it can call queryinterface() to check whether the nsirdfliteral is supported.
Browser chrome tests
function test() { waitforexplicitfinish(); settimeout(completetest, 1000); } function completetest() { ok(
true, "timeout ran"); finish(); } if your test is randomly timing out and you think that's just due to it taking too long, you can extend the timeout.
... requestlongertimeout(2); waitforexplicitfinish(); settimeout(completetest, 40000); } function completetest() { ok(
true, "timeout did not run"); finish(); } exceptions in tests any exceptions thrown under test() will be caught and reported in the test output as a failure.
Creating a Login Manager storage module
to see some debugging output in the console set signon.debug to
true using about:config.
...the category registration looks like this: nscomptr<nsicategorymanager> cat = do_getservice(ns_categorymanager_contractid); ns_ensure_state(cat); cat->addcategoryentry("login-manager-storage", "nsiloginmanagerstorage", kyourcontractid, pr_
true, pr_
true, nsnull); don't forget to unregister the category on unload.
Creating reftest-based unit tests
for tests that are run manually, this is not
true.
...for example, it occurs to me that we assume that spaces between a element name and an attribute name have no effect, but do we know this is
true?
Creating Sandboxed HTTP Connections
if amerge is
true, the new value is appened, otherwise the old value is overwritten.
...if amerge is
true, the new value is appened, otherwise the old value is overwritten.
Listening to events on all tabs
asameuri
true if awebprogress is requesting a refresh of the current uri.
... return value
true if the refresh may proceed.
HTMLIFrameElement.getCanGoBack()
}); returns a promise that resolves with a boolean that equals
true if the history can be navigated backward or false if not.
... example function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled =
true; console.log("it's not possible to navigate the history backward."); } }); } specification not part of any specification.
HTMLIFrameElement.getCanGoForward()
}); returns a promise that resolves with a boolean that equals
true if the history can be navigated forward or false if not.
... example function canmovefwd() { browser.getcangoforward().then(function(result) { if (result) { fwd.disabled = false; console.log("it's possible to navigate the history forward."); } else { fwd.disabled =
true; console.log("it's not possible to navigate the history forward."); } }); } specification not part of any specification.
HTMLIFrameElement.getMuted()
the muted value is available in the request.result property, and is a boolean value —
true means muted, and false means unmuted.
... promise version: a promise that resolves with the muted value — a boolean where
true means muted, and false means unmuted.
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.
... 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).
mozbrowsercaretstatechanged
its properties are canselectall: a boolean indicating whether the selectall command is available (
true) or not (false.) cancut: a boolean indicating whether the cut command is available (
true) or not (false.) cancopy: a boolean indicating whether the copy command is available (
true) or not (false.) canpaste: a boolean indicating whether the paste command is available (
true) or not (false.) reason a domstring that defines the reason for the state being changed.
... collapsed a boolean indicating whether the current selection is collapsed (
true) or not (false.) caretvisible a boolean indicating whether the caret is currently visible (
true) or not (false.) selectionvisible a boolean indicating whether the current selection is visible (
true) or not (false.) selectioneditable a boolean indicating whether the current selection is editable (
true) or not (false.) selectedtextcontext a domstring containing the currently-selected text content.
mozbrowserlocationchange
cangoback a boolean that defines whether it's possible to go back in the navigation history (
true) or not (false).
... cangoforward a boolean that defines whether it's possible to go forward in the navigation history (
true) or not (false).
HTTP Cache
the anew argument in oncacheentryavailable is
true for and only for new entries.
...tput stream of the entry has been opened or closed metadataready or setvalid on the entry has been called the entry has been doomed state == empty: on oper_readonly flag use: oncacheentryavailable with null for the cache entry otherwise: state = writing opener is removed from the fifo and remembered as the current 'writer' oncacheentryavailable with anew =
true and this entry is invoked (on the caller thread) for the writer state == ready: oncacheentrycheck with the entry is invoked on the first opener in fifo - on the caller thread if demanded result == recheck_after_write_finished: opener is left in the fifo with a flag recheckafterwrite such openers are skipped until the output stream on the entry is closed, the...
Implementing QueryInterface
nsresult status; if ( !foundinterface ) { // ok, ask |nsbase1imp| first, because i want _it_ to be the one
true |nsisupports|.
... it will be difficult, if not impossible, to get the right thing to happen if any of your base classes participate in
true aggregation.
JavaScript-DOM Prototypes in Mozilla
because of this, the following holds
true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ if img1 would come from one document and img2 from another document, then the above would not be
true.
...prototype | |.__proto__ | element.prototype | |.__proto__ | node.prototype | |.__proto__ | object.prototype | |.__proto__ | null if you have an instance of a htmldivelement in javascript, the following will hold
true: div.__proto__ === htmldivelement.prototype which means that the following should also be
true: div.__proto__ === div.constructor.prototype non standard no browser is required to provide modifiable __proto__, nor a global node, nor provide any way to get at host objects nor their associated prototypes.
Widget Wrappers
areatype the type of the widget's current area isgroup
true, will be false for wrappers around single widget nodes source for api-provided widgets, whether they are built-in to firefox or add-on-provided disabled for api-provided widgets, whether the widget is currently disabled.
...this will point to the overflow chevron on overflowable toolbars if and only if your widget node is overflowed, to the anchor for the panel menu if your widget is inside the panel menu, and to the node itself in all other cases overflowed boolean indicating whether the node is currently in the overflow panel of the toolbar isgroup false, will be
true for the group widget label for api-provided widgets, convenience getter for the label attribute of the dom node tooltiptext for api-provided widgets, convenience getter for the tooltiptext attribute of the dom node disabled for api-provided widgets, convenience getter and setter for the disabled state of this single widget.
DeferredTask.jsm
this is always
true when read from code inside the task function, but can also be
true when read from external code, in case the task is an asynchronous generator function.
... bool ispending(); return value returns
true if pending, false otherwise.
Dict.jsm
return value
true if an entry was found and removed; false if no match was found.
... return value
true if the specified key is in the dictionary, otherwise false.
Downloads.jsm
close the message to stop."); } finally { yield list.remove(download); yield download.finalize(
true); } } finally { yield list.removeview(view); } }).then(null, components.utils.reporterror); conversion from nsidownloadmanager starting in firefox for desktop version 26, the nsidownloadmanager and nsidownload interfaces are not available anymore.
...to enable the new download manager : first you have to set the pref browser.download.usejstransfer to
true.
Sqlite.jsm
defaults to
true.
... these functions receive the following arguments: readonly (optional) if
true the clone will be read-only, default is false.
WebChannel.jsm
examples setting up a webchannel between chrome code and a webpage chrome code let channel = new webchannel(webchannelid, services.io.newuri("https://mozilla.org", null, null)); // receive messages channel.listen(function (webchannelid, message, sendercontext) { // send messages channel.send({ data: { greeting:
true } }, sendercontext); }); webpage code receive messages from an existing webchannel in content code window.addeventlistener("webchannelmessagetocontent", function(e) { // receive messages console.log(e.detail); },
true); send messages to an existing webchannel in chrome code window.dispatchevent(new window.customevent("webchannelmessagetochrome", { detail: { id: webchannelid,...
... message: { something:
true } } })); ...
Creating localizable web applications
this is particularly
true for short strings, like "file" or "log in".
...while this is
true for english, it should be noted that some languages require different forms of strings for numbers greater than 1 as well.
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.
browser.download.lastDir.savePerSite
if set to
true, the data is stored as content preference.
... type:boolean default value:
true exists by default: no application support:firefox 11.0 status: active; last updated 2012-02-15 introduction: pushed to nightly on 2011-12-11 bugs: bug 702748 values
true (default) the last used directory for the website (host) serving the file for download will be preselected in the file picker.
browser.pagethumbnails.capturing_disabled
type:boolean default value:
true exists by default: no application support: firefox 14.0 status: active; last updated 2012-09-17 introduction: pushed to nightly on 2012-04-13 bugs: bug 726347 values false the application creates screenshots of visited web pages.
...
true (default) the application doesn't create screenshots of visited web pages.
Preference reference
set it to
true to enable it, or false to disable it.browser.dom.window.dump.filebrowser.dom.window.dump.file redirects the ouput of window.dump() calls to a file whose address is specified in this preference if browser.dom.window.dump.enabled is set to
true.
...if set to
true, the data is stored as content preference.browser.pagethumbnails.capturing_disabledthe preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "new tab page" (about:newtab) which offers the most often visited pages for fast navigation.browser.search.context.loadinbackgroundbrowser.search.context.loadinbackground controls whether a search from the context menu with "search <search engine> for <selected t...
Leak And Bloat Tests
user_pref("mail.accountmanager.accounts", "account1,account2"); user_pref("mail.accountmanager.defaultaccount", "account2"); user_pref("mail.accountmanager.localfoldersserver", "server1"); user_pref("mail.identity.id1.fullname", "tinderbox"); user_pref("mail.identity.id1.smtpserver", "smtp1"); user_pref("mail.identity.id1.useremail", "tinderbox@invalid.com"); user_pref("mail.identity.id1.valid",
true); user_pref("mail.root.none-rel", "[profd]mail"); user_pref("mail.root.pop3-rel", "[profd]mail"); user_pref("mail.server.server1.directory-rel", "[profd]mail/local folders"); user_pref("mail.server.server1.hostname", "local folders"); user_pref("mail.server.server1.name", "local folders"); user_pref("mail.server.server1.type", "none"); user_pref("mail.server.server1.username", "nobody"); user_pre...
...f("mail.server.server2.check_new_mail", false); user_pref("mail.server.server2.directory-rel", "[profd]mail/tinderbox"); user_pref("mail.server.server2.download_on_biff",
true); user_pref("mail.server.server2.hostname", "tinderbox"); user_pref("mail.server.server2.login_at_startup", false); user_pref("mail.server.server2.name", "tinderbox@invalid.com"); user_pref("mail.server.server2.type", "pop3"); user_pref("mail.server.server2.username", "tinderbox"); user_pref("mail.smtp.defaultserver", "smtp1"); user_pref("mail.smtpserver.smtp1.hostname", "tinderbox"); user_pref("mail.smtpserver.smtp1.username", "tinderbox"); user_pref("mail.smtpservers", "smtp1"); user_pref("mail.startup.enabledmailcheckonce",
true); user_pref("mailnews.start_page_override.mstone", "1.9pre"); user_pref("mail.shell.checkd...
Introduction to NSPR
this requirement implies that when a thread first enters the monitor, an evaluation of the invariant expression must yield a
true.
...therefore, evaluation of the expression must also yield a
true at that point in execution.
PRBool
syntax #include <prtypes.h> typedef enum { pr_false = 0, pr_
true = 1 } prbool; description wherever possible, do not use prbool in mozilla c++ code.
...use pr_false and pr_
true for clarity of target type in assignments and actual arguments.
PR_Wait
the thread should act on the data only when the expression is
true.
... resuming from the wait is merely an opportunity to evaluate the expression, not an assertion that the expression is
true.
NSS 3.12.5 release_notes
additional documentation in pk11pub.h: the caller of pk11_derencodepublickey should free the returned secitem with a secitem_freeitem(..., pr_
true) call.
... in secasn1.h: if both pool and dest are null, the caller should free the returned secitem with a secitem_freeitem(..., pr_
true) call.
NSS 3.12.6 release notes
nss_ssl_require_safe_negotiation values: 1: requiresafenegotiation =
true unset: requiresafenegotiation = false controls whether safe renegotiation indication is required for initial handshake.
... if
true, a connection will be dropped at initial handshake if the peer server or client does not support safe renegotiation.
NSS 3.15 release notes
tls client applications may enable this via a call to ssl_optionsetdefault(ssl_enable_ocsp_stapling, pr_
true); added function secitem_reallocitemv2.
... new macros in ssl.h ssl_enable_ocsp_stapling - used with ssl_optionset to configure tls client sockets to request the certificate_status extension (eg: ocsp stapling) when set to pr_
true notable changes in nss 3.15 secitem_reallocitem is now deprecated.
NSS 3.30 release notes
nss 3.30 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_rtm/src/ new in nss 3.30 new functionality in the pkcs#11 root ca module (nssckbi), cas with positive trust are marked with a new boolean attribute, cka_nss_mozilla_ca_policy, set to
true.
... new macros in ciferfam.h pkcs12_aes_cbc_128, pkcs12_aes_cbc_192, pkcs12_aes_cbc_256 - cipher family identifiers corresponding to the pkcs#5 v2.1 aes based encryption schemes used in the pkcs#12 support in nss in pkcs11n.h cka_nss_mozilla_ca_policy - identifier for a boolean pkcs#11 attribute, that should be set to
true, if a ca is present because of it's acceptance according to the mozilla ca policy notable changes in nss 3.30 the tls server code has been enhanced to support session tickets when no rsa certificate (e.g.
NSS Sample Code sample2
enccontext = pk11_createcontextbysymkey(ciphermech, cka_encrypt, symkey, secparam); rv1 = pk11_cipherop(enccontext, buf1, &tmp1_outlen, sizeof(buf1), data, strlen(data)+1); rv2 = pk11_digestfinal(enccontext, buf1+tmp1_outlen, &tmp2_outlen, sizeof(buf1)-tmp1_outlen); pk11_destroycontext(enccontext, pr_
true); result_len = tmp1_outlen + tmp2_outlen; if (rv1 != secsuccess || rv2 != secsuccess) goto out; fprintf(stderr, "encrypted data: "); for (i=0; i<result_len; i++) fprintf(stderr, "%02x ", buf1[i]); fprintf(stderr, "\n"); /* decrypt buf1 into buf2.
...ext */ enccontext = pk11_createcontextbysymkey(ciphermech, cka_decrypt, symkey, secparam); rv1 = pk11_cipherop(enccontext, buf2, &tmp1_outlen, sizeof(buf2), buf1, result_len); rv2 = pk11_digestfinal(enccontext, buf2+tmp1_outlen, &tmp2_outlen, result_len-tmp1_outlen); pk11_destroycontext(enccontext, pr_
true); result_len = tmp1_outlen + tmp2_outlen; if (rv1 != secsuccess || rv2 != secsuccess) goto out; fprintf(stderr, "decrypted data: %s\n", buf2); /* =========================== end section ============================= */ out: if (symkey) pk11_freesymkey(symkey); if (secparam) secitem_freeitem(secparam, pr_
true); } ...
nss tech note2
for example, 1024[805ef10]: c_findobjectsinit 1024[805ef10]: hsession = 0x1000001 1024[805ef10]: ptemplate = 0xbffff410 1024[805ef10]: ulcount = 3 1024[805ef10]: cka_label = localhost.nyc.rr.com [20] 1024[805ef10]: cka_token = ck_
true [1] 1024[805ef10]: cka_class = cko_certificate [4] 1024[805ef10]: rv = 0x0 1024[805ef10]: c_findobjects 1024[805ef10]: hsession = 0x1000001 1024[805ef10]: phobject = 0x806d810 1024[805ef10]: ulmaxobjectcount = 16 1024[805ef10]: pulobjectcount = 0xbffff38c 1024[805ef10]: *pulobjectcount = 0x1 1024[805ef10]: phobject[0] = 0xf6457d04 1024[805ef10]: rv = 0x0 1024[805ef10]: c_findo...
...ct = 0xf6457d04 1024[805ef10]: ptemplate = 0xbffff2d0 1024[805ef10]: ulcount = 2 1024[805ef10]: cka_token = 0 [1] 1024[805ef10]: cka_label = 0 [20] 1024[805ef10]: rv = 0x0 1024[805ef10]: c_getattributevalue 1024[805ef10]: hsession = 0x1000001 1024[805ef10]: hobject = 0xf6457d04 1024[805ef10]: ptemplate = 0xbffff2d0 1024[805ef10]: ulcount = 2 1024[805ef10]: cka_token = ck_
true [1] 1024[805ef10]: cka_label = localhost.nyc.rr.com [20] 1024[805ef10]: rv = 0x0 4.
FC_GetSessionInfo
otherwise, it fills in the ck_session_info structure with the following information: state: the state of the session, i.e., no role is assumed, the user role is assumed, or the crypto officer role is assumed flags: bit flags that define the type of session ckf_rw_session (0x00000002):
true if the session is read/write; false if the session is read-only.
... ckf_serial_session (0x00000004): this flag is provided for backward compatibility and is always set to
true.
Small Footprint
to build such minimalist jar without debug information, run the following command from the top directory of rhino distribution: ant clean ant -ddebug=off -dno-regexp=
true -dno-e4x=
true smalljar if you omit -dno-regexp=
true, then the resulting smalljs.jar will include regular expression support.
... similarly omitting -dno-e4x=
true results in smalljs.jar that includes runtime support for e4x.
Rhino scopes and contexts
to seal all objects in the standard library pass
true for the sealed argument when calling context.initstandardobjects(scriptableobject, boolean): scriptableobject sealedsharedscope = cx.initstandardobjects(null,
true); this seals only all standard library objects, it does not seal the shared scope itself thus after callinginitstandardobjects, sealedsharedscope can be farther populated with application-specific objects and functions.
... scriptableobject sealedsharedscope = cx.initstandardobjects(null,
true); // force the liveconnect stuff to be loaded.
Scripting Java
this works just as in java, with the use of the new operator: js> new java.util.date() thu jan 24 16:18:17 est 2002 if we store the new object in a javascript variable, we can then call methods on it: js> f = new java.io.file("test.txt") test.txt js> f.exists()
true js> f.getname() test.txt static methods and fields can be accessed from the class object itself: js> java.lang.math.pi 3.141592653589793 js> java.lang.math.cos(0) 1 in javascript, unlike java, the method by itself is an object and can be evaluated as well as being called.
...function can use it to distinguish on behalf of which method it was called: js> var frame = new packages.javax.swing.jframe(); js> frame.addwindowlistener(function(event, methodname) { if (methodname == "windowclosing") { print("calling system.exit()..."); java.lang.system.exit(0); } }); js> frame.setsize(100, 100); js> frame.visible =
true;
true js> calling system.exit()...
Invariants
so it is utterly crucially important that this invariant always be
true if objects are being created.
...but this is
true only so long as we are actually in the interpreter or jit code.
Introduction to the JavaScript shell
seal(object[, deep]) seals the specified object, or an object graph if deep is
true.
...returns
true on success, false if the sleep was interrupted.
JIT Optimization Strategies
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.
... for (var i = 0; i < array.length; i++) { if (array[i] > 100) return
true; } when this optimization is successful, property access is eliminated entirely and replaced with an inline constant.
BOOLEAN_TO_JSVAL
please use js::booleanvalue/js::
truevalue/js::falsevalue instead in spidermonkey 45 or later.
... if b is
true, the result is jsval_
true.
JS::PersistentRooted
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.
... js::rootedvalue val(cx, persistentval.ref()); // or // js::rootedvalue val(cx, *persistentval); // [spidermonkey 38] // js::rootedvalue val(cx, persistentval); args.rval().set(val); return
true; } static const jsfunctionspec functions[] = { js_fn("getpersistent", getpersistent, 1, 0), js_fn("setpersistent", setpersistent, 0, 0), js_fs_end }; int main(int argc, const char* argv[]) { // initialize runtime // ...
JSFastNative
if the jsfastnative returns js_
true, the last value passed to this macro will be returned to the caller.
... on success, the callback must call js_set_rval (at least once) and return js_
true.
JSObjectOps.getProperty
description get, set, or delete obj[id], returning js_false on error or exception, js_
true on success.
... if deleting without error, *vp will be jsval_false if obj[id] is permanent, and jsval_
true if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a property of a prototype, or no property in obj or its prototype chain).
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.
JSVAL_IS_NULL
syntax jsval_is_null(v) description jsval_is_null(v) is
true if v is jsval_null, which is the javascript null value.
... (note: jsval_is_object(jsval_null) is also
true.) example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it contains a null value.
JS_BufferIsCompilableUnit
otherwise return
true.
... the intent is to support interactive compilation - accumulate lines in a buffer until js_bufferiscompilableunit is
true, then pass it to the compiler.
JS_DeleteElement2
on success, *succeeded receives false if the property was not deleted because it is permanent and
true otherwise.
...if deletion is successful, js_deleteelement2 stores
true to *succeeded and returns
true.
JS_GetGCParameter
if
true, it is determined based on whether gcs are high- or low- frequency.
... jsgc_dynamic_mark_slice / "dynamicmarkslice" if
true, high-frequency gcs will use a longer mark slice.
JS_InstanceOf
js_instanceof returns
true if obj is of the given class and false otherwise.
...if obj is of the given class, it returns
true.
JS_IsExtensible
receives
true if extensible, false otherwise.
...if successful, js_isextensible stores [[extensible]] property to *extensible and returns
true, otherwise returns false and the value of *extensible is undefined.
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).
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).
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_PreventExtensions
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_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 * pointer to a js context from which to derive runtime informati...
... description js_samevalue determines whether two values are the same, returning
true or false accordingly.
JS_SetArrayLength
this is
true even if obj is not an array object.
...on success, js_setarraylength returns
true.
JS_SetBranchCallback
if the callback returns js_
true, the js engine continues to execute the script.
...the callback simply increments the counter and does nothing further (returning js_
true immediately) unless the counter has reached the threshold value.
JS_SetContextCallback
for future compatibility the callback must do nothing and return
true if any other value is passed.
...the callback may perform its own cleanup and must always return
true.
JS_SetElement
on success, js_setelement returns
true.
... 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.
JS_SetRegExpInput
multiline bool
true if input is multiline.
... on successful, js_setregexpinput returns
true, otherwise returns false.
JS_ValueToBoolean
on success, js_valuetoboolean stores the converted value in *bp and returns js_
true.
... for versions greater than jsversion_1_2, all objects convert to js_
true, even boolean wrapper objects like the one produced by new boolean(false).
JSAPI reference
s_dropexceptionstate these functions translate errors into exceptions and vice versa: js_reportpendingexception js_errorfromexception js_throwreportederror obsolete since jsapi 29 values and types typedef jsval js::value js::value constructors: js::nullvalue added in spidermonkey 24 js::undefinedvalue added in spidermonkey 24 js::booleanvalue added in spidermonkey 24 js::
truevalue added in spidermonkey 24 js::falsevalue added in spidermonkey 24 js::numbervalue added in spidermonkey 24 js::int32value added in spidermonkey 24 js::doublevalue added in spidermonkey 24 js::float32value added in spidermonkey 24 js::stringvalue added in spidermonkey 24 js::objectvalue added in spidermonkey 24 js::objectornullvalue added in spidermonkey 24 js::symbolvalue added in sp...
...idermonkey 38 js::value constants: js::nullhandlevalue added in spidermonkey 24 js::undefinedhandlevalue added in spidermonkey 24 js::
truehandlevalue added in spidermonkey 38 js::falsehandlevalue added in spidermonkey 38 jsval constants: jsval_null obsolete since jsapi 42 jsval_void obsolete since jsapi 42 jsval_
true obsolete since jsapi 42 jsval_false obsolete since jsapi 42 jsval_zero obsolete since jsapi 42 jsval_one obsolete since jsapi 42 function and macros for checking the type of a jsval: enum jstype js_typeofvalue all of the following are deprecated.
SpiderMonkey 31
the jsbool type has been removed, along with the corresponding js_
true and js_false constants.
... they have been replaced by bool,
true, and false respectively.
SpiderMonkey 38
g 645416) js::identifystandardconstructor (bug 976148) js::iscallable (bug 1065811) js::isconstructor (bug 1065811) js::mutablehandlesymbol (bug 645416) js::ordinarytoprimitive (bug 1103152) js::propertyspecnameequalsid (bug 1082672) js::propertyspecnameissymbol (bug 1082672) js::propertyspecnametopermanentid (bug 1082672) js::protokeytoid (bug 987669) js::rootedsymbol (bug 645416) js::
truehandlevalue (bug 959787) jsconstintegerspec (bug 1066020) jsid_is_symbol (bug 645416) jsid_to_symbol (bug 645416) jsprop_define_late (bug 825199) jsprop_ignore_enumerate (bug 1037770) jsprop_ignore_permanent (bug 1037770) jsprop_ignore_readonly (bug 1037770) jsprop_ignore_value (bug 1037770) jsprop_propop_accessors (bug 1088002) jsprop_redefine_nonconfigurable (bug 1101123) js_addfinali...
... 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.
Redis Tips
technically, this is
true: it's a database that doesn't use sql.
... it is also
true that ice cream is a food that isn't made from whale meat.
Retrieving part of the bookmarks tree
var rootnode = result.root; rootnode.containeropen =
true; // iterate over the immediate children of this folder and dump to console for (var i = 0; i < rootnode.childcount; i ++) { var node = rootnode.getchild(i); dump("child: " + node.title + "\n"); } // close a container after using it!
...etnewquery(); var bookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); var toolbarfolder = bookmarksservice.toolbarfolder; query.setfolders([toolbarfolder], 1); var result = historyservice.executequery(query, options); var rootnode = result.root; rootnode.containeropen =
true; // iterate over the immediate children of this folder and dump to console for (var i = 0; i < rootnode.childcount; i ++) { var node = rootnode.getchild(i); dump("child: " + node.title + "\n"); } // close a container after using it!
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.
... a quoted string in the preference file will always appear as a string, even if the value of the string is "
true" or "false".
An Overview of XPCOM
ns_failed return
true if the passed status code was a failure.
... ns_succeeded returns
true is the passed status code was a success.
Receiving startup notifications
registering with the category manager to register with the category manager, simply call its nsicategorymanager.addcategoryentry() method: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "contract-id", pr_
true, pr_
true, getter_copies(previous)); this causes your component to be instantiated using nsicomponentmanager.createinstance().
... if you want your component to be started as a service, prepend "service," to the contract id: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "service,contract-id", pr_
true, pr_
true, getter_copies(previous)); with "service," specified, the component is instantiated using nsicomponentmanager.getservice().
XPCOM Stream Guide
(this is particularly
true of streams that reach out over a network connection, like http and ftp channels.) stream listeners implement three methods.
... there are two parts: initializing the pump, and telling it to asynchronously read data into the stream listener: var pump = components.classes["@mozilla.org/network/input-stream-pump;1"] .createinstance(components.interfaces.nsiinputstreampump); pump.init(stream, -1, -1, 0, 0,
true); pump.asyncread(listener, context); nsipipe code examples file input and output for file input, see code snippets: reading from a file.
Introduction to XPCOM for the DOM
queryinterface() consider again the class nsfoo that implements two interfaces, nsifoo and nsifoo2: class nsfoo : public nsifoo, public nsifoo2 let's assume an instance of nsfoo was somehow created (this assertion is
true most of the time).
... return ns_ok; } ns_imethodimp nshtmldocument::getneat(prbool *aneat) { if(!aneat) { return ns_error_null_pointer; } nsresult rv = fabian(); if( rv == ns_ok ) { *aneat = pr_
true; } else { *aneat = pr_false; } return ns_ok; } this code is of course written in nshtmldocument.cpp.
Components.utils.isXrayWrapper
returns
true if the object is an xray: false otherwise.
... example var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); //
true var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waived); // false ...
Components.utils.reportError
to show them, set the preference 'javascript.options.showinconsole' to
true, or use nsconsoleservice instead to show a message.
... firefox 4: the preference 'javascript.options.showinconsole' is set to
true by default in this version.
Components.utils.unwaiveXrays
the chrome code can then use unwaivexrays to restore xray protection: // chrome code // contentwindow is an xray var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); //
true // expandos are not visible in xrays var foo = gbrowser.contentwindow.foo; // undefined // you can waive xray vision for an object var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waived); // false foo = waived.foo; // "i'm an expando"...
... // waiving is transitive isxray = components.utils.isxraywrapper(waived.document); // false // use unwaivexrays to undo the waiver var unwaived = components.utils.unwaivexrays(waived); isxray = components.utils.isxraywrapper(unwaived); //
true foo = unwaived.foo; // undefined // unwaiving is transitive isxray = components.utils.isxraywrapper(unwaived.document); //
true ...
HOWTO
put the following at the end of your script: // do async processing // from <https://developer.mozilla.org/en/xpconnect/xpcshell/howto> print("doing async work"); gscriptdone = false; var gthreadmanager = cc["@mozilla.org/thread-manager;1"] .getservice(ci.nsithreadmanager); var mainthread = gthreadmanager.currentthread; while (!gscriptdone) mainthread.processnextevent(
true); while (mainthread.haspendingevents()) mainthread.processnextevent(
true); 2.
...both success and error callbacks, put: gscriptdone =
true; if you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait).
XPCshell Test Manifest Expressions
operators in order of decreasing precedence: () == != && || literal values booleans: the literal strings
true and false.
... os_version - the version of the operating system on which the test is being run toolkit - the graphics toolkit used by this build one of: 'windows', 'cocoa', 'gtk2', 'android' processor - the cpu which the code is compiled for one of: 'x86', 'x86_64', 'arm' bits - the pointer size of the cpu architecture, in bits one of 32, 64, possibly unknown debug - set to
true if this build is a debug build, false otherwise crashreporter - set to
true if this build has crash reporting code enabled, false otherwise.
Observer Notifications
you can cancel the shutdown from here by setting asubject.data to
true (asubject is the first parameter to your observer, the data value is an nsisupportsprbool).
...recipients may set this to
true to abort the close.
IAccessibleTable2
isselected returns
true if the specified column is selected completely and false otherwise.
...isselected returns
true if the specified row is selected completely and false otherwise.
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.
mozIStorageAggregateFunction
t32 mean = total / mnumbers.length(); nstarray<print64> data(mnumbers); for (pruint32 i = 0; i < data.length(); i++) { print32 value = data[i] - mean; data[i] = value * value; } total = 0; for (pruint32 i = 0; i < data.length(); i++) total += data[i]; nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_
true(result, ns_error_out_of_memory); rv = result->setasdouble(sqrt(double(total) / double(data.length()))); ns_ensure_success(rv, rv); ns_addref(*_result = result); return ns_ok; } private: nstarray<print32> mnumbers; }; // now, register our function with the database connection.
... nscomptr<mozistoragefunction> func = new standarddeviationfunc(); ns_ensure_
true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("stddev"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function.
mozIStorageFunction
class squarefunction : public mozistoragefunction { public: ns_imethod onfunctioncall(mozistoragevaluearray *aarguments, 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.
... nscomptr<mozistoragefunction> func = new squarefunction(); ns_ensure_
true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("square"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function.
mozIStorageVacuumParticipant
return value return
true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed.
...void onendvacuum( in boolean asucceeded ); parameters asucceeded
true if the vacuum operation was successful, or false if it wasn't successful.
nsIAccessibleEvent
isfromuserinput boolean returns
true if the event was caused by explicit user input, as opposed to purely originating from a timer or mouse movement.
... example to listen to in-process accessibility invents, make your object an nsiobserver, and listen for accessible-event by using code something like this: nscomptr<nsiobserverservice> observerservice = do_getservice("@mozilla.org/observer-service;1", &rv); if (ns_succeeded(rv)) { rv = observerservice->addobserver(this, "accessible-event", pr_
true); } ...
nsIAppStartup
void getstartupinfo(); void hidesplashscreen(); obsolete since gecko 1.9.1 void initialize(in nsisupports nativeappsupportorsplashscreen); obsolete since gecko 1.9.1 void quit(in pruint32 amode); void restartinsafemode(in pruint32 aquitmode); void run(); attributes attribute type description interrupted boolean
true if the startup process was interrupted by an interactive prompt.
... return value
true if a window was opened.
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
if this attribute is set to
true, then the document will not be loaded from the cache.
...return value returns
true if this channel's data is being loaded from the cache, otherwise returns false.
nsIComponentRegistrar
return value
true if a factory is registered for the classid, false otherwise.
... return value
true if a factory is registered for the contractid, false otherwise.
nsIContentViewer
if the method returns
true, all subsequent calls will be ignored.
... return value
true if the document will allow unloading; otherwise false.
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.
nsICookie
isdomain boolean
true if the cookie is a domain cookie, false otherwise.
... issecure boolean
true if the cookie was transmitted over ssl, false otherwise.
nsICookie2
ishttponly boolean
true if the cookie is an http only cookie.
... issession boolean
true if the cookie is a session cookie.
nsICryptoHash
acstring finish( in prbool aascii ); parameters aascii if
true then the returned value is a base-64 encoded string.
...passing
true returns the hash as a base 64 encoded string.
nsIDBChangeListener
on the first call, aprechange is
true, and astatus is undefined.
... aprechange
true on first call before change, false on second call after change.
nsIDOMElement
boolean hasattribute( in domstring name ); parameters name attribute name return value a boolean,
true if the given attribute is set.
...boolean hasattributens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname attribute name return value a boolean,
true if the given attribute is set.
nsIDOMEvent
if the event can bubble the value is
true, else the value is false.
...if the default action can be prevented the value is
true, else the value is false.
nsIDOMStorageEventObsolete
canbubblearg
true if the event is allowed to bubble, otherwise false.
... cancelablearg
true if the event can be canceled, otherwise false.
nsIDroppedLinkHandler
if
true, the source is not checked.
... return value
true if the link being dragged can be dropped.
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.
... aforcesave
true to always save this content to disk, regardless of nsimimeinfo and other such influences.
nsIFormHistory2
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.
nsIGlobalHistory2
aredirect whether the uri was redirected to another location; this is
true for the original uri which is redirected.
... return value
true if a uri has been visited.
nsIHttpChannelInternal
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.
... channelisfordownload boolean external handlers may set this to
true to notify the channel that it is open on behalf of a download.
nsIIDNService
isascii on return, this is set to
true if the result is ascii or ace encoded; otherwise it's false.
... return value returns
true if the specified string is ace encoded; otherwise, returns false.
nsIIOService
n 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.
nsIJSID
returns
true if the jsid has been initialised.
... return value
true if the nsijsid's are valid and have the same nsid, otherwise false.
nsIMIMEInputStream
use: var mimeinputstream = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); method overview void addheader(in string name, in string value); void setdata(in nsiinputstream stream); attributes attribute type description addcontentlength boolean when
true a "content-length" header is automatically added to the stream.
... example var postdata = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength =
true; postdata.setdata(stringstream); ...
nsIMarkupDocumentViewer
inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) method overview void scrolltonode(in nsidomnode node); void sizetocontent(); attributes attribute type description allowplugins boolean if
true, plugins are allowed within the doc shell.
... default =
true.
nsIMemory
void heapminimize( in boolean immediate ); parameters immediate if
true, heap minimization will occur immediately if the call was made on the main thread.
... return value
true if we are in a low-memory situation.
nsIMimeConverter
void markread(in boolean read); parameters read if
true, mark as read.
... encoderwrite() void markflagged(in boolean flagged); parameters flagged if
true, mark as flagged.
nsIModule
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.
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: function(ahdr) {return 0;} } to attach it use the nsimsgdbview.addcolumnhandler() method (recall gdbview is the global nsimsgdbview in thunderbird): gdbview.addcolumnhandler("newcolumn", columnhandler...
...return value
true if the column displays a string value.
nsIMsgDatabase
aleaveinvaliddb set to
true if you do not want the database to bedeleted if it is invalid.
...if deleteviafolder is
true, we'll call nsimsgfolder.deletemessages() to delete the messages.
nsIMsgIncomingServer
by default this value is set to
true via global pref 'allows_specialfolders_usage' (mailnews.js).
...otherwise, return
true.
nsIMsgSearchTerm
y); 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.
nsINavHistoryResult
suppressnotifications boolean if
true, notifications are suppressed.
...if
true, the result will keep a weak reference to the observer, which must implement the nsisupportsweakreference interface.
nsINetworkLinkService
refox 8.0 / thunderbird 8.0 / seamonkey 2.5) implemented by: @mozilla.org/network/network-link-service;1 as a service: var networklinkservice = components.classes["@mozilla.org/network/network-link-service;1"] .getservice(components.interfaces.nsinetworklinkservice); attributes attribute type description islinkup boolean this is set to
true when the system is believed to have a usable network connection.
... linkstatusknown boolean this is set to
true when we believe that islinkup is accurate.
nsIPipe
void init( in boolean nonblockinginput, in boolean nonblockingoutput, in unsigned long segmentsize, in unsigned long segmentcount, in nsimemory segmentallocator ); parameters nonblockinginput
true specifies non-blocking input stream behavior.
... nonblockingoutput
true specifies non-blocking output stream behavior.
nsIPrintingPrompt
if you stub out this service you must set "printsilent" to
true, if you do not, printing will terminate and an error dialog will be displayed.
... isforprinting
true - for printing, false for print preview.
nsIPropertyBag
goodies obtained from window.navigator are: appcodename:"mozilla" appname:"netscape" appversion:"5.0 (windows)" battery:batterymanager buildid:"20140529161749" cookieenabled:
true donottrack:"yes" geolocation:geolocation language:"en-us" mimetypes:mimetypearray mozalarms:null mozapps:xpcwrappednative_nohelper mozcameras:cameramanager mozconnection:mozconnection mozcontacts:contactmanager mozid:null mozkeyboard:xpcwrappednative_nohelper mozpay:null mozpermissionsettings:null mozphonenumberservice:phonenumberservice mozpower:mozpowermanager moztcpsocket:null online:
true oscp...
...to do this use nsipropertybag: services.sysinfo.getproperty("version"); //output 5.1 services.sysinfo.getproperty("name"); //output windows_nt services.sysinfo.getproperty("arch"); //output x86 services.sysinfo.getproperty("haswindowstouchinterface"); //outputs false or
true if windows touch is there consult the uxp repo (//github.com/realityripple/uxp/blob/master/xpcom/base/nssysteminfo.cpp) for the properties supported.
nsIRequest
ispending is
true when there is an outstanding asynchronous event that will make the request no longer be pending.
... return value
true if the request has yet to reach completion.
nsIServiceManager
return value
true if the service has already been created.
... return value
true if the service has already been created.
nsISessionStore
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in versions of firefox prior to 3.5, the user preference browser.sessionstore.enabled must be
true for these calls to be successful.
... aoverwrite if this parameter is
true, all existing tabs are removed and replaced with the tabs in the state astate.
nsISimpleEnumerator
must be preceded by a call to hasmoreelements() which returns pr_
true.
...return value pr_
true if there are remaining elements in the enumerator.
nsIStringEnumerator
must be preceded by a call to hasmoreelements() which returns pr_
true.
...return value
true if there are remaining strings in the enumerator.
nsITaskbarWindowPreview
if the enablecustomdrawing attribute is
true, the controller you implement will start receiving calls to its nsitaskbarpreviewcontroller.drawpreview() and nsitaskbarpreviewcontroller.drawthumbnail() methods, as well as reads of its width, height, and thumbnailaccessratio attributes.
...method overview nsitaskbarpreviewbutton getbutton(in unsigned long index); attributes attribute type description enablecustomdrawing boolean if
true, the nsitaskbarpreviewcontroller object's nsitaskbarpreviewcontroller.drawpreview() and nsitaskbarpreviewcontroller.drawthumbnail() methods will be called to draw the preview.
nsITelemetry
this is
true if the fhr data reporting service or the self-support service is enabled.
... static -
true for histograms defined in histograms.json, false for ones defined with newhistogram().
nsITextInputProcessorCallback
focus: false, _hasrightstocompose: false, _tip: null, _callback: function simpleime_callback(atip, anotification) { try { switch (anotification.type) { case "request-to-commit": atip.commitcomposition(); 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...
... return value if this handles the notification normally or does nothing, it should return
true.
nsITransferable
islargedataset() returns
true if the data is large.
... return value
true if the data is large; otherwise, the result is false.
nsIUTF8ConverterService
set this to pr_
true only if you suspect that astring can be mistaken for ascii / utf-8 but is actually not in ascii / utf-8 so that astring has to go through the conversion.
... aallowsubstitution when
true, allow the decoder to substitute invalid input sequences by replacement characters.
nsIUTF8StringEnumerator
must be preceded by a call to hasmore(), which returns pr_
true.
...return value
true if there are remaining strings in the enumerator, otherwise false.
nsIUpdate
iscompleteupdate boolean
true if the update is a complete replacement of the existing installation; false if the update is a patch representing the difference between the new version and the existing version.
... issecurityupdate boolean
true if the update is a security update.
nsIWebNavigation
if
true this indicates that there is back session history available for navigation.
...if
true this indicates that there is forward session history available for navigation.
nsIWebProgressListener2
asameuri
true if awebprogress is requesting a refresh of the current uri.
... return value
true if the refresh may proceed.
nsIXMLHttpRequest
example code this is a simple example code for opening a simple http request from a xul application (like a mozilla extension) without using observers: var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('post', "http://www.foo.bar:8080/nietzsche.do",
true); req.send('your=data&and=more&stuff=here'); example 2 var {cu: utils, cc: classes, ci: instances} = components; cu.import('resource://gre/modules/services.jsm'); function xhr(url, cb) { let xhr = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); let handler = ev => { evf(m => xhr.removeeventlistener(m, handler, !1)); switch (ev.type)...
...); break; } default: services.prompt.alert(null, 'xhr error', 'error fetching package: ' + xhr.statustext + ' [' + ev.type + ':' + xhr.status + ']'); break; } }; let evf = f => ['load', 'error', 'abort'].foreach(f); evf(m => xhr.addeventlistener(m, handler, false)); xhr.mozbackgroundrequest =
true; xhr.open('get', url,
true); xhr.channel.loadflags |= ci.nsirequest.load_anonymous | ci.nsirequest.load_bypass_cache | ci.nsirequest.inhibit_persistent_caching; xhr.responsetype = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer.
nsIXULSortService
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void insertcontainernode(in nsirdfcompositedatasource db, in nsrdfsortstate sortstateptr, in nsicontent root, in nsicontent
trueparent, in nsicontent container, in nsicontent node, in boolean anotify); native code only!
...void insertcontainernode( in nsirdfcompositedatasource db, in nsrdfsortstate sortstateptr, in nsicontent root, in nsicontent
trueparent, in nsicontent container, in nsicontent node, in boolean anotify ); parameters db sortstateptr root
trueparent container node anotify sort() sort the contents of the widget containing anode using asortkey as the comparison key, and asorthints as how to sort.
nsIXULTemplateBuilder
return value returns
true if the node has content generated for it; otherwise returns false.
...aforcecreation if
true, the contents of the element are generated even if the element is closed; this behavior is used with menus.
nsIXULTemplateQueryProcessor
if the query processor needs to load the datasource asynchronously, it may set the ashoulddelaybuilding returned parameter to
true to delay building the template content, and call the builder's rebuild method when the data is available.
...aistrusted
true if the template is in a trusted document.
nsIXULWindow
ascreen
true to center the window relative to the screen containing arelative if arelative is not null.
...false to center it relative to arelative itself (arelative must be set in this case.) aalert
true to move the window to an alert position, generally centered horizontally and 1/3 down from the top.
nsIZipReader
return value boolean value,
true if the zip entry exists, false is it does not exist.
... { zr.open(nsifilexpi); //if file dne it throws here var entries = zr.findentries('*'); //we use asterik because we want everything listed out while (entries.hasmore()) { var entrypointer = entries.getnext(); //just a string of "zip path" (this means path to file in zip, and it uses forward slashes remember) var entry = zr.getentry(entrypointer); // should return
true on `entry instanceof ci.nsizipentry` console.log('entrypointer', entrypointer); /* console output * "entrypointer" "bootstrap.js" scratchpad/1:18 */ console.info('entry', entry); /* console output * "entry" xpcwrappednative_nohelper { queryinterface: queryinterface(), compression: getter, size: getter, realsize: getter, crc32: getter, isd...
Setting HTTP request headers
filespec, location, type); log("----------------------------> registerself"); var catmgr = components.classes["@mozilla.org/categorymanager;1"].getservice(components.interfaces.nsicategorymanager); catmgr.addcategoryentry("app-startup", this.myname, this.myprogid,
true,
true); }, getclassobject: function (compmgr, cid, iid) { log("----------------------------> getclassobject"); return this.myfactory; }, mycid: components.id("{9cf5f3df-2505-42dd-9094-c1631bd1be1c}"), myprogid: "@dougt/myhttplistener;1", myname: "simple http listener", myfactory: { queryinterface: function (aiid) { if (!a...
...sisupports) && !aiid.equals(components.interfaces.nsifactory)) throw components.results.ns_error_no_interface; return this; }, createinstance: function (outer, iid) { log("----------------------------> createinstance"); return new myhttplistener(); } }, canunload: function(compmgr) { return
true; } }; function nsgetmodule(compmgr, filespec) { return mymodule; } privacy and security good practice a use case for setting specific a http request header is to have a specific web site be able to check if a specific plugin / addon / extension is installed.
XPIDL
regular in parameters are reflected more or less normally, with numeric types all representing numbers, booleans as
true or false, the various strings (including astring et al) as a javascript string, and nsid types as a components.id instance.
...native code should pay particular attention to not passing in null values for out parameters (although some parts of the codebase are known to violate this, it is strictly enforced at the js<->native barrier), and also ensuring that boolean types only receive values of 0 (false) or 1 (
true).
Xray vision
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.
...+ ' this.address = {"street" : "main street"};' + ' this.fullname = function() {' + ' return this.firstname + " " + this.lastname;'+ ' };' + '};' + 'var me = new person();' + 'object.defineproperty(me, "lastname", {' + ' enumerable:
true,' + ' configurable:
true,' + ' writable:
true,' + ' value: "smith"' + '});' + 'object.defineproperty(me, "middlename", {' + ' enumerable:
true,' + ' configurable:
true,' + ' get: function() { return "wait, is this really a getter?"; ...
Creating a gloda message query
(use nsimsgtagservice to access message tags.) query.starred(
true/false): add the constraint that the message must be (or not be) starred (flagged).
... query.read(
true/false): add the constraint that the message must be (or not be) marked as read.
Filelink Providers
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.
Mail composition back end
sage 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.
...if the setting for getfcc() is set to
true, the copy operation is automatically performed after a successful send operation.
Mail event system
rmovemessages sample code in this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintpropertychanged(item, property, oldvalue, newvalue) { listenerhasfired=
true; var propertystring = property.getunicode(); dump("onintpropertychanged has fired with property + " + propertystring + "!\n"); if (propertystring == "totalmessages") { totalmessageslistenerhasfired=
true; //now show us visually var folder = item.queryinterface(components.interfaces.nsimsgfolder); dump("the folder " + folder.prettyname + " now has " + newvalu...
...then we could // verify that our listener fired by checking if listenerhasfired and // totalmessageslistenerhasfired are
true // this is left as an exercise for the reader.
Creating a Custom Column
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!
...mcolumnhandler 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, all we are doing here is making sure that both the text that is displayed to the user (getcelltext()) and the string we sort according to (when the user decided to sort t...
Filter Incoming Mail
ghdr.isread ) { // here we are, a new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false,
true); // here with have a string to modify with javascript.
...ect = mimeconvert.encodemimepartiistr_utf8(subject, false, "utf-8", 0, 72); } } }; function init() { var notificationservice = components.classes["@mozilla.org/messenger/msgnotificationservice;1"] .getservice(components.interfaces.nsimsgfoldernotificationservice); notificationservice.addlistener(newmaillistener, notificationservice.msgadded); } addeventlistener("load", init,
true); have a look to nsimsgdbhdr to get the full list of properties to be modified.
Using the Multiple Accounts API
- boolean, should we download new messags on biff (
true) or just alert user that there is new mail (false) preference: mail.server.server.directory - local platform-specific path to store messages and folder indexes preference: mail.server.server.name - user-visible name of server the following are specific to imap: preference: mail.server.server.admin_url - administration url for server preference: mail.server.server.using_subscriptio...
...(replyto: header in mail messages) preference: mail.identity.identity.organization - user's organization (organization: header in mail messages) preference: mail.identity.identity.compose_html - boolean, should we compose messages in html (
true) or plain text (false)?
Drawing and Event Handling - Plugins
if you want to make an opaque windowless plug-in transparent, call the npn_setvalue method and set nppvplugintransparentbool to the value
true.
...the plug-in must return
true from npp_handleevent if it has handled the event and false if it has not.
URLs - Plugins
to post a file, set the flag file to
true, the buffer buf to the path name string for a file, and len to the length of the path string.
...this example uploads a file from the root of the local file system to an ftp server and displays the response in a frame named response: char* mydata = "file:///c\/mydirectory/myfilename"; uint32 mylength = strlen(mydata) + 1; err = npn_posturl(instance, "ftp://fred@ftp.example.com/pub/", "response", mylength, mydata,
true); sending mail a plug-in can send an email message using npn_posturl or npn_posturlnotify.
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
visit the url about:config, and set the devtools.chrome.enabled preference to
true: setting the 'devtools.chrome.enabled' preference open a developer scratchpad (menu button > developer > scratchpad), and select "browser" from the "environment" menu.
... dbg.memory.trackingallocationsites =
true; } window.demoplotallocations = function() { // grab the allocation log.
Page inspector 3-pane mode - Firefox Developer Tools
enabling the 3-pane inspector pre-firefox 62 in earlier versions of firefox (since firefox 59/60), you can enable 3 pane mode in release/beta by going to about:config and flipping the following prefs to
true: devtools.inspector.split-rule-enabled — this switches 3-pane mode on and off.
... in firefox 61, these preferences got renamed to: devtools.inspector.three-pane-enabled devtools.inspector.three-pane-toggle you need to flip these two to
true in release/beta to test the feature in firefox 61.
Waterfall - Firefox Developer Tools
for example, suppose we have code like this: var iterations = 70; var multiplier = 1000000000; function calculateprimes() { console.time("calculating..."); 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); } } console.timeend("calculating..."); return primes; } the waterfall's output will look something like this: the marker is labeled with the argument you passed to ...
...e a timestamp every 10 iterations of the loop, labeled with the iteration number: var iterations = 70; var multiplier = 1000000000; function calculateprimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { if (i % 10 == 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: ...
Settings - Firefox Developer Tools
if common preferences is not included in the settings, web console logs can be persisted by using the 'about:config' url in browser address bar, searching for: 'devtools.webconsole.persistlog' then toggling this value to
true inspector show browser styles a setting to control whether styles applied by the browser (user-agent styles) should be displayed in the inspector's rules view.
... note: this option got removed from the ui in firefox 56, because this version ships with a new debugger ui, but it can still be enabled for the old ui by setting the preference devtools.debugger.workers to
true.
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.
... syntax var iscollpased = range.collapsed value a boolean value which is
true if the range is collapsed.
AddressErrors - Web APIs
", "debit"] } } ]; let defaultpaymentdetails = { total: {label: 'donation', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected:
true } ] }; supportedhandlers describes the supported payment handlers and the details for those.
... let request; function process() { let options = {requestshipping:
true}; try { request = new paymentrequest(supportedhandlers, defaultpaymentdetails, options); // add event listeners here.
AnimationEvent.initAnimationEvent() - Web APIs
canbubblearg a boolean flag indicating if the event can bubble (
true) or not (false).
... cancelablearg a boolean flag indicating if the event associated action can be avoided (
true) or not (false).
AudioBufferSourceNode.loop - Web APIs
syntax var loopingenabled = audiobuffersourcenode.loop; audiobuffersourcenode.loop =
true | false; value a boolean which is
true if looping is enabled; otherwise, the value is false.
... you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop =
true; }, function(e){"er...
AudioBufferSourceNode - Web APIs
audiobuffersourcenode.loopstart optional a floating-point value indicating the time, in seconds, at which playback of the audiobuffer must begin when loop is
true.
... audiobuffersourcenode.loopend optional a floating-point number indicating the time, in seconds, at which playback of the audiobuffer stops and loops back to the time indicated by loopstart, if loop is
true.
BaseAudioContext.createPeriodicWave() - Web APIs
constraints optional an dictionary object that specifies whether normalization should be disabled (if not specified, normalization is enabled by default.) it takes one property: disablenormalization: if set to
true, normalization is disabled for the periodic wave.
... var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization:
true}); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a sine wave here, we create a periodicwave with two values.
BasicCardRequest.supportedNetworks - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
BasicCardResponse.billingAddress - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
BasicCardResponse.cardNumber - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
BasicCardResponse.cardSecurityCode - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
BasicCardResponse.cardholderName - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
BasicCardResponse.expiryMonth - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
BasicCardResponse.expiryYear - Web APIs
ort noedge no support ≤18 — 79firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 57firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
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".
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).
CSS.supports() - Web APIs
return value
true if the browser supports the rule, otherwise false.
... examples result = css.supports("text-decoration-style", "blink"); result = css.supports("display: flex"); result = css.supports("(--foo: red)"); result = css.supports(`(transform-style: preserve) or (-moz-transform-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve)`); // result is
true or false specification specification status comment css conditional rules module level 3the definition of 'css: supports()' in that specification.
CSSNumericValue.equals() - Web APIs
to return a value of
true, all passed values must be of the same type and value and must be in the same order.
... let cssmathsum = new cssmathsum(css.px(1), css.px(2)); let matchingcssmathsum = new cssmathsum(css.px(1), css.px(2)); // prints
true console.log(cssmathsum.equals(matchingcssmathsum)); let othercssmathsum = cssmathsum(css.px(2), css.px(1)); // prints false console.log(cssmathsum.equals(othercssmathsum)); // also prints false console.log(css.cm("1").equal(css.in("0.393701"))); specifications specification status comment css typed om level 1the definition of 'equals' 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.
CacheStorage - Web APIs
cachestorage.has() returns a promise that resolves to
true if a cache object matching the cachename exists.
... cachestorage.open() returns a promise that resolves to the cache object matching the cachename (a new cache is created if it doesn't already exist.) cachestorage.delete() finds the cache object matching the cachename, and if found, deletes the cache object and returns a promise that resolves to
true.
CanvasRenderingContext2D.ellipse() - Web APIs
anticlockwise optional an optional boolean which, if
true, draws the ellipse anticlockwise (counter-clockwise).
... = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'red'; ctx.beginpath(); ctx.ellipse(60, 75, 50, 30, math.pi * .25, 0, math.pi * 1.5); ctx.fill(); ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.ellipse(150, 75, 50, 30, math.pi * .25, 0, math.pi); ctx.fill(); ctx.fillstyle = 'green'; ctx.beginpath(); ctx.ellipse(240, 75, 50, 30, math.pi * .25, 0, math.pi,
true); ctx.fill(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.ellipse' in that specification.
ConvolverNode.normalize - Web APIs
its default value is
true in order to achieve a more uniform output level from the convolver, when loaded with diverse impulse responses.
... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg',
true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
DOMMatrix - Web APIs
is2d read only a boolean flag whose value is
true if the matrix was initialized as a 2d matrix.
... isidentity read only a boolean whose value is
true if the matrix is the identity matrix.
DOMMatrixReadOnly - Web APIs
is2d read only a boolean flag whose value is
true if the matrix was initialized as a 2d matrix.
... isidentity read only a boolean whose value is
true if the matrix is the identity matrix.
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.replace() - Web APIs
return value a boolean value, which is
true if oldtoken was successfully replaced, or false if not.
...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.supports() - Web APIs
the supports() method of the domtokenlist interface returns
true if a given token is in the associated attribute's supported tokens.
... syntax let
trueorfalse = element.supports(token) parameters token a domstring containing the token to query for.
DOMTokenList.toggle() - Web APIs
if token doesn't exist it's added and the function returns
true.
...if set to
true, then token will only be added, but not removed.
DOMTokenList - Web APIs
domtokenlist.contains(token) returns
true if the list contains the given token, otherwise false.
... domtokenlist.supports(token) returns
true if a given token is in the associated attribute's supported tokens.
DataTransfer.clearData() - Web APIs
html <span class="tweaked" id="source" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.
...tener('dragleave', dragleavehandler); dropable.removeeventlistener('drop', drophandler); } } function dragoverhandler (event) { status.innerhtml = 'drop available'; event.preventdefault(); } function dragleavehandler (event) { status.innerhtml = 'drag in process (drop was available)'; event.preventdefault(); } function drophandler (event) { dropped =
true; status.innerhtml = 'drop done'; event.preventdefault(); // get data linked to event format « text » var _data = event.datatransfer.getdata('text/plain'); var element = document.getelementbyid(_data); // append drag source element to event's target element event.target.appendchild(element); // change css styles and displayed text element.style.csstext = ...
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.
Detecting device orientation - Web APIs
window.addeventlistener("deviceorientation", handleorientation,
true); after registering your event listener (in this case, a javascript function called handleorientation()), your listener function periodically gets called with updated orientation data.
... processing motion events motion events are handled the same way as the orientation events except that they have their own event's name: devicemotion window.addeventlistener("devicemotion", handlemotion,
true); what's really changed are the information provided within the devicemotionevent object passed as a parameter of the handlemotion function.
DisplayMediaStreamConstraints.audio - Web APIs
this value may simply be a boolean, where
true indicates that an audio track should be included an false (the default) indicates that no audio should be included in the stream.
... 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.
DisplayMediaStreamConstraints.video - Web APIs
this value may simply be a boolean, where
true specifies that a default selection of input source be made (typically the entire display area of the device in use, spanning every screen in a multiple screen configuration).
... 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.fullscreen - Web APIs
syntax var isfullscreen = document.fullscreen; value a boolean value which is
true if the document is currently displaying an element in full-screen mode; otherwise, the value is false.
... 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.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.
DocumentOrShadowRoot.fullscreenElement - Web APIs
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.
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
* * @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.
... * @return
true if the node is: * 1) a |text| node that is all whitespace * 2) a |comment| node * and otherwise false.
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).
Element: blur event - Web APIs
nput[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event delegation there are two ways of implementing event delegation for this event: by using the focusout event, or by setting the usecapture parameter of addeventlistener() to
true.
... html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; },
true); form.addeventlistener('blur', (event) => { event.target.style.background = ''; },
true); result specifications specification status comment ui events working draft added info that this event is composed.
Element: focus event - Web APIs
input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event delegation there are two ways of implementing event delegation for this event: by using the focusin event, or by setting the usecapture parameter of addeventlistener() to
true.
... html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; },
true); form.addeventlistener('blur', (event) => { event.target.style.background = ''; },
true); result specifications specification status comment ui events working draft added info that this event is composed.
Element: paste event - Web APIs
bubbles yes cancelable yes interface clipboardevent event handler property onpaste if the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to
true) then the default action is to insert the contents of the clipboard into the document at the cursor position.
... examples live example html <div class="source" contenteditable="
true">try copying text from this box...</div> <div class="target" contenteditable="
true">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const target = document.queryselector('div.target'); target.addeventlistener('paste', (event) => { let paste = (eve...
Element.scrollIntoViewIfNeeded() - Web APIs
syntax todo parameters opt_center is an optional boolean value with a default value of
true: if
true, the element will be aligned so it is centered within the visible area of the scrollable ancestor.
... example var element = document.getelementbyid("my-el"); element.scrollintoviewifneeded(); element.scrollintoviewifneeded(
true); // centers the element in the visible area specifications not part of any specification.
Element.toggleAttribute() - Web APIs
return value
true if attribute name is eventually present, and false otherwise.
... 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.
Event.bubbles - Web APIs
syntax var doesitbubble = event.bubbles; value a boolean, which is
true if the event bubbles up through the dom.
...events that do bubble have this property set to
true.
Event.cancelBubble - Web APIs
setting its value to
true before returning from an event handler prevents propagation of the event.
... example elem.onclick = function(event) { // do cool things here event.cancelbubble =
true; } specifications specification status comment domthe definition of 'cancelbubble' in that specification.
Event.returnValue - Web APIs
it is set to
true by default, allowing the default action to occur.
... 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.
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.
Using Fetch - Web APIs
an accurate check for a successful fetch() would include checking that the promise resolved, then checking that the response.ok property has a value of
true.
...('x-custom-header', 'processthisimmediately'); the same can be achieved by passing an array of arrays or an object literal to the constructor: const myheaders = new headers({ 'content-type': 'text/plain', 'content-length': content.length.tostring(), 'x-custom-header': 'processthisimmediately' }); the contents can be queried and retrieved: console.log(myheaders.has('content-type')); //
true console.log(myheaders.has('set-cookie')); // false myheaders.set('content-type', 'text/html'); myheaders.append('x-custom-header', 'anothervalue'); console.log(myheaders.get('content-length')); // 11 console.log(myheaders.get('x-custom-header')); // ['processthisimmediately', 'anothervalue'] myheaders.delete('x-custom-header'); console.log(myheaders.get('x-custom-header')); // [ ] some of the...
FileSystemEntry - Web APIs
isdirectory read only a boolean which is
true if the entry represents a directory; otherwise, it's false.
... isfile read only a boolean which is
true if the entry represents a file.
FileSystemEntrySync - Web APIs
isdirectory readonly boolean
true if filesystementrysync is a directory.
... isfile readonly boolean
true if the filesystementrysync is a file.
FontFaceSet.check() - Web APIs
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.
Gamepad.buttons - Web APIs
each gamepadbutton object has two properties: pressed and value: the pressed property is a boolean indicating whether the button is currently pressed (
true) or unpressed (false).
...ion gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed ==
true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed ==
true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed ==
true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed ==
true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = raf(gameloop); }; value an array of gam...
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).
... syntax var ispressed = navigator.getgamepads()[0].pressed; example var gp = navigator.getgamepads()[0]; // get the first gamepad object if(gp.buttons[0].pressed ==
true) { // respond to button being pressed } value a boolean.
GamepadButton - Web APIs
gamepadbutton.pressed read only a boolean value indicating whether the button is currently pressed (
true) or unpressed (false).
...ion gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed ==
true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed ==
true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed ==
true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed ==
true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = raf(gameloop); }; specifications ...
GeolocationCoordinates - Web APIs
this value, specified in degrees, indicates how far off from heading
true north the device is.
... 0 degrees represents
true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees).
GlobalEventHandlers.onerror - Web APIs
these error events do not bubble up to window, but (at least in firefox) can be handled with a window.addeventlistener configured with usecapture set to
true.
... 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.
GlobalEventHandlers.onkeypress - Web APIs
*/ (function () { const ssecret = /* choose your hidden word...: */ "exit"; let 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.
HTMLCanvasElement.getContext() - Web APIs
this option is only available, if the flag gfx.canvas.willreadfrequently.enable is set to
true (which, by default, is only the case for b2g/firefox os).
... preservedrawingbuffer: if the value is
true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
HTMLDialogElement.open - Web APIs
syntax dialoginstance.open =
true; var myopenvalue = dialoginstance.open; value a boolean representing the state of the open html attribute.
...
true means it is set, and therefore the dialog is shown.
HTMLElement.contentEditable - Web APIs
this enumerated attribute can have the following values: '
true' indicates that the element is contenteditable.
... syntax editable = element.contenteditable element.contenteditable = '
true' specifications specification status comment html living standardthe definition of 'contenteditable' in that specification.
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.
... syntax editable = element.iscontenteditable example html <p id="mytext1">uneditable paragraph</p> <p id="mytext2" contenteditable="
true">editable paragraph</p> <p id="infotext1">can edit the first paragraph?
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.
HTMLFormElement - Web APIs
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.
HTMLImageElement.alt - Web APIs
you should never use alt for text that could be cons
trued as a caption or title.
...this is
true whether the /me image is in a bitmapped format such as png or jpeg or in a vector format like svg.
HTMLImageElement.complete - Web APIs
syntax let doneloading = htmlimageelement.complete; value a boolean value which is
true if the image has completely loaded; otherwise, the value is false.
... the image is considered completely loaded if any of the following are
true: neither the src nor the srcset attribute is specified.
HTMLImageElement.currentSrc - Web APIs
45edge full support 13firefox full support 38 full support 38 no support 32 — 52disabled disabled from version 32 until version 52 (exclusive): this feature is behind the dom.image.srcset.enabled preference (needs to be set to
true).
... android full support 45firefox android full support 38 full support 38 no support 32 — 52disabled disabled from version 32 until version 52 (exclusive): this feature is behind the dom.image.srcset.enabled preference (needs to be set to
true).
HTMLImageElement.srcset - Web APIs
34edge full support 12firefox full support 38 full support 38 no support 32 — 52disabled disabled from version 32 until version 52 (exclusive): this feature is behind the dom.image.srcset.enabled preference (needs to be set to
true).
... android full support 34firefox android full support 38 full support 38 no support 32 — 52disabled disabled from version 32 until version 52 (exclusive): this feature is behind the dom.image.srcset.enabled preference (needs to be set to
true).
HTMLImageElement - Web APIs
htmlimageelement.complete read only returns a boolean that is
true if the browser has finished fetching the image, whether successful or not.
... that means this value is also
true if the image has no src value indicating an image to load.
HTMLMediaElement.autoplay - Web APIs
a media element whose source is a mediastream and whose autoplay property is
true will begin playback when it becomes active (that is, when mediastream.active becomes
true).
... syntax htmlmediaelement.autoplay =
true | false; var autoplay = htmlmediaelement.autoplay; value a boolean whose value is
true if the media element will begin playback as soon as enough content has loaded to allow it to do so without interruption.
HTMLMediaElement.ended - Web APIs
syntax var isended = htmlmediaelement.ended value a boolean which is
true if the media contained in the element has finished playing.
... if the source of the media is a mediastream, this value is
true if the value of the stream's active property is false.
HTMLMediaElement.loop - Web APIs
syntax var loop = video.loop; audio.loop =
true; value a boolean.
... example var obj = document.createelement('video'); obj.loop =
true; //
true specifications specification status comment html living standardthe definition of 'htmlmediaelement.loop' in that specification.
HTMLMediaElement.paused - Web APIs
true is paused and false is not paused.
... example var obj = document.createelement('video'); console.log(obj.paused); //
true specifications specification status comment html living standardthe definition of 'htmlmediaelement.paused' in that specification.
HTMLMediaElement.srcObject - Web APIs
const mediastream = await navigator.mediadevices.getusermedia({video:
true}); const video = document.createelement('video'); video.srcobject = mediastream; in this example, a new mediasource is assigned to a newly-created <video> element.
... const mediastream = await navigator.mediadevices.getusermedia({video:
true}); const video = document.createelement('video'); if ('srcobject' in video) { video.srcobject = mediastream; } else { // avoid using this in new browsers, as it is going away.
HTMLMediaElement - Web APIs
true if the audio is muted and false otherwise.
... play fired when the paused property is changed from
true to false, as a result of the htmlmediaelement.play() method, or the autoplay attribute playing fired when playback is ready to start after having been paused or delayed due to lack of data progress fired periodically as the browser loads a resource.
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.
HTMLElement.focus() - Web APIs
if preventscroll is set to
true, no scrolling will occur.
...ton> <p></p> <button type="button" onclick="focusmethod()">click me to focus on the button!</button> result focus with focusoption javascript focusscrollmethod = function getfocus() { document.getelementbyid("mybutton").focus({preventscroll:false}); } focusnoscrollmethod = function getfocuswithoutscrolling() { document.getelementbyid("mybutton").focus({preventscroll:
true}); } html <button type="button" onclick="focusscrollmethod()">click me to focus on the button!</button> <button type="button" onclick="focusnoscrollmethod()">click me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" id="mybutton" style="margin-top: 500px;">click me!</button> </div> result specification...
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.
...the available options are: flatten: a boolean indicating whether to return the assigned nodes of any available child <slot> elements (
true) or not (false).
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 the flatten option is set to
true, it also returns the assigned elements of any other slots that are descendants of this slot.
HTMLStyleElement.scoped - Web APIs
the htmlstyleelement.scoped property is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (
true).
... syntax value = style.scoped; style.scoped =
true; ...
HTMLStyleElement - Web APIs
htmlstyleelement.disabled is a boolean value representing whether or not the stylesheet is disabled (
true) or not (false).
... 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).
HTMLVideoElement.msHorizontalMirror - Web APIs
syntax htmlvideoelement.mshorizontalmirror: boolean; value boolean value set to
true flips the video playback horizontally.
... example var myvideo = document.getelementbyid("videotag1"); myvideo.mshorizontalmirror =
true; myvideo.play(); example #2: var flip = document.queryselector('#flip'); flip.addeventlistener('click', function() { video.mshorizontalmirror =
true; }); see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
effectrequired a boolean which if set to
true requires a video effect to be defined.
... example var ovideo1 = document.getelementbyid("video1"); ovideo1.msinsertvideoeffect("windows.media.videoeffects.videostabilization",
true, null); see also htmlvideoelement microsoft api extensions ...
HTML Drag and Drop API - Web APIs
// add the target element's id to the data transfer object ev.datatransfer.setdata("text/plain", ev.target.id); } window.addeventlistener('domcontentloaded', () => { // get the element by id const element = document.getelementbyid("p1"); // add the ondragstart event listener element.addeventlistener("dragstart", dragstart_handler); }); </script> <p id="p1" draggable="
true">this element is draggable.</p> for more information, see: draggable attribute reference drag operations guide define the drag's data the application is free to include any number of data items in a drag operation.
...ransfer.dropeffect = "move"; } function dragover_handler(ev) { ev.preventdefault(); ev.datatransfer.dropeffect = "move" } function drop_handler(ev) { ev.preventdefault(); // get the id of the target and add the moved element to the target's dom const data = ev.datatransfer.getdata("application/my-app"); ev.target.appendchild(document.getelementbyid(data)); } </script> <p id="p1" draggable="
true" ondragstart="dragstart_handler(event)">this element is draggable.</p> <div id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">drop zone</div> for more information, see: performing a drop drag end at the end of a drag operation, the dragend event fires at the source element — the element that was the target of the drag start.
IDBDatabase.createObjectStore() - Web APIs
autoincrement if
true, the object store has a key generator.
... invalidaccesserror if autoincrement is set to
true and keypath is either an empty string or an array containing an empty string.
IDBIndex.multiEntry - Web APIs
this method takes an optional options parameter whose multientry property is set to
true/false.
... syntax var ismultientry = myindex.multientry; value a boolean: value effect
true there is one record in the index for each item in an array of keys.
IDBIndex.unique - Web APIs
this method takes an optional parameter, unique, which if set to
true means that the index will not be able to accept duplicate entries.
... syntax var isunique = idbindex.unique; value a boolean: value effect
true the current index does not allow duplicate values for a key.
IDBIndex - Web APIs
if
true, there is one record in the index for each item in an array of keys.
... idbindex.unique read only if
true, this index does not allow duplicate values for a key.
IDBKeyRange.includes() - Web APIs
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.
...bkeyrange.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.
IDBKeyRange.lower - Web APIs
here we declare keyrangevalue = idbkeyrange.upperbound("f", "w",
true,
true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (
true).
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w",
true,
true); console.log(keyrangevalue.lower); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.f...
IDBKeyRange.upper - Web APIs
here we declare keyrangevalue = idbkeyrange.upperbound("f", "w",
true,
true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (
true).
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w",
true,
true); console.log(keyrangevalue.upper); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.f...
IDBObjectStoreSync - Web APIs
unique if
true, keys in the index must be unique; if false, duplicate keys are allowed.
... exceptions this method can raise an idbdatabaseexception with the following codes: constraint_err if nooverwrite was
true, and a record exists in this index for the given key or this index is auto-populated; or if no record exists with the given key in the index's referenced object store.
IdleDeadline.didTimeout - Web APIs
if didtimeout is
true, the idledeadline object's timeremaining() method will return approximately 0.
... syntax var timedout = idledeadline.didtimeout; value a boolean which is
true if the callback is running due to the callback's timeout period elapsing or false if the callback is running because the user agent is idle and is offering time to the callback.
IntersectionObserverEntry - Web APIs
intersectionobserverentry.isintersecting read only a boolean value which is
true if the target element intersects with the intersection observer's root.
... if this is
true, then, the intersectionobserverentry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting.
KeyboardEvent.code - Web APIs
"output"> </div> css #output { font-family: arial, helvetica, sans-serif; border: 1px solid black; } javascript window.addeventlistener("keydown", function(event) { let str = "keyboardevent: key='" + event.key + "' | code='" + event.code + "'"; let el = document.createelement("span"); el.innerhtml = str + "<br/>"; document.getelementbyid("output").appendchild(el); },
true); try it out to ensure that keystrokes go to the sample, click in the output box below before pressing keys.
...se "arrowup": // handle "forward" updateposition(moverate); break; case "keya": case "arrowleft": // handle "turn left" angle -= turnrate; break; case "keyd": case "arrowright": // handle "turn right" angle += turnrate; break; } refresh(); // consume the event so it doesn't get handled twice event.preventdefault(); },
true); try it out to ensure that keystrokes go to the sample code, click inside the black game play field below before pressing keys.
LayoutShift - Web APIs
layoutshift.hadrecentinput returns
true if there was a user input in the past 500 milliseconds.
... if (!entry.hadrecentinput) { cumulativelayoutshiftscore += entry.value; } } }); observer.observe({type: 'layout-shift', buffered:
true}); document.addeventlistener('visibilitychange', () => { if (document.visibilitystate === 'hidden') { // force any pending records to be dispatched.
LockedFile.getMetadata() - Web APIs
each key is a boolean where
true means the metadata is expected and where false means it is not expected.
... note that if the key is undefined, it is considered as if it were
true.
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.
... syntax var matches = <varm>mediaquerylist.matches; value a boolean which is
true if the document currently matches the media query list; otherwise, it's false.
MediaQueryList - Web APIs
when the media query test starts or stops evaluating to
true).
... matchesread only a boolean that returns
true if the document currently matches the media query list, or false if not.
MediaQueryListEvent.MediaQueryListEvent() - Web APIs
matches: a boolean representing the media query status —
true if it matches, false if not.
... examples var media = '(max-width: 600px)'; var matches =
true; var mymediaquerylistevent = new mediaquerylistevent({media, matches}); specifications specification status comment css object model (cssom) view modulethe definition of 'mediaquerylistevent()' in that specification.
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: dataavailable event - Web APIs
var chunks = []; mediarecorder.addeventlistener('stop', (event) => { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls =
true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); }); mediarecorder.addeventlistener('dataavailable', (event) => { chunks.push(event.data); }); ...
... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls =
true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
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 - Web APIs
example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio:
true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecorder = new mediarecorder(stream); visualize(stream); record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); console.log("recorder started"); record.style.background = "red"; record.style.color = "black"; ...
...document.createelement('button'); clipcontainer.classlist.add('clip'); audio.setattribute('controls', ''); deletebutton.innerhtml = "delete"; cliplabel.innerhtml = clipname; clipcontainer.appendchild(audio); clipcontainer.appendchild(cliplabel); clipcontainer.appendchild(deletebutton); soundclips.appendchild(clipcontainer); audio.controls =
true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audiourl = url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); deletebutton.onclick = function(e) { evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } mediarecorder.ondataavailable =...
MediaSessionActionDetails.fastSeek - Web APIs
the boolean property fastseek in the mediasessionactiondetails dictionary is an optional value which, when specified and
true, indicates that the requested seekto operation is part of an ongoing series of seekto operations.
... syntax let mediasessionactiondetails = { fastseek: shouldfastseek }; let shouldfastseek = mediasessionactiondetails.fastseek; value a boolean which is
true if the action is part of an ongoing series of seek actions which should be treated as part of an overall seek operation.
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.
... return value a boolean which is
true if the browser feels that it can probably play media of the specified type.
MediaStream.ended - Web APIs
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 - Web APIs
mediastream.active read only a boolean value that returns
true if the mediastream is active, or false otherwise.
... mediastream.ended read only a boolean value set to
true if the end of the stream has been reached.
MediaStreamTrack.enabled - Web APIs
the enabled property on the mediastreamtrack interface is a boolean value which is
true if the track is allowed to render the source stream or false if it is not.
... syntax const enabledflag = track.enabled track.enabled = [
true | false] value when
true, enabled indicates that the track is permitted to render its actual media to the output.
MediaTrackConstraints.cursor - Web APIs
for example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertfakecursorflag = false; if (displaystream.getvideotracks()[0].getsettings().cursor === "never") { insertfakecursorflag =
true; } following this code, insertfakecursorflag is
true if there's no cursor rendered into the stream already.
... later code can detect this flag's value and if it's
true, can manually look at some metadata that might be provided and insert a fake representation of the cursor at the correct position.
MediaTrackConstraints.logicalSurface - Web APIs
syntax var constraintsobject = { logicalsurface: constraint }; constraintsobject.logicalsurface = constraint; value a constrainboolean which is
true if logical surfaces should be permitted among the selections available to the user.
... for example, if your app needs to know if the selected display surface is a logical one: let islogicalsurface = displaystream.getvideotracks()[0].getsettings().logicalsurface; following this code, islogicalsurface is
true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen.
MediaTrackSettings.logicalSurface - Web APIs
syntax islogicalsurface = mediatracksettings.logicalsurface; value a boolean value which is
true if the video track in the stream of captured video is taken from a logical display surface.
... for example, a user agent may choose to allow the user to choose whether to share the entire document (a browser with logicalsurface value of
true), or just the currently visible portion of the document (where the logicalsurface of the browser surface is false).
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.
... syntax aspectconstraintsupported = supportedconstraintsdictionary.aspectratio; value this property is present in the dictionary (and its value is always
true) 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.
... syntax autogainsupported = supportedconstraintsdictionary.autogaincontrol; value this property is present in the dictionary (and its value is always
true) 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.
... syntax channelcountconstraintsupported = supportedconstraintsdictionary.channelcount; value this property is present in the dictionary (and its value is always
true) if the user agent supports the channelcount constraint.
MediaTrackSupportedConstraints.deviceId - Web APIs
the mediatracksupportedconstraints dictionary's deviceid property is a read-only boolean value which is present (and set to
true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the deviceid constraint.
... syntax deviceidconstraintsupported = supportedconstraintsdictionary.deviceid; value this property is present in the dictionary (and its value is always
true) if the user agent supports the deviceid constraint.
MediaTrackSupportedConstraints.echoCancellation - Web APIs
the mediatracksupportedconstraints dictionary's echocancellation property is a read-only boolean value which is present (and set to
true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the echocancellation constraint.
... syntax echocancellationconstraintsupported = supportedconstraintsdictionary.echocancellation; value this property is present in the dictionary (and its value is always
true) 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.
... syntax facingmodeconstraintsupported = supportedconstraintsdictionary.facingmode; value this property is present in the dictionary (and its value is always
true) 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.
... if this property is present, its value is always
true.
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.
... syntax groupidconstraintsupported = supportedconstraintsdictionary.groupid; value this property is present in the dictionary (and its value is always
true) 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.
... syntax heightconstraintsupported = supportedconstraintsdictionary.height; value this property is present in the dictionary (and its value is always
true) 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.
... syntax latencyconstraintsupported = supportedconstraintsdictionary.latency; value this property is present in the dictionary (and its value is always
true) if the user agent supports the latency constraint.
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.
... syntax noisesuppressionsupported = supportedconstraintsdictionary.noisesuppression; value this property is present in the dictionary (and its value is always
true) if the user agent supports the noisesuppression constraint (and therefore supports noise suppression on audio tracks).
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.
... syntax samplerateconstraintsupported = supportedconstraintsdictionary.samplerate; value this property is present in the dictionary (and its value is always
true) 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.
... syntax samplesizeconstraintsupported = supportedconstraintsdictionary.samplesize; value this property is present in the dictionary (and its value is always
true) 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.
... syntax volumeconstraintsupported = supportedconstraintsdictionary.volume; value this property is present in the dictionary (and its value is always
true) 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.
... syntax widthconstraintsupported = supportedconstraintsdictionary.width; value this property is present in the dictionary (and its value is always
true) if the user agent supports the width constraint.
Transcoding assets for Media Source Extensions - Web APIs
while this is
true on paper, browser support varies for specific container/codec combinations.
... to check if the browser supports a particular container, you can pass a string of the mime type to the mediasource.istypesupported method: mediasource.istypesupported('audio/mp3'); // false mediasource.istypesupported('video/mp4'); //
true mediasource.istypesupported('video/mp4; codecs="avc1.4d4028, mp4a.40.2"'); //
true the string is the mime type of the container, optionally followed by a list of codecs.
msIsBoxed - Web APIs
returns
true if the video is in letterbox or pillarbox mode.
... syntax isboxed = object.msisboxed value boolean value set to
true activates boxed mode for the video player.
MutationObserver.MutationObserver() - Web APIs
const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist:
true, attributes:
true, // omit (or set to false) to observe only changes to the parent node subtree:
true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); the desired subtree is located by finding an element with the id someelement.
...in it, we specify values of
true for both childlist and attributes, so we get the information we want.
Navigator.canShare() - Web APIs
the navigator.canshare() method of the web share api returns
true if a call to navigator.share() would succeed.
...
true if data can be shared with navigator.share().
Navigator.cookieEnabled - Web APIs
syntax var cookieenabled = navigator.cookieenabled; cookieenabled is a boolean:
true or false.
... note: when the browser is configured to block third-party cookies, and navigator.cookieenabled is invoked inside a third-party iframe, it returns
true in safari, edge spartan and ie (while trying to set a cookie in such scenario would fail).
Navigator.mozIsLocallyAvailable() - Web APIs
ifoffline allows you to specify whether or not the offline resources cache should be checked; specify
true to consider the offline resources cache.
... example var available = navigator.mozislocallyavailable("my-image-file.png",
true); if (available) { /* the offline resource is present */ } else { console.log("certain needed resources are not available offline"); } specifications not part of any specifications.
Navigator - Web APIs
navigator.cookieenabled read only returns false if setting a cookie will be ignored and
true otherwise.
... standard navigator.canshare() returns
true if a call to navigator.share() would succeed.
Node.getRootNode() - Web APIs
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).
....nodename); // #document // create a shadowroot var shadowroot = shadowhost.attachshadow({mode:'open'}); shadowroot.innerhtml = '<style>div{background:#2bb8aa;}</style>' + '<div class="js-shadowchild">content</div>'; var shadowchild = shadowroot.queryselector('.js-shadowchild'); // the default value of composed is false console.log(shadowchild.getrootnode() === shadowroot); //
true console.log(shadowchild.getrootnode({composed:false}) === shadowroot); //
true console.log(shadowchild.getrootnode({composed:
true}).nodename); // #document </script> specifications specification status comment domthe definition of 'getrootnode()' in that specification.
Node - Web APIs
node.isdefaultnamespace() 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.
...ode(parentnode, function(node){ if (endscan) { return false } // ignore anything which isn't a text node if (node.nodetype !== node.text_node) { return } if (typeof pattern === "string") { if (-1 !== node.textcontent.indexof(pattern)) { matches.push(node) } } else if (pattern.test(node.textcontent)) { if (!pattern.global) { endscan =
true matches = node } else { matches.push(node) } } }) return matches } for example, to find text nodes that contain typos: const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"] const pattern = new regexp("\\b(" + typos.join("|") + ")\\b", "gi") const mistakes = grep(document.body, pattern) console.log(mistakes) specifications spec...
NodeList - Web APIs
for...of loops will loop over nodelist objects correctly: const list = document.queryselectorall('input[type=checkbox]'); for (let checkbox of list) { checkbox.checked =
true; } recent browsers also support iterator methods (foreach()) as well as entries(), values(), and keys().
... there is also an internet explorer-compatible way to use array.prototype.foreach for iteration: const list = document.queryselectorall('input[type=checkbox]'); array.prototype.foreach.call(list, function (checkbox) { checkbox.checked =
true; }); specifications specification status comment domthe definition of 'nodelist' in that specification.
Notification.renotify - Web APIs
false is the default;
true makes the notification renotify the user.
... var options = { body: 'do you like my body?', renotify:
true } var n = new notification('test notification',options); console.log(n.renotify) // should log
true specifications specification status comment notifications apithe definition of 'renotify' in that specification.
Notification.silent - Web APIs
false is the default;
true makes the notification silent.
... var options = { body: 'do you like my body?', silent:
true } var n = new notification('test notification', options); console.log(n.silent) // should log
true specifications specification status comment notifications apithe definition of 'silent' 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.
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).
OffscreenCanvas.getContext() - Web APIs
this option is only available, if the flag gfx.canvas.willreadfrequently.enable is set to
true (which, by default, is only the case for b2g/firefox os).
... preservedrawingbuffer: if the value is
true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
PaymentAddress.toJSON() - Web APIs
requires the comma-delineated list in dom.payments.request.supportedregions to contain one or more of the supported 2-character iso locales, currently us and ca.disabled from version 62: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
...requires the comma-delineated list in dom.payments.request.supportedregions to contain one or more of the supported 2-character iso locales, currently us and ca.disabled from version 62: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.PaymentRequest() - Web APIs
if you set this type to
true, you should select an appropriate shippingtype.
... 'discover', 'mir', 'unionpay'] } }]; var details = { total: {label: 'donation', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected:
true } ] }; var options = {requestshipping:
true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
PaymentRequest.abort() - Web APIs
61edge full support 15firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 53firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.prototype.id - Web APIs
61edge full support 16firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 60firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.onshippingaddresschange - Web APIs
61edge full support 15firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 53firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest.shippingAddress - Web APIs
you can trigger this by setting paymentoptions.requestshipping to
true when calling the paymentrequest constructor.
...}).catch(function(err) { console.error("uh oh, something bad happened", err.message); }); function updatedetails(details, shippingaddress, resolve) { if (shippingaddress.country === 'us') { var shippingoption = { id: '', label: '', amount: {currency: 'usd', value: '0.00'}, selected:
true }; if (shippingaddress.region === 'mo') { shippingoption.id = 'mo'; shippingoption.label = 'free shipping in missouri'; details.total.amount.value = '55.00'; } else { shippingoption.id = 'us'; shippingoption.label = 'standard shipping in us'; shippingoption.amount.value = '5.00'; details.total.amount.value = '60.00'; } details.displayi...
PaymentRequest.shippingType - Web APIs
61edge full support 15firefox full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 55firefox android full support 55notes disabled full support 55notes disabled notes available only in nightly builds.disabled from version 55: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentRequest - Web APIs
this property is only populated if the constructor is called with the requestshipping flag set to
true.
...this property is only populated if the constructor is called with the requestshipping flag set to
true.
PaymentResponse.complete() - Web APIs
61edge full support 15firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
...to change preferences in chrome, visit chrome://flags.firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentResponse.details - Web APIs
61edge full support 15firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
...to change preferences in chrome, visit chrome://flags.firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
PaymentResponse.requestId - Web APIs
61edge full support 16firefox full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
... nochrome android full support 60firefox android full support 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to
true).
Permissions - Web APIs
tandardchrome full support 46edge full support 79firefox full support 51disabled full support 51disabled disabled from version 51: this feature is behind the dom.permissions.revoke.enable preference (needs to be set to
true).
... full support 46chrome android full support 46firefox android full support 51disabled full support 51disabled disabled from version 51: this feature is behind the dom.permissions.revoke.enable preference (needs to be set to
true).
Using the Permissions API - Web APIs
for example, the pushpermissiondescriptor should also contain a boolean that specifies if uservisibleonly is
true or false.
...it can be re-enabled by setting the preference dom.permissions.revoke.enable to
true.
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.
ProgressEvent.initProgressEvent() - Web APIs
canbubblearg is a boolean flag indicating if the event can bubble (
true) or not (false).
... cancelablearg is a boolean flag indicating if the event associated action can be avoided (
true) or not (false).
Proximity Events - Web APIs
the userproximityevent.near property is
true if the object is close or false if the object is far.
... example window.addeventlistener('userproximity', function(event) { if (event.near) { // let's power off the screen navigator.mozpower.screenenabled = false; } else { // otherwise, let's power on the screen navigator.mozpower.screenenabled =
true; } }); specifications specification status comment proximity sensorthe definition of 'proximity events' in that specification.
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.
... at the time of this writing, this method's result only resolves to
true on windows when windows hello capabilities are available (on recent versions of this os).
PublicKeyCredential - Web APIs
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.
... with the current state of implementation, this method only resolves to
true when windows hello is available on the system.
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
note: see publickeycredential.isuserverifyingplatformauthenticatoravailable() which resolves to
true when a user-verifiying platform authenticator is available.
... examples var publickey = { authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey:
true, userverification: "required" }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); spe...
RTCDataChannel: close event - Web APIs
dc.addeventlistener("close", ev => { messageinputbox.disabled =
true; sendbutton.disabled =
true; connectbutton.disabled = false; disconnectbutton.disabled =
true; }, false); all this code does in response to receiving the close event is to disable an input box and its "send" button, and to enable the button used to start a call (while disabling the one that ends a call).
... you can also use the onclose event handler property to set a handler for close events: dc.onclose = ev => { messageinputbox.disabled =
true; sendbutton.disabled =
true; connectbutton.disabled = false; disconnectbutton.disabled =
true; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'close' in that specification.
RTCDataChannel: open event - Web APIs
dc.addeventlistener("open", ev => { messageinputbox.disabled = false; sendmessagebutton.disabled = false; disconnectbutton.disabled = false; connectbutton.disabled =
true; messageinputbox.focus(); }, false); this can also be done by directly setting the value of the channel's onopen event handler property.
... dc.onopen = ev => { messageinputbox.disabled = false; sendmessagebutton.disabled = false; disconnectbutton.disabled = false; connectbutton.disabled =
true; messageinputbox.focus(); } ...
RTCDataChannel.ordered - Web APIs
the read-only rtcdatachannel property ordered indicates whether or not the data channel guarantees in-order delivery of messages; the default is
true, which indicates that the data channel is indeed ordered.
... syntax var ordered = adatachannel.ordered; a boolean value which is
true if in-order delivery is guaranteed and is otherwise false.
RTCIceCandidatePairStats.selected - Web APIs
syntax isselected = icpstats.selected; value a firefox-specific boolean value which is
true if the candidate pair described by this object is the one currently in use.
... if that fails, then the second section iterates over the reports, looking for a candidate-pair record whose firefox-specific selected property is
true.
RTCIceCandidatePairStats - Web APIs
nominated optional a boolean value which, if
true, indicates that the candidate pair described by this object is one which has been proposed for use, and will be (or was) used if its priority is the highest among the nominated candidate pairs.
... non-standard properties selected optional a firefox-specific boolean value which is
true if the candidate pair described by this object is the one currently in use.
RTCPeerConnection.setConfiguration() - Web APIs
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 other peer using the signaling server }) .catch(reporterror); first, a new rtcconfiguration is created, restartconfig, specifying the new ice server and its credentials.
...ice negotiation is restarted by calling createoffer(), specifying
true as the value of the icerestart option.
RTCRtpContributingSource.source - Web APIs
full support 59edge full support ≤79firefox full support 59disabled full support 59disabled disabled from version 59: this feature is behind the media.peerconnection.rtpsourcesapi.enable preference (needs to be set to
true).
...full support 59chrome android full support 59firefox android full support 59disabled full support 59disabled disabled from version 59: this feature is behind the media.peerconnection.rtpsourcesapi.enable preference (needs to be set to
true).
Range.collapse() - Web APIs
syntax range.collapse(tostart); parameters tostart optional a boolean value:
true collapses the range to its start, false to its end.
... example var range = document.createrange(); referencenode = document.getelementsbytagname("div").item(0); range.selectnode(referencenode); range.collapse(
true); specifications specification status comment domthe definition of 'range.collapse()' in that specification.
ReadableStream.cancel() - Web APIs
var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive =
true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ?
...gth - 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?
ReadableStream.getReader() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done -
true if the stream has already given you all its data.
...always undefined when done is
true.
ReadableStream.tee() - Web APIs
st 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.
...always undefined when done is
true.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done -
true if the stream has already given you all its data.
...always undefined when done is
true.
ReadableStreamDefaultReader.cancel() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done -
true if the stream has already given you all its data.
...always undefined when done is
true.
ReportingObserver() - Web APIs
buffered: a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (
true) or not (false).
... examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserver()' in that specification.
ReportingObserverOptions - Web APIs
buffered a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (
true) or not (false).
... examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserveroptions' in that specification.
Reporting API - Web APIs
the callback runs when observation starts an options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered:
true).
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example ...
format - Web APIs
string font format examples of common extensions
truedoc-pfr
truedoc™ portable font resource .pfr embedded-opentype embedded opentype .eot type-1 postscript™ type 1 .pfb, .pfa
truetype
truetype .ttf opentype opentype, including
truetype open .ttf
truetype-gx
truetype with gx extensions - speedo speedo - intellifont intellifont - ...
...example myglyph.format = "
truedoc-pfr"; specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'format' in that specification.
Using server-sent events - Web APIs
for example, assuming the client script is on example.com: const evtsource = new eventsource("//api.example.com/ssedemo.php", { withcredentials:
true } ); once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtsource.onmessage = function(event) { const newelement = document.createelement("li"); const eventlist = document.getelementbyid("list"); newelement.innerhtml = "message: " + event.data; eventlist.appendchild(newelement); } this code li...
... the php code for the example we're using here follows: date_default_timezone_set("america/new_york"); header("cache-control: no-cache"); header("content-type: text/event-stream"); $counter = rand(1, 10); while (
true) { // every second, send a "ping" event.
ServiceWorkerRegistration.unregister() - Web APIs
the promise will resolve to false if no registration was found, otherwise it resolves to
true irrespective of whether unregistration happened or not (it may not unregister if someone else just called serviceworkercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered.
...le the following simple example registers a service worker example, but then immediately unregisters it again: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); registration.unregister().then(function(boolean) { // if boolean =
true, unregister is successful }); }).catch(function(error) { // registration failed console.log('registration failed with ' + error); }); }; specifications specification status comment service workersthe definition of 'serviceworkerregistration.unregister()' in that specification.
SpeechRecognition.continuous - Web APIs
it defaults to single results (false.) syntax var mycontinuous = myspeechrecognition.continuous; myspeechrecognition.continuous =
true; value a boolean representing the current speechrecognition's continuous status.
...
true means continuous, and false means not continuous (single result each time.) examples this code is excerpted from our speech color changer example.
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.
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 - 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.
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.
... syntax var iscollpased = staticrange.collapsed value a boolean value which is
true if the range is collapsed.
StorageManager - Web APIs
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.
Using writable streams - Web APIs
ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
...sing it a message to be written and the stream to write to: sendmessage("hello, world.", writablestream); 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.
Text.isElementContentWhitespace - Web APIs
var tn = document.createtextnode("hello world"); tn.iselementcontentwhitespace; /* evaluates to false */ for a node that is all whitespace characters, the iselementcontentwhitespace evaluates to
true.
... var ws = document.createtextnode(" \t \r\n ") ws.iselementcontentwhitespace; /* evaluates to
true */ ...
TouchEvent.altKey - Web APIs
if the alt key is enabled, the attribute's value is
true.
... 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.ctrlKey - Web APIs
if this key is enabled, the attribute's value is
true.
... 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
if this key is enabled, the attribute's value is
true.
... 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
if this key is enabled, the attribute's value is
true.
... 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.
Multi-touch interaction - Web APIs
ev.preventdefault(); // cache the touch points for later processing of 2-touch pinch/zoom if (ev.targettouches.length == 2) { for (var i=0; i < ev.targettouches.length; i++) { tpcache.push(ev.targettouches[i]); } } if (logevents) log("touchstart", ev,
true); update_background(ev); } touch move handler the touchmove handler calls preventdefault() for the same reason mentioned above, and invokes the pinch/zoom handler.
...false :
true; } function log(name, ev, printtargetids) { var o = document.getelementsbytagname('output')[0]; var s = name + ": touches = " + ev.touches.length + " ; targettouches = " + ev.targettouches.length + " ; changedtouches = " + ev.changedtouches.length; o.innerhtml += s + " "; if (printtargetids) { s = ""; for (var i=0; i < ev.targettouches.length; i++...
TransitionEvent.initTransitionEvent() - Web APIs
canbubblearg is a boolean flag indicating if the event can bubble (
true) or not (false).
... cancelablearg is a boolean flag indicating if the event associated action can be avoided (
true) or not (false).
VideoTrack.selected - Web APIs
syntax isvideoselected = videotrack.selected; videotrack.selected =
true | false; value the selected property is a boolean whose value is
true if the track is active.
... only a single video track can be active at any given time, so setting this property to
true for one track while another track is active will make that other track inactive.
VideoTrack - Web APIs
only a single video track can be active at any given time, so setting this property to
true for one track while another track is active will make that other track inactive.
... for (var i = 0; i < tracks.length; i++) { if (tracks[i].language === userlanguage) { tracks[i].selected =
true; break; } }); the language is in standard (rfc 5646) format.
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).
WebGLRenderingContext.getVertexAttrib() - Web APIs
gl.vertex_attrib_array_enabled: returns a glboolean that is
true if the vertex attribute is enabled at this index.
... gl.vertex_attrib_array_normalized: returns a glboolean that is
true if fixed-point data types are normalized for the vertex attribute array at the given index.
WebGLRenderingContext.pixelStorei() - Web APIs
glint 4 1, 2, 4, 8 opengl es 2.0 gl.unpack_flip_y_webgl flips the source data along its vertical axis if
true.
... glboolean false
true, false webgl gl.unpack_premultiply_alpha_webgl multiplies the alpha channel into the other color channels glboolean false
true, false webgl gl.unpack_colorspace_conversion_webgl default color space conversion or no color space conversion.
Color masking - Web APIs
anvas"); 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); greentoggle.addeventlistener("click", setcolormask, false); bluetoggle.addeventlistener("click", setcolormask, false); function setcolormask(evt)...
... { var index = evt.target === greentoggle && 1 || evt.target === bluetoggle && 2 || 0; mask[index] = !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.
Lifetime of a WebRTC session - Web APIs
only once signaling has been successfully completed can the
true process of opening the webrtc peer connection begin.
... to explicitly trigger ice restart, simply start the renegotiation process by calling rtcpeerconnection.createoffer(), specifying the icerestart option with a value of
true.
Lighting a WebXR setting - Web APIs
because the bouncing and scattering of light can be expensive to compute in real time, especially if multiple light sources are involved, it's common to use ambient lighting to simulate the scattered light caused by all the other light sources in the scene, instead of actually calculating the
true effect of light scattering.
... how browsers mitigate these issues in order to help mitigate these risks, browsers are required by the webxr lighting estimation api specification to report lighting information that is fudged somewhat from the
true value.
WebXR permissions and security - Web APIs
once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are
true: the requestsession() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application.
... if all of that is
true, the promise returned by requestsession() is resolved, and the new xrsession object is passed into the fulfillment handler.
Starting up and shutting down a WebXR session - Web APIs
this returns a promise which resolves to
true if the given type of session is available for use or false otherwise.
... in basic form, code to do this final setup might look something like this: async function runsession(session) { let worlddata; session.addeventlistener("end", onsessionend); let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible:
true }); // set up webgl data and such worlddata = loadglprograms(session, "worlddata.xml"); if (!worlddata) { return null; } // finish configuring webgl worlddata.session.updaterenderstate({ baselayer: new xrwebgllayer(worlddata.session, gl) }); // start rendering the scene referencespace = await worlddata.session.requestreferencespace("unbounded"); worlddata.referen...
Advanced techniques: Creating and sequencing audio - Web APIs
notesinqueue.push({ note: beatnumber, time: time }); if (pads[0].queryselectorall('button')[currentnote].getattribute('aria-checked') === '
true') { playsweep() } if (pads[1].queryselectorall('button')[currentnote].getattribute('aria-checked') === '
true') { playpulse() } if (pads[2].queryselectorall('button')[currentnote].getattribute('aria-checked') === '
true') { playnoise() } if (pads[3].queryselectorall('button')[currentnote].getattribute('aria-checked') === '
true') { playsourceno...
... this.dataset.playing = '
true'; } else { window.cleartimeout(timerid); this.dataset.playing = 'false'; } }) }); summary we've now got an instrument inside our browser!
Controlling multiple parameters with ConstantSourceNode - Web APIs
onnect(gainnode1); oscnode2 = context.createoscillator(); oscnode2.type = "sine"; oscnode2.frequency.value = 329.627556912869929; // e oscnode2.connect(gainnode2); oscnode3 = context.createoscillator(); oscnode3.type = "sine"; oscnode3.frequency.value = 391.995435981749294 // g oscnode3.connect(gainnode3); oscnode1.start(); oscnode2.start(); oscnode3.start(); playing =
true; } each of the three oscillators is set up the same way: create the oscillatornode by calling audiocontext.createoscillator().
... 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.
window.cancelIdleCallback() - Web APIs
47edge full support 79firefox full support 55 full support 55 full support 53disabled disabled from version 53: this feature is behind the dom.requestidlecallback.enabled preference (needs to be set to
true).
...47chrome android full support 47firefox android full support 55 full support 55 full support 53disabled disabled from version 53: this feature is behind the dom.requestidlecallback.enabled preference (needs to be set to
true).
Window.closed - Web APIs
possible values:
true: the window has been closed.
... const popupwindow = null; function refreshpopupwindow() { if (popupwindow && !popupwindow.closed) { // popupwindow is open, refresh it popupwindow.location.reload(
true); } else { // open a new popup window popupwindow = window.open('popup.html', 'datawindow'); } } specification specification status comment html living standardthe definition of 'window.closed' in that specification.
Window.event - Web APIs
fox full support 63notes disabled full support 63notes disabled notes this was briefly enabled by default in 65, then removed again while related compatibility issues are sorted out (see bug 1520756).disabled from version 63: this feature is behind the dom.window.event.enabled preference (needs to be set to
true).
...oid full support 63notes disabled full support 63notes disabled notes this was briefly enabled by default in 65, then removed again while related compatibility issues are sorted out (see bug 1520756).disabled from version 63: this feature is behind the dom.window.event.enabled preference (needs to be set to
true).
Window.matchMedia() - Web APIs
to perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the matches property, which will be
true if the document meets the media query's requirements.
... examples this example runs the media query (max-width: 600px) and displays the value of the resulting mediaquerylist's matches property in a <span>; as a result, the output will say "
true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that.
Privileged features - Web APIs
mozilla and firefox users can force new windows to always render the titlebar by setting dom.disable_window_open_feature.titlebar to
true in about:config or in their user.js file.
... mozilla and firefox users can force new windows to always have a close button by setting dom.disable_window_open_feature.close to
true in about:config or in their user.js file.
Window.open() - Web APIs
you cannot reliably because the users can prevent the window from being resized by setting dom.disable_window_move_resize to
true in about:config or by editing accordingly their user.js file.
...which is simply not
true.
Window.window - Web APIs
this means: global variables of your script are in fact properties of window: var global = {data: 0}; alert(global === window.global); // displays "
true" you can access built-in properties of the window object without having to type window.
...alert(window === window.window); // displays "
true" the point of having the window property refer to the object itself, was likely to make it easy to refer to the global object.
Window - Web APIs
windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (
true) or not (false).
... online fired when the browser has gained access to the network and the value of navigator.online has switched to
true.
WorkerGlobalScope.navigator - Web APIs
example if you call the following console.log(navigator); inside a worker (which would basically be the equivalent of self.console.log(self.navigator);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workernavigator object written to the console — something like the following: object {online:
true, useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) ap…ml, like gecko) chrome/40.0.2214.93 safari/537.36", product: "gecko", platform: "macintel", appversion: "5.0 (macintosh; intel mac os x 10_10_1) applewebki…ml, like gecko) chrome/40.0.2214.93 safari/537.36"…} appcodename: "mozilla" appname: "netscape" appversion: "5.0 (macintosh; 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.
WorkerGlobalScope - Web APIs
windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (
true) or not (false).
... online fired when the browser has gained access to the network and the value of navigator.online switched to
true.
WritableStream.WritableStream() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
WritableStream.getWriter() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
WritableStream - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
WritableStreamDefaultWriter.close() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
WritableStreamDefaultWriter.write() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...ew 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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink err...
WritableStreamDefaultWriter - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream:
true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { 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.
...oder("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(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console...
XMLHttpRequest.send() - Web APIs
example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server',
true); xhr.onload = function () { // request finished.
...}; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server',
true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes.
XMLHttpRequest - Web APIs
if
true, the request will be sent without cookie and authentication headers.
...if
true, the same origin policy will not be enforced on the request.
XRSession.updateRenderState() - Web APIs
these are
true exceptions, since this method does not return a promise.
... function onxrsessionstarted(xrsession) { let glcanvas = document.createelement("canvas"); let gl = glcanvas.getcontext("webgl", { xrcompatible:
true }); loadwebglresources(); xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); } specifications specification status comment webxr device apithe definition of 'xrsession.updaterenderstate()' in that specification.
XRSystem - Web APIs
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.
... if (navigator.xr) { immersivebutton.addeventlistener("click", onbuttonclicked); navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.disabled = false; } else { immersivebutton.disabled =
true; }); } function onbuttonclicked() { if (!xrsession) { navigator.xr.requestsession('immersive-vr') .then(() => { // onsessionstarted() not shown for reasons of brevity and clarity.
XRWebGLLayer.antialias - Web APIs
the read-only xrwebgllayer property antialias is a boolean value which is
true if the rendering layer's frame buffer supports antialiasing.
... syntax let antialiasingsupported = xrwebgllayer.antialias; value a boolean value which is
true if the webgl rendering layer's frame buffer is configured to support antialiasing.
XRWebGLLayer.framebuffer - Web APIs
opaque framebuffers will not have an alpha channel available unless the alpha property is
true when creating the layer.
... note: the depth and stencil properties are not required to be supported in order for a browser to be cons
trued as having full webgl support.
XRWebGLLayerInit.antialias - Web APIs
the boolean antialias property, if present and set to
true in the xrwebgllayerinit object provided as the xrwebgllayer() constructor's layerinit parameter, requests that the new webgl rendering layer support anti-aliasing.
... syntax let layerinit = { antialias: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { antialias: boolvalue }); value a boolean value which can be set to
true to request anti-aliasing support in the new webgl rendering layer.
msPutPropertyEnabled - Web APIs
syntax var retval = style.msputpropertyenabled(propertyname,
true); parameters name[in]: name of the property.
... (string) boolean[in]:
true = enable the property.
ARIA Screen Reader Implementors Guide - Accessibility
busy regions: any changes in a region marked with aria-busy="
true" should not be added to the queue until that attribute is cleared.
... atomic (aria-atomic="
true") regions with multiple changes should not be presented twice with the same content.
Using the aria-required attribute - Accessibility
value
true or false (default: false) possible effects on user agents and assistive technology screen readers should announce the field as required.
... examples example 1: a simple form <form action="post"> <label for="firstname">first name:</label> <input id="firstname" type="text" aria-required="
true" /> <br/> <label for="lastname">last name:</label> <input id="lastname" type="text" aria-required="
true" /> <br/> <label for="streetaddress">street address:</label> <input id="streetaddress" type="text" /> </form> working examples: tooltip example (includes the use of the aria-required attribute) notes used in aria roles combobox gridcell listbox radiogr...
Using the progressbar role - Accessibility
if the progressbar is describing the loading progress of a particular region of a page, the author should use aria-describedby to point to the status, and set the aria-busy attribute to
true on the region until it is finished loading.
... note: elements with the role progressbar have an implicit aria-readonly value of
true.
ARIA: timer role - Accessibility
aria-atomic="
true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g.
... <div id="clock" role="timer" aria-live="polite" aria-atomic="
true"></div> accessibility concerns improperly using the timer role can unintentionally xxx specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'timer' in that specification.
ARIA: row role - Accessibility
states and properties aria-expanded state the aria-expanded attribute, which defines the state of the row, can take one of three values, or be omitted: aria-expanded="
true: row is currently expanded.
...the aria-selected attribute can take one of three values, or be omitted: aria-selected="
true: row is currently selected aria-selected="false": row is not currently selected.
Text labels and names - Accessibility
headings must be labeled make sure that your headings have non-empty text content, and are not hidden, such as with css display:none or aria-hidden=
true.
... headings should have visible text content make sure that your headings have non-empty text content, and are not hidden, such as with css display:none or aria-hidden=
true.
:host() - CSS: Cascading Style Sheets
4edge full support 79firefox full support 63 full support 63 no support 61 — 63disabled disabled from version 61 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
... full support 54firefox android full support 63 full support 63 no support 61 — 63disabled disabled from version 61 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
:host - CSS: Cascading Style Sheets
4edge full support 79firefox full support 63 full support 63 no support 61 — 63disabled disabled from version 61 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
... full support 54firefox android full support 63 full support 63 no support 61 — 63disabled disabled from version 61 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to
true).
:scope - CSS: Cascading Style Sheets
no support 20 — 32disabled disabled from version 20 until version 32 (exclusive): this feature is behind the layout.css.scope-pseudo.enabled preference (needs to be set to
true).
... full support 20disabled disabled from version 20: this feature is behind the layout.css.scope-pseudo.enabled preference (needs to be set to
true).
font-stretch - CSS: Cascading Style Sheets
for
truetype or opentype variable fonts, the "wdth" variation is used to implement varying widths.
... for
truetype or opentype variable fonts, the "wdth" variation is used to implement varying glyph widths.
font-style - CSS: Cascading Style Sheets
on the other hand, if a
true italicized version of the font family exists, we can include it in the src descriptor and specify the font style as italic, so that it is clear that the font is italicized.
...
true italics use different glyphs and are a bit different from their upright counterparts, having some unique features and generally have a rounded and calligraphic quality.
At-rules - CSS: Cascading Style Sheets
furthermore, they all convey a common semantic meaning—they all link some type of condition, which at any time evaluates to either
true or false.
... if the condition evaluates to
true, then all of the statements within the group will be applied.
animation-delay - CSS: Cascading Style Sheets
full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 44prefixed disabled prefixed implemented with the vendor prefix: -webkit-disabled from version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to
true).
...rt 16 full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 44prefixed disabled prefixed implemented with the vendor prefix: -webkit-disabled from version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to
true).
animation-direction - CSS: Cascading Style Sheets
rt 16 full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 44prefixed disabled prefixed implemented with the vendor prefix: -webkit-disabled from version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to
true).
...rt 16 full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 44prefixed disabled prefixed implemented with the vendor prefix: -webkit-disabled from version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to
true).
aspect-ratio - CSS: Cascading Style Sheets
partial support 71notes notes firefox 71 adds internal support only for mapped values no support 69 — 71notes disabled notes firefox 69 adds internal support only for mapped valuesdisabled from version 69 until version 71 (exclusive): this feature is behind the layout.css.width-and-height-map-to-aspect-ratio.enabled preference (needs to be set to
true).
... full support 79firefox full support 71 full support 71 no support 69 — 71disabled disabled from version 69 until version 71 (exclusive): this feature is behind the layout.css.width-and-height-map-to-aspect-ratio.enabled preference (needs to be set to
true).
box-direction - CSS: Cascading Style Sheets
nted with the vendor prefix: -moz- full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 48prefixed disabled prefixed implemented with the vendor prefix: -webkit-disabled from version 48: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to
true).
...nted with the vendor prefix: -moz- full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 48prefixed disabled prefixed implemented with the vendor prefix: -webkit-disabled from version 48: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to
true).
font-variant-caps - CSS: Cascading Style Sheets
52edge full support 79firefox full support 34 full support 34 no support 24 — 34disabled disabled from version 24 until version 34 (exclusive): this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
... full support 52firefox android full support 34 full support 34 no support 24 — 34disabled disabled from version 24 until version 34 (exclusive): this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
font-variant-position - CSS: Cascading Style Sheets
noedge no support nofirefox full support 34 full support 34 no support 24 — 34disabled disabled from version 24 until version 34 (exclusive): this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
...id no support nofirefox android full support 34 full support 34 no support 24 — 34disabled disabled from version 24 until version 34 (exclusive): this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
font-variant - CSS: Cascading Style Sheets
52edge full support 79firefox full support 34 full support 34 no support 33 — 34disabled disabled from version 33 until version 34 (exclusive): this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
... full support 52firefox android full support 34 full support 34 no support 33 — 34disabled disabled from version 33 until version 34 (exclusive): this feature is behind the layout.css.font-features.enabled preference (needs to be set to
true).
position - CSS: Cascading Style Sheets
56edge full support 16firefox full support 32 full support 32 no support 26 — 48disabled disabled from version 26 until version 48 (exclusive): this feature is behind the layout.css.sticky.enabled preference (needs to be set to
true).
...android full support 56firefox android full support 32 full support 32 no support 26 — 48disabled disabled from version 26 until version 48 (exclusive): this feature is behind the layout.css.sticky.enabled preference (needs to be set to
true).
url() - CSS: Cascading Style Sheets
the url() function can be included as a value for background, background-image, list-style, list-style-image, content, cursor, border, border-image, border-image-source, mask, mask-image, src as part of a @font-face block, and @counter-style/symbol in css level 1, the url() functional notation described only
true urls.
...now, url() denotes only
true <url>s.
Setting up adaptive streaming media sources - Developer guides
dash:schema:mpd:2011" xsi:schemalocation="urn:mpeg:dash:schema:mpd:2011 dash-mpd.xsd" type="static" mediapresentationduration="pt654s" minbuffertime="pt2s" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011"> <baseurl>http://example.com/ondemand/</baseurl> <period> <!-- english audio --> <adaptationset mimetype="audio/mp4" codecs="mp4a.40.5" lang="en" subsegmentalignment="
true" subsegmentstartswithsap="1"> <representation id="1" bandwidth="64000"> <baseurl>elephantsdream_aac48k_064.mp4.dash</baseurl> </representation> </adaptationset> <!-- video --> <adaptationset mimetype="video/mp4" codecs="avc1.42401e" subsegmentalignment="
true" subsegmentstartswithsap="1"> <representation id="2" bandwidth="100000" width="480" height="360"> ...
...rsion="1.0"?> <mpd xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xsi:schemalocation="urn:mpeg:dash:schema:mpd:2011" profiles="urn:mpeg:dash:profile:isoff-main:2011" type="static" mediapresentationduration="pt0h9m56.46s"> <baseurl> http://example.com/segments </baseurl> <period start="pt0s"> <adaptationset bitstreamswitching="
true"> <representation id="0" codecs="avc1" mimetype="video/mp4" width="320" height="240" startwithsap="1" bandwidth="46986"> <segmentbase> <initialization sourceurl="main/news100/1.m4s" range="0-862"/> </segmentbase> <segmentlist duration="1"> <segmenturl media="main/news100/2.m4s" mediarange="863-7113"/> <segmenturl media="ma...
Creating a cross-browser video player - Developer guides
o/tears-of-steel-battle-clip-medium.ogg" type="video/ogg"> <!-- flash fallback --> <object type="application/x-shockwave-flash" data="flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" width="1024" height="576"> <param name="movie" value="flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" /> <param name="allowfullscreen" value="
true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="controlbar=over&image=img/poster.jpg&file=flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" /> <img alt="tears of steel poster image" src="img/poster.jpg" width="1024" height="428" title="no video playback possible, please download the video from the link below" />...
...e); } else { if (videocontainer.requestfullscreen) videocontainer.requestfullscreen(); else if (videocontainer.mozrequestfullscreen) videocontainer.mozrequestfullscreen(); 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 det...
Media events - Developer guides
pause sent when the playback state is changed to paused (paused property is
true).
... you can easily watch for these events, using code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); },
true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes.
HTML attribute: required - HTML: Hypertext Markup Language
note: setting aria-required="
true" tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the element.
...assistive technology should inform the user that the form control in mandatory based on the required attribute, but adding aria-required="
true" doesn't hurt, in case the browser / screen reader combination does not support required yet.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
n-standardchrome full support 35edge full support 79firefox no support 33 — 59disabled no support 33 — 59disabled disabled from version 33 until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true).
... full support 37chrome android full support 37firefox android no support 33 — 59disabled no support 33 — 59disabled disabled from version 33 until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to
true).
<input type="reset"> - HTML: Hypertext Markup Language
this is especially
true since the modifiers are typically non-standard to avoid conflicts.
... disabling and enabling a reset button to disable a reset button, simply specify the disabled global attribute on it, like so: <input type="reset" value="disabled" disabled> you can enable and disable buttons at run time by simply setting disabled to
true or false; in javascript this looks like btn.disabled =
true or btn.disabled = false.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
you can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is
true.
...x72" href="favicon72.png"> <!-- non-retina iphone, ipod touch, and android 2.1+ devices: --> <link rel="apple-touch-icon-precomposed" href="favicon57.png"> <!-- basic favicon --> <link rel="icon" href="favicon32.png"> conditionally loading resources with media queries you can provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is
true.
<template>: The Content Template element - HTML: Hypertext Markup Language
if ('content' in document.createelement('template')) { // instantiate the table with the existing html tbody // and the row with the template var tbody = document.queryselector("tbody"); var template = document.queryselector('#productrow'); // clone the new row and insert it into the table var clone = template.content.clonenode(
true); var td = clone.queryselectorall("td"); td[0].textcontent = "1235646565"; td[1].textcontent = "stuff"; tbody.appendchild(clone); // clone the new row and insert it into the table var clone2 = template.content.clonenode(
true); td = clone2.queryselectorall("td"); td[0].textcontent = "0384928528"; td[1].textcontent = "acme kidney beans 2"; tbody.appendchil...
... consider the following html and javascript: html <div id="container"></div> <template id="template"> <div>click me</div> </template> javascript const container = document.getelementbyid("container"); const template = document.getelementbyid("template"); function clickhandler(event) { alert("clicked a div"); } const firstclone = template.content.clonenode(
true); firstclone.addeventlistener("click", clickhandler); container.appendchild(firstclone); const secondclone = template.content.firstelementchild.clonenode(
true); secondclone.addeventlistener("click", clickhandler); container.appendchild(secondclone); result firstclone is a documentfragment instance, so while it gets appended inside the container as expected, clicking on it does not trigger the ...
contenteditable - HTML: Hypertext Markup Language
the attribute must take one of the following values:
true or an empty string, which indicates that the element is editable.
... note that although its allowed values include
true and false, this attribute is an enumerated one and not a boolean one.
MIME types (IANA media types) - HTTP
generic binary data (or binary data whose
true type is unknown) is application/octet-stream.
...in this case, the ideal would be the
true type of the original files; this is often impossible as .rar files can hold several resources of different types.
HTTP headers - HTTP
access-control-allow-credentials indicates whether the response to the request can be exposed when the credentials flag is
true.
...it is a structured header whose value is a boolean so possible values are ?0 for false and ?1 for
true.
Meta programming - JavaScript
handler.preventextensions() object.preventextensions() reflect.preventextensions() object.preventextensions(proxy) only returns
true if object.isextensible(proxy) is false.
... with reflect.has() for example, you get the in operator as a function: reflect.has(object, 'assign') //
true a better apply function in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object).
JavaScript modules - JavaScript
63edge full support 79firefox full support 67 full support 67 no support 66 — 67disabled disabled from version 66 until version 67 (exclusive): this feature is behind the javascript.options.dynamicimport preference (needs to be set to
true).
... full support 63firefox android full support 67 full support 67 no support 66 — 67disabled disabled from version 66 until version 67 (exclusive): this feature is behind the javascript.options.dynamicimport preference (needs to be set to
true).
Assertions - JavaScript
if the multiline flag is set to
true, also matches immediately after a line break character.
...if the multiline flag is set to
true, also matches immediately before a line break character.
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
function test() { let foo = 33; if (
true) { let foo = (foo + 55); // referenceerror: can't access lexical // declaration `foo' before initialization } } test(); valid cases to change "foo" inside the if statement, you need to remove the let that causes the redeclaration.
... function test(){ let foo = 33; if (
true) { foo = (foo + 55); } } test(); ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
function foo() { 'use strict'; bar =
true; } foo(); // referenceerror: assignment to undeclared variable bar valid cases to make "bar" a declared variable, you can add the var keyword in front of it.
... function foo() { 'use strict'; var bar =
true; } foo(); ...
Functions - JavaScript
'use strict'; function f() { return 1; } { function f() { return 2; } } f() === 1; //
true // f() === 2 in non-strict mode block-level functions in non-strict code in a word: don't.
... in strict mode, all browsers that support es2015 handle this the same way: zero is defined only if shoulddefinezero is
true, and only in the scope of the if-block.
Array.prototype.find() - JavaScript
if testresult is
true, return kvalue.
... return undefined; }, configurable:
true, writable:
true }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it is best not to polyfill array.prototype at all, as you cannot make it non-enumerable.
Array.from() - JavaScript
in addition, since
true iterables cannot be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ecma-262.
...if isconstructor(c) is
true, then // 13.
Array.prototype.values() - JavaScript
array.prototype.values === array.prototype[symbol.iterator] //
true iteration using .next() var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // object { value: "d", done: false } iterator.next(); // object { value: "e", done: false } iterator.next(); ...
... // object { value: undefined, done:
true } iteraror.next().value; // undefined one-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(letter); } // undefined reason: when next().done=
true or currentindex>length the for..of loop ends.
ArrayBuffer.isView() - JavaScript
return value
true if the given argument is one of the arraybuffer views; otherwise, false.
... examples using isview arraybuffer.isview(); // false arraybuffer.isview([]); // false arraybuffer.isview({}); // false arraybuffer.isview(null); // false arraybuffer.isview(undefined); // false arraybuffer.isview(new arraybuffer(10)); // false arraybuffer.isview(new uint8array()); //
true arraybuffer.isview(new float32array()); //
true arraybuffer.isview(new int8array(10).subarray(0, 3)); //
true const buffer = new arraybuffer(2); const dv = new dataview(buffer); arraybuffer.isview(dv); //
true specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.isview' in that specification.
Atomics.isLockFree() - JavaScript
it returns
true, if the given size is one of the bytes_per_element property of integer typedarray types.
... examples using islockfree atomics.islockfree(1); //
true atomics.islockfree(2); //
true atomics.islockfree(3); // false atomics.islockfree(4); //
true atomics.islockfree(5); // false atomics.islockfree(6); // false atomics.islockfree(7); // false atomics.islockfree(8); //
true specifications specification ecmascript (ecma-262)the definition of 'atomics.islockfree' in that specification.
Boolean.prototype.toString() - JavaScript
for boolean objects and values, the built-in tostring() method returns the string "
true" or "false" depending on the value of the boolean object.
... examples using tostring() in the following code, flag.tostring() returns "
true": var flag = new boolean(
true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification.
DataView - JavaScript
var littleendian = (function() { var buffer = new arraybuffer(2); new dataview(buffer).setint16(0, 256,
true /* littleendian */); // int16array uses the platform's endianness.
... 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.
Generator.prototype.return() - JavaScript
function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done:
true } g.next(); // { value: undefined, done:
true } if return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state.
... function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done:
true } g.return(); // { value: undefined, done:
true } g.return(1); // { value: 1, done:
true } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.return' in that specification.
JSON.parse() - JavaScript
polyfill // from https://github.com/douglascrockford/json-js/blob/master/json2.js if (typeof json.parse !== "function") { var rx_one = /^[\],:{}\s]*$/; var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fa-f]{4})/g; var rx_three = /"[^"\\\n\r]*"|
true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g; var rx_four = /(?:^|:|,)(?:\s*\[)+/g; var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; json.parse = function(text, reviver) { // the parse method takes a text and an optional reviver function, and returns // a javascript value if the text is a ...
... throw new syntaxerror("json.parse"); }; } examples using json.parse() json.parse('{}'); // {} json.parse('
true'); //
true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned.
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.
Map.prototype.has() - JavaScript
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.clz32() - JavaScript
now, inversing the bits reveals the lowest zeros return 32 - clon(~integer) |0; */ } make these helper functions into asm.js module; then, you have a
true performance masterpiece.
...suint === 0) { return 32; } return 31 - (log(asuint) / ln2 | 0) |0; // the "| 0" acts like math.floor }; })(math.log, math.ln2); examples using math.clz32() math.clz32(1); // 31 math.clz32(1000); // 22 math.clz32(); // 32 var stuff = [nan, infinity, -infinity, 0, -0, false, null, undefined, 'foo', {}, []]; stuff.every(n => math.clz32(n) == 32); //
true math.clz32(
true); // 31 math.clz32(3.5); // 30 specifications specification ecmascript (ecma-262)the definition of 'math.clz32' in that specification.
Number.isFinite() - JavaScript
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 - JavaScript
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.
... convert numeric strings and null to numbers number('123') // 123 number('123') === 123 ///
true number('12.3') // 12.3 number('12.00') // 12 number('123e-1') // 12.3 number('') // 0 number(null) // 0 number('0x11') // 17 number('0b11') // 3 number('0o11') // 9 number('foo') // nan number('100a') // nan number('-infinity') //-infinity specifications specification ecmascript (ecma-262)the definition of 'number' in that specification.
Object.freeze() - JavaScript
o === obj; //
true // the object has become frozen.
... object.isfrozen(obj); // ===
true // now any changes will fail obj.foo = 'quux'; // silently does nothing // silently doesn't add the property obj.quaxxor = 'the friendly duck'; // in strict mode such attempts will throw typeerrors function fail(){ 'use strict'; obj.foo = 'sparky'; // throws a typeerror delete obj.foo; // throws a typeerror delete obj.quaxxor; // returns
true since attribute 'quaxxor' was never added obj.sparky = 'arf'; // throws a typeerror } fail(); // attempted changes through object.defineproperty; // both statements below throw a typeerror.
Object.prototype.__proto__ - JavaScript
shape.__proto__ = circle; // get the object prototype console.log(shape.__proto__ === circle); //
true var shape = function () {}; var p = { a: function () { console.log('aaa'); } }; shape.prototype.__proto__ = p; var circle = new shape(); circle.a(); // aaa console.log(shape.prototype === circle.__proto__); //
true // or var shape = function () {}; var p = { a: function () { console.log('a'); } }; var circle = new shape(); circle.__proto__ = p; circle.a(); // a...
... console.log(shape.prototype === circle.__proto__); // false // or function test() {}; test.prototype.myname = function () { console.log('myname'); }; var a = new test(); console.log(a.__proto__ === test.prototype); //
true a.myname(); // myname // or var fn = function () {}; fn.prototype.myname = function () { console.log('myname'); }; var obj = { __proto__: fn.prototype }; obj.myname(); // myname specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__proto__' in that specification.
Promise.resolve() - JavaScript
true // value: 33 the inverted order of the logs is due to the fact that the then handlers are called asynchronously.
... resolving thenables and throwing errors // resolving a thenable object var p1 = promise.resolve({ then: function(onfulfill, onreject) { onfulfill('fulfilled!'); } }); console.log(p1 instanceof promise) //
true, object casted to a promise p1.then(function(v) { console.log(v); // "fulfilled!" }, function(e) { // not called }); // thenable throws before callback // promise rejects var thenable = { then: function(resolve) { throw new typeerror('throwing'); resolve('resolving'); }}; var p2 = promise.resolve(thenable); p2.then(function(v) { // not called }, function(e) { console.error(e); // typeerror: throwing }); // thenable throws after callback // promise resolves var thenable = { then: function(resolve) { resolve('resolving'); throw new ty...
handler.getPrototypeOf() - JavaScript
examples basic usage const obj = {}; const proto = {}; const handler = { getprototypeof(target) { console.log(target === obj); //
true console.log(this === handler); //
true return proto; } }; const p = new proxy(obj, handler); console.log(object.getprototypeof(p) === proto); //
true five ways to trigger the getprototypeof trap const obj = {}; const p = new proxy(obj, { getprototypeof(target) { return array.prototype; } }); console.log( object.getprototypeof(p) === array.prototype, ...
... //
true reflect.getprototypeof(p) === array.prototype, //
true p.__proto__ === array.prototype, //
true array.prototype.isprototypeof(p), //
true p instanceof array //
true ); two kinds of exceptions const obj = {}; const p = new proxy(obj, { getprototypeof(target) { return 'foo'; } }); object.getprototypeof(p); // typeerror: "foo" is not an object or null const obj = object.preventextensions({}); const p = new proxy(obj, { getprototypeof(target) { return {}; } }); object.getprototypeof(p); // typeerror: expected same prototype value specifications specification ecmascript (ecma-262)the definition of '[[getprototypeof]]' in that specification.
handler.set() - JavaScript
return
true to indicate that assignment succeeded.
... const p = new proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return
true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); //
true console.log(p.a); // 10 specifications specification ecmascript (ecma-262)the definition of '[[set]]' in that specification.
ReferenceError() constructor - JavaScript
examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) //
true console.log(e.message) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 6 console.log(e.stack) // "@scratchpad/2:2:7\n" } creating a reference...
...error try { throw new referenceerror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof referenceerror) //
true console.log(e.message) // "hello" console.log(e.name) // "referenceerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
ReferenceError - JavaScript
examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) //
true console.log(e.message) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 6 console.log(e.stack) // "@scratchpad/2:2:7\n" } creating a reference...
...error try { throw new referenceerror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof referenceerror) //
true console.log(e.message) // "hello" console.log(e.name) // "referenceerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'referenceerror' in that specification.
Reflect.construct() - JavaScript
er' } // calling this: let obj1 = reflect.construct(oneclass, args, otherclass) // ...has the same result as this: let obj2 = object.create(otherclass.prototype) oneclass.apply(obj2, args) console.log(obj1.name) // 'one' console.log(obj2.name) // 'one' console.log(obj1 instanceof oneclass) // false console.log(obj2 instanceof oneclass) // false console.log(obj1 instanceof otherclass) //
true console.log(obj2 instanceof otherclass) //
true //another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { consol.log(arguments[3]); } let obj1 = reflect.construct(func1, ['i', 'love', 'my', 'india']) obj1 however, while the end result is the same, there is one important difference in the process.
...} let obj3 = object.create(otherclass.prototype); oneclass.apply(obj3, args) // output: // oneclass // undefined examples using reflect.construct() let d = reflect.construct(date, [1776, 6, 4]) d instanceof date //
true d.getfullyear() // 1776 specifications specification ecmascript (ecma-262)the definition of 'reflect.construct' in that specification.
Reflect.getOwnPropertyDescriptor() - JavaScript
examples using reflect.getownpropertydescriptor() reflect.getownpropertydescriptor({x: 'hello'}, 'x') // {value: "hello", writable:
true, enumerable:
true, configurable:
true} reflect.getownpropertydescriptor({x: 'hello'}, 'y') // undefined reflect.getownpropertydescriptor([], 'length') // {value: 0, writable:
true, enumerable: false, configurable: false} difference to object.getownpropertydescriptor() if the target argument to this method is not an object (a primitive), then it will cause a typeerror.
... reflect.getownpropertydescriptor('foo', 0) // typeerror: "foo" is not non-null object object.getownpropertydescriptor('foo', 0) // { value: "f", writable: false, enumerable:
true, configurable: false } specifications specification ecmascript (ecma-262)the definition of 'reflect.getownpropertydescriptor' in that specification.
Reflect.has() - JavaScript
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 specification ecmascript (ecma-262)the definition of 'reflect.has' in that specification.
RegExp.prototype.dotAll - JavaScript
property attributes of regexp.prototype.dotall writable no enumerable no configurable yes description the value of dotall is a boolean and
true if the "s" flag was used; otherwise, false.
... examples using dotall var str1 = 'bar\nexample foo example'; var regex1 = new regexp('bar.example','s'); console.log(regex1.dotall); // output:
true console.log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 = new regexp('bar.example'); console.log(regex2.dotall); // output: false console.log(str2.replace(regex2,'')); // output: bar // example foo example specifications specification ecmascript (ecma-262)the definition of...
RegExp.prototype.global - JavaScript
property attributes of regexp.prototype.global writable no enumerable no configurable yes description the value of global is a boolean and
true if the "g" flag was used; otherwise, false.
... examples using global var regex = new regexp('foo', 'g'); console.log(regex.global); //
true var str = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // output: example var regex1 = new regexp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // output: examplefoo specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.global' in that specification.
RegExp.prototype.ignoreCase - JavaScript
property attributes of regexp.prototype.ignorecase writable no enumerable no configurable yes description the value of ignorecase is a boolean and
true if the "i" flag was used; otherwise, false.
... examples using ignorecase var regex = new regexp('foo', 'i'); console.log(regex.ignorecase); //
true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.ignorecase' in that specification.
RegExp.prototype.multiline - JavaScript
property attributes of regexp.prototype.multiline writable no enumerable no configurable yes description the value of multiline is a boolean and is
true if the "m" flag was used; otherwise, false.
... examples using multiline var regex = new regexp('foo', 'm'); console.log(regex.multiline); //
true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.multiline' in that specification.
RegExp.prototype.unicode - JavaScript
property attributes of regexp.prototype.unicode writable no enumerable no configurable yes description the value of unicode is a boolean and
true if the "u" flag was used; otherwise false.
... examples using the unicode property var regex = new regexp('\u{61}', 'u'); console.log(regex.unicode); //
true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification.
Set.prototype.has() - JavaScript
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.
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.
...when this flag is set to
true, the constructed memory object can be shared between workers via postmessage(), just like sharedarraybuffer, and the backing buffer of the memory object is a sharedarraybuffer.
String.prototype.indexOf() - JavaScript
for example, the following expression returns -1: 'blue whale'.indexof('blue') // returns -1 checking occurrences note that 0 doesn't evaluate to
true and -1 doesn't evaluate to false.
... therefore, when checking if a specific string exists within another string, the correct way to check would be: 'blue whale'.indexof('blue') !== -1 //
true 'blue whale'.indexof('bloe') !== -1 // false ~('blue whale'.indexof('bloe')) // 0, which is falsy examples using indexof() the following example uses indexof() to locate values in the string "brave new world".
String.prototype.localeCompare() - JavaScript
let items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; items.sort( (a, b) => a.localecompare(b, 'fr', {ignorepunctuation:
true})); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] check browser support for extended arguments the locales and options arguments are not supported in all browsers yet.
...e base letter console.log('ä'.localecompare('a', 'de', { sensitivity: 'base' })); // 0 // in swedish, ä and a are separate base letters console.log('ä'.localecompare('a', 'sv', { sensitivity: 'base' })); // a positive value numeric sorting // by default, "2" > "10" console.log("2".localecompare("10")); // 1 // numeric using options: console.log("2".localecompare("10", undefined, {numeric:
true})); // -1 // numeric using locales tag: console.log("2".localecompare("10", "en-u-kn-
true")); // -1 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.localecompare' in that specification.
String - JavaScript
in javascript, you just use the less-than and greater-than operators: let a = 'a' let b = 'b' if (a < b) { //
true console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } a similar result can be achieved using the localecompare() method inherited by string instances.
...(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.
Symbol.unscopables - JavaScript
setting a property to
true in an unscopables object will make it unscopable and therefore it won't appear in lexical scope variables.
... var obj = { foo: 1, bar: 2 }; obj[symbol.unscopables] = { foo: false, bar:
true }; with (obj) { console.log(foo); // 1 console.log(bar); // referenceerror: bar is not defined } specifications specification ecmascript (ecma-262)the definition of 'symbol.unscopables' in that specification.
TypeError() constructor - JavaScript
the line number of the code that caused the exception examples catching a typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) //
true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw new typeerror('hello', "somef...
...ile.js", 10) } catch (e) { console.log(e instanceof typeerror) //
true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
TypeError - JavaScript
examples catching a typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) //
true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw new typeerror('hello', "somef...
...ile.js", 10) } catch (e) { console.log(e instanceof typeerror) //
true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'typeerror' in that specification.
TypedArray.prototype.filter() - JavaScript
return
true to keep the element, false otherwise.
... 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.
TypedArray.prototype.includes() - JavaScript
the includes() method determines whether a typed array includes a certain element, returning
true or false as appropriate.
... examples using includes var uint8 = new uint8array([1,2,3]); uint8.includes(2); //
true uint8.includes(4); // false uint8.includes(3, 3); // false // nan handling (only
true for float32 and float64) new uint8array([nan]).includes(nan); // false, since the nan passed to the constructor gets converted to 0 new float32array([nan]).includes(nan); //
true; new float64array([nan]).includes(nan); //
true; specifications specification ecmascript (ecma-262)the ...
URIError() constructor - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) //
true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw new urierror('hello', 'somefile.js',...
... 10) } catch (e) { console.log(e instanceof urierror) //
true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
URIError - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) //
true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw new urierror('hello', 'somefile.js',...
... 10) } catch (e) { console.log(e instanceof urierror) //
true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'urierror' in that specification.
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.
WeakMap.prototype.has() - JavaScript
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
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.
WebAssembly.Memory() constructor - JavaScript
if set to
true, it is a shared memory.
...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.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).
undefined - JavaScript
in the following code, the variable x is not initialized, and the if statement evaluates to
true.
... // x has not been declared before if (typeof x === 'undefined') { // evaluates to
true without errors // these statements execute } if (x === undefined) { // throws a referenceerror } however, there is another alternative.
Lexical grammar - JavaScript
abstract boolean byte char double final float goto int long native short synchronized throws transient volatile additionally, the literals null,
true, and false cannot be used as identifiers in ecmascript.
...
true false numeric literals the number and bigint types use numeric literals.
Conditional (ternary) operator - JavaScript
exprif
true : expriffalse parameters condition an expression whose value is used as a condition.
... exprif
true an expression which is evaluated if the condition evaluates to a truthy value (one which equals or can be converted to
true).
Inequality (!=) - JavaScript
like the equality operator, the inequality operator will attempt to convert and compare operands of different types: 3 != "3"; // false to prevent this, and require that different types are considered to be different, use the strict inequality operator instead: 3 !== "3"; //
true examples comparison with no type conversion 1 != 2; //
true "hello" != "hola"; //
true 1 != 1; // false "hello" != "hello"; // false comparison with type conversion "1" != 1; // false 1 != "1"; // false 0 != false; // false 0 != null; //
true 0 != undefined; //
true 0 != !!null; // false, look at logica...
...l not operator 0 != !!undefined; // false, look at logical not operator null != undefined; // false const number1 = new number(3); const number2 = new number(3); number1 != 3; // false number1 != number2; //
true comparison of objects const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 != object2 //
true object2 != object2 // false specifications specification ecmascript (ecma-262)the definition of 'equality operators' in that specification.
Strict inequality (!==) - JavaScript
like the strict equality operator, the strict inequality operator will always consider operands of different types to be different: 3 !== "3"; //
true examples comparing operands of the same type console.log("hello" !== "hello"); // false console.log("hello" !== "hola"); //
true console.log(3 !== 3); // false console.log(3 !== 4); //
true console.log(
true !==
true); // false console.log(
true !== false); //
true console.log(null !== null); // false comparing operands of different typ...
...es console.log("3" !== 3); //
true console.log(
true !== 1); //
true console.log(null !== undefined); //
true comparing objects const object1 = { name: "hello" } const object2 = { name: "hello" } console.log(object1 !== object2); //
true console.log(object1 !== object1); // false specifications specification ecmascript (ecma-262)the definition of 'equality operators' in that specification.
Unary plus (+) - JavaScript
it can convert string representations of integers and floats, as well as the non-string values
true, false, and null.
... 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.
typeof - JavaScript
er typeof 42n === 'bigint'; // strings typeof '' === 'string'; typeof 'bla' === 'string'; typeof `template literal` === 'string'; typeof '1' === 'string'; // note that a number within a string is still typeof string typeof (typeof 1) === 'string'; // typeof always returns a string typeof string(1) === 'string'; // string converts anything into a string, safer than tostring // booleans typeof
true === 'boolean'; typeof false === 'boolean'; typeof boolean(1) === 'boolean'; // boolean() will convert values based on if they're truthy or falsy typeof !!(1) === 'boolean'; // two calls of the !
...typeof new boolean(
true) === 'object'; typeof new number(1) === 'object'; typeof new string('abc') === 'object'; // functions typeof function() {} === 'function'; typeof class c {} === 'function'; typeof math.sin === 'function'; typeof null // this stands since the beginning of javascript typeof null === 'object'; in the first implementation of javascript, javascript values were represented as a type tag and a valu...
do...while - JavaScript
syntax do statement while (condition); statement a statement that is executed at least once and is re-executed each time the condition evaluates to
true.
...if condition evaluates to
true, the statement is re-executed.
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 conform to the async iterable protocol, they can be looped using for await...of.
... 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.
for...of - JavaScript
functions generating an iterable object: function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; while (
true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (const n of fibonacci()) { console.log(n); // truncate the sequence at 1000 if (n >= 1000) { break; } } do not reuse generators generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword.
...} 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.
function declaration - JavaScript
typeof foo is function the results are exactly the same for a condition that evaluates to
true var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ?
...typeof foo is ${typeof foo}`); if (
true) { function foo(){ return 1; } } // in chrome: // 'foo' name is hoisted.
Statements and declarations - JavaScript
if...else executes a statement if a specified condition is
true.
... while creates a loop that executes a specified statement as long as the test condition evaluates to
true.
Template literals (Template strings) - JavaScript
`\`` === '`' // -->
true multi-line strings any newline characters inserted in the source are part of the template literal.
... for instance, if condition a is
true, then return this templated literal.
prefer_related_applications - Web app manifests
if the prefer_related_applications member is set to
true, the user agent might suggest installing one of the related applications instead of this web app.
... examples "prefer_related_applications":
true specification specification status comment feedback web app manifestthe definition of 'prefer_related_applications' in that specification.
<mfrac> - MathML
if
true, the fraction line is bevelled, which means that numerator and denominator are displayed side by side and separated by a slash (/).
... examples sample rendering: your browser rendering: a b c d <math> <mfrac bevelled="
true"> <mfrac> <mi> a </mi> <mi> b </mi> </mfrac> <mfrac> <mi> c </mi> <mi> d </mi> </mfrac> </mfrac> </math> specifications specification status comment mathml 3.0the definition of 'mfrac' in that specification.
<mover> - MathML
use the following syntax: <mover> base overscript </mover> attributes accent if
true the over-script is an accent, which is drawn closer to the base expression.
... examples sample rendering: rendering in your browser: x + y + z ⏞ <math> <mover accent="
true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> ⏞ <!--top curly bracket--> </mo> </mover> </math> specifications specification status comment mathml 3.0the definition of 'mover' in that specification.
<mstyle> - MathML
the main effect is that larger versions of operators are displayed, when displaystyle is set to
true.
... <math> <mstyle displaystyle="
true" mathcolor="teal"> <mrow> <munderover> <mo stretchy="
true" form="prefix">∑</mo> <mrow> <mi>i</mi> <mo form="infix">=</mo> <mn>1</mn> </mrow> <mi>n</mi> </munderover> <mstyle displaystyle="
true"> <mfrac> <mn>1</mn> <mi>n</mi> </mfrac> </mstyle> </mrow> </mstyle...
<mtable> - MathML
if you want to use this element as an inline-block, you might want to set <mtable displaystyle="
true">...</mtable>.
...the main effect is that larger versions of operators are displayed, when displaystyle is set to
true.
<munder> - MathML
it uses the following syntax: <munder> base underscript </munder> attributes accentunder if
true, the element is an accent, which is drawn closer to the base expression.
... examples sample rendering: rendering in your browser: x + y + z ⏟ <math> <munder accentunder="
true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> ⏟ <!--bottom curly bracket--> </mo> </munder> </math> specifications specification status comment mathml 3.0the definition of 'munder' in that specification.
Web audio codec guide - Web media technologies
for each factor that affects the encoded audio, there is a simple rule that is nearly always
true: because the fidelity of digital audio is determined by the granularity and precision of the samples taken to convert it into a data stream, the more data used to represent the digital version of the audio, the more closely the sampled sound will match the source material.
... for the purposes of this example, we'll assume that all browsers have the same codec and container support as firefox (although this is far from
true).
Web video codec guide - Web media technologies
how much compression is being applied the more the encoded video is allowed to deviate from the source, the easier it is to accomplish higher compression rates quality setting the higher the quality configuration, the more like the original media the encoded video will look in general, higher quality settings will result in larger encoded video files; the degree to which this is
true varies depending on the codec bit rate quality generally improves with higher bit rates higher bit rates inherently lead to larger output files the options available when encoding video, and the values to be assigned to those options, will vary not only from one codec to another but depending on the encoding software you use.
...this is especially
true if you wish to use an open codec rather than a proprietary one.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
there are two options passed to the pushmanager.subscribe() method — the first is uservisibleonly:
true, which means all the notifications sent to the user will be visible to them, and the second one is the applicationserverkey, which contains our successfully acquired and converted vapid key.
... 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.
SVG Conditional Processing Attributes - SVG: Scalable Vector Graphics
externalresourcesrequired requiredextensions requiredfeatures systemlanguage attributes externalresourcesrequired deprecated since svg 2 if set to
true, it indicates that the browser must wait for all the external resources necessary to render that element to be loaded before processing the associated element.
... value: false|
true; animatable: no requiredextensions list all the browser specific capabilities that must be supported by the borwser to be allowed to render the associated element.
preserveAlpha - SVG: Scalable Vector Graphics
only one element is using this attribute: <feconvolvematrix> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="convolvematrix1" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 -1 2 0 0 0 0 0 -2" preservealpha="
true"/> </filter> <filter id="convolvematrix2" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 -1 2 0 0 0 0 0 -2" preservealpha="false"/> </filter> <image xlink:href="//developer.mozilla.org/files/6457/mdn_logo_only_color.png" width="200" height="200" style="filter:url(#convolvematrix1);"/> <image xlink:href="//developer.mozilla.org/files/6457/mdn_logo_on...
...ly_color.png" width="200" height="200" style="filter:url(#convolvematrix2); transform:translatex(220px);"/> </svg> usage notes default value false value
true | false animatable yes
true this value indicates that the convolution will only apply to the color channels.
requiredExtensions - SVG: Scalable Vector Graphics
if all of the given extensions are supported, then the attribute evaluates to
true; otherwise, the current element and its children are skipped and thus will not be rendered.
... if the attribute is not present, then it implicitly evaluates to "
true".
systemLanguage - SVG: Scalable Vector Graphics
the attribute evaluates to "
true" if one of the language tags indicated by user preferences is a case-insensitive match or prefix (followed by a "-") of one of the language tags given in the value of this parameter.
... if the attribute is not present, then it implicitly evaluates to "
true".
<switch> - SVG: Scalable Vector Graphics
the <switch> svg element evaluates any requiredfeatures, requiredextensions and systemlanguage attributes on its direct child elements in order, and then renders the first child where these attributes evaluate to
true.
...in particular, setting display:none on a child has no effect on the
true/false testing for <switch> processing.
SVG documentation index - SVG: Scalable Vector Graphics
it determines whether or not all of the named features are supported by the browser; if all of them are supported, the attribute evaluates to
true end the element is rendered; otherwise, the attribute evaluates to false and the current element and its children are skipped and thus will not be rendered.
... 369 <switch> element, needsexample, svg, svg container the <switch> svg element evaluates any requiredfeatures, requiredextensions and systemlanguage attributes on its direct child elements in order, and then renders the first child where these attributes evaluate to
true.
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.
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.
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.
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.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
by making the second parameter "
true", it will clone all descendants as well (a deep clone).
... // importnode is used to clone the nodes we want to process via xslt -
true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode,
true); // add the cloned dom into the xml document xmlref.appendchild(clonednode); once the stylesheet has been imported, xsltprocessor has to perform two methods for the actual transformation, namely xsltprocessor.transformtodocument() and xsltprocessor.transformtofragm...
Understanding WebAssembly text format - WebAssembly
to create an equivalent value using javascript, you'd use the webassembly.global() constructor: const global = new webassembly.global({value: "i32", mutable:
true}, 0); webassembly memory the above example is a pretty terrible logging function: it only prints a single integer!
... over on the javascript api side, the webassembly.memory() constructor's initialization object now has a shared property, which when set to
true will create a shared memory: let memory = new webassembly.memory({initial:10, maximum:100, shared:
true}); the memory's buffer property will now return a sharedarraybuffer, instead of the usual arraybuffer: memory.buffer // returns sharedarraybuffer over in the text format, you can create a shared memory using the shared keyword, like this: (memory 1 2 shared) unlike unshared memories, sha...
Using the WebAssembly JavaScript API - WebAssembly
to create a webassembly global instance from inside your javascript, you use the webassembly.global() constructor, which looks like this: const global = new webassembly.global({value:'i32', mutable:
true}, 0); you can see that this takes two parameters: an object that contains two properties describing the global variable: value: its data type, which can be any data type accepted within webassembly modules — i32, i64, f32, or f64.
...got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:
true}, 0); webassembly.instantiatestreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43)...
Cross-domain Content Scripts - Archive of obsolete content
-> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> the "panel-script.js" uses xmlhttprequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=your-api-key"; self.port.on("show", function () { var request = new xmlhttprequest(); request.open("get", url,
true); request.onload = function () { var jsonresponse = json.parse(request.responsetext); var summary = getsummary(jsonresponse); 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 "cro...
Reddit Example - Archive of obsolete content
is is the complete add-on script: var data = require("sdk/self").data; var button = require("sdk/ui/button/action").actionbutton({ id: "reddit-panel", label: "reddit panel", icon: "./icon-16.png", onclick: function() { reddit_panel.show(); } }); var reddit_panel = require("sdk/panel").panel({ width: 240, height: 320, contenturl: "http://www.reddit.com/.mobile?keep_extension=
true", contentscriptfile: [data.url("jquery-2.1.0.min.js"), data.url("panel.js")] }); reddit_panel.port.on("click", function(url) { require("sdk/tabs").open(url); }); this code supplies two content scripts to the panel's constructor in the contentscriptfile option: the jquery library and the script that intercepts link clicks.
Modules - Archive of obsolete content
to avoid problems like this, the object passed to loadsubscript should be a
true global object, having its own instances of the built-in constructors.
page-mod - Archive of obsolete content
for example: var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*", contentscriptfile: data.url("show.js"), contentscriptoptions: { showoptions:
true, numbers: [1, 2], greeting: "hello!" } }); the values are accessible to content scripts via the self.options property: // show.js if (self.options.showoptions) { window.alert(self.options.greeting); var sum = self.options.numbers[0] + self.options.numbers[1]; window.alert(sum); } the values can be any json-serializable value: a string, number, boolean, null, array o...
request - Archive of obsolete content
to force the response to be interpreted as latin-1, use overridemimetype: var request = require("sdk/request").request; var quijote = request({ url: "http://www.latin1files.org/quijote.txt", overridemimetype: "text/plain; charset=latin1", oncomplete: function (response) { console.log(response.text); } }); quijote.get(); anonymous boolean if
true, the request will be sent without cookies or authentication headers.
simple-storage - Archive of obsolete content
to store a value, just assign it to a property on storage: var ss = require("sdk/simple-storage"); ss.storage.myarray = [1, 1, 2, 3, 5, 8, 13]; ss.storage.myboolean =
true; ss.storage.mynull = null; ss.storage.mynumber = 3.1337; ss.storage.myobject = { a: "foo", b: { c:
true }, d: null }; ss.storage.mystring = "o frabjous day!"; you can store array, boolean, number, object, null, and string values.
core/promise - Archive of obsolete content
lets see the implementation of readasync that we used in several of the examples above: const { defer } = require('sdk/core/promise'); function readasync(url) { var deferred = defer(); let xhr = new xmlhttprequest(); xhr.open("get", url,
true); xhr.onload = function() { deferred.resolve(xhr.responsetext); }; xhr.onerror = function(event) { deferred.reject(event); }; xhr.send(); return deferred.promise; } so defer returns an object that contains a promise and two resolve, reject functions that can be used to resolve / reject that promise.
frame/hidden-frame - Archive of obsolete content
page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(self.element.contentdocument.title); },
true,
true); } })); see the panel module for a real-world example of usage of this module.
preferences/event-target - Archive of obsolete content
example var { prefstarget } = require("sdk/preferences/event-target"); // listen to the same branch which reqire("sdk/simple-prefs") does var target = prefstarget({ branchname: "extensions." + require("sdk/self").preferencesbranch + "." }); target.once("test", function(prefname) { console.log(prefname) // logs "test" console.log(target.prefs[name]) // logs
true }); target.once("", function() { console.log(prefname) // logs "test" console.log(target.prefs[name]) // logs
true }) // changing a pref which our target listens to require("sdk/simple-prefs").prefs.test =
true; ...
preferences/service - Archive of obsolete content
a properties file example: require("sdk/preferences/service").set("general.useragent.locale", "chrome://global/locale/intl.properties"); example: setting global preferences var { get, set } = require("sdk/preferences/service"); var { when: unload } = require("sdk/system/unload"); var oldvalue = get("browser.urlbar.autofill"); set("browser.urlbar.autofill",
true); // by amo policy global preferences must be changed back to their original value unload(function() { set("browser.urlbar.autofill", oldvalue); }); ...
remote/parent - Archive of obsolete content
// remote.js const { frames } = require("sdk/remote/child"); frames.addeventlistener("pageshow", function() { // `this` is bound to the frame the event came from let frame = this; frame.port.emit("pageshow"); },
true); // main.js const { frames, remoterequire } = require("sdk/remote/parent"); remoterequire("./remote.js", module); // the first argument is the frame the message came from frames.port.on("pageshow", (frame) => { console.log(frame.frameelement.currenturi.host + ": pageshow"); }); globals functions remoterequire(id, module = null) loads a module in any existing and future child processes.
system/environment - Archive of obsolete content
usage var { env } = require('sdk/system/environment'); you can get the value of an environment variable, by accessing the property with the name of the desired variable: var path = env.path; you can check for the existence of an environment variable by checking whether a property with that variable name exists: console.log('path' in env); //
true console.log('foo' in env); // false you can set the value of an environment variable by setting the property: env.foo = 'foo'; env.path += ':/my/path/' you can unset an environment variable by deleting the property: delete env.foo; limitations there is no way to enumerate existing environment variables, also env won't have any enumerable properties: console.log(object.keys(env)); // [] env...
util/list - Archive of obsolete content
examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: function add(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._remove.bind(this)); } }); mylist('foo', 'bar', 'baz').length == 3; //
true new mylist('new', 'keyword').length == 2; //
true mylist.apply(null, [1, 2, 3]).length == 3; //
true let list = mylist(); list.length == 0; //
true list.add(1, 2, 3) == 3; //
true properties length number of elements in this list.
util/object - Archive of obsolete content
let { merge } = require("sdk/util/object"); var a = { jetpacks: "are yes", foo: 10 } var b = merge(a, { foo: 5, bar: 6 }, { foo: 50, location: "sf" }); b === a //
true b.jetpacks // "are yes" b.foo // 50 b.bar // 6 b.location // "sf" // merge also translates property descriptors var c = { "type": "addon" }; var d = {}; object.defineproperty(d, "name", { value: "jetpacks", configurable: false }); merge(c, d); var props = object.getownpropertydescriptor(c, "name"); console.log(props.configurable); //
true parameters source : object the object t...
Implementing the widget - Archive of obsolete content
the widget's content script the widget's content script just listens for left- and right- mouse clicks and posts the corresponding message to the add-on code: this.addeventlistener('click', function(event) { if(event.button == 0 && event.shiftkey == false) self.port.emit('left-click'); if(event.button == 2 || (event.button == 0 && event.shiftkey ==
true)) self.port.emit('right-click'); event.preventdefault(); },
true); save this in your data/widget directory as widget.js.
Getting started (cfx) - Archive of obsolete content
for example: while
true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run.
Bootstrapped extensions - Archive of obsolete content
creating a bootstrapped extension to mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>
true</em:bootstrap> then you need to add a bootstrap.js file that contains the required functions; this should be alongside the install.rdf file in the extension's package.
Canvas code snippets - Archive of obsolete content
add a listener to the // frame's onload event iframe.addeventlistener('load', this.remotepageloaded,
true); //append to the end of the page window.document.body.appendchild(iframe); return; }; remotecanvas.prototype.remotepageloaded = function() { // look back up the iframe by id var ldrframe = document.getelementbyid('test-iframe'); // get a reference to the window object you need for the canvas // drawwindow method var remotewindow = ldrframe.contentwindow; //d...
Customizing the download progress bar - Archive of obsolete content
init : function fdm_init() { 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"].
Downloading Files - Archive of obsolete content
acy = 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, "", nsfileinst...
File I/O - Archive of obsolete content
queryinterface(components.interfaces.nsilocalfile).path); } creating folders fileutils.getdir() can create a folder automatically if it doesn't exist yet: components.utils.import("resource://gre/modules/fileutils.jsm"); var dir = fileutils.getdir("profd", ["dir"],
true); the above example creates a folder called "dir" in the user's profile folder.
JavaScript Debugger Service - Archive of obsolete content
k; 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.script.filename + "@" + f.line + "@" + f.functionn...
Post data to window - Archive of obsolete content
createinstance(ci.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength =
true; postdata.setdata(stringstream); // postdata is ready to be used as apostdata argument ...
Sidebar - Archive of obsolete content
for this snippet to work, you have to declare mainwindow as in the previous code block then write: mainwindow.document.getelementbyid("sidebar-splitter").hidden =
true; be aware that if you change the splitter's hidden attribute, you need to reset it to a safe value when your sidebar is closed, or replaced by another sidebar.
xml:base support in old browsers - Archive of obsolete content
e if (!att.match(/\/$/)) { // if no trailing slash, add one, since it is being attached to a relative path att += '/'; } xmlbase = att + xmlbase; // if previous path was not absolute, resolve against the 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 === '') ?
Communication between HTML and your extension - Archive of obsolete content
after the html component was update with the result of the ajax request, i created and dispatched the event like this: var event = document.createevent("events"); event.initevent("my-custom-event",
true,
true); document.body.dispatchevent(event); in the code of the extension that catches the loading of a new page i added this code: var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page.
Default Preferences - Archive of obsolete content
inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultprefs.example.int', 1); pref('extensions.defaultprefs.example.float', 0.1); pref('extensions.defaultprefs.example.string', 'fadf'); pref('extensions.defaultprefs.example.bool',
true); notice that unlike when you're reading preferences, writing default preferences uses the same function no matter the data type of the preference.
Displaying web content in an extension without security issues - Archive of obsolete content
for example, your template document might have this code: <style type="text/css"> #entrytemplate { display: none; } </style> <div id="entrytemplate"> <div class="title"></div> <div class="description"></div> </div> now to insert a new entry in the document you would do the following: var template = doc.getelementbyid("entrytemplate"); var entry = template.clonenode(
true); entry.removeattribute("id"); entry.getelementsbyclassname("title")[0].textcontent = title; entry.getelementsbyclassname("description")[0].textcontent = description; template.parentnode.appendchild(entry); the important difference here is that the result will always have the same structure as the template tag.
Inline options - Archive of obsolete content
<menuitem value="500" label="small"/> <menuitem value="800" label="medium"/> <menuitem value="1200" label="large"/> </menupopup> </menulist> </setting> <!-- radio button example (this example would be stored as a boolean) --> <setting pref="extensions.myaddon.options2" type="radio" title="options 2"> <radiogroup> <radio value="false" label="disabled"/> <radio value="
true" label="enabled"/> </radiogroup> </setting> <!-- button example - not tied to a preference, but attached to a command --> <setting title="do something" type="control"> <button id="myaddon-button" label="click me" oncommand="alert('thank you!');"/> </setting> setting element changed notifications most of the setting elements (it might be all i havent really looked), support oninputchanged...
Offering a context menu for form controls - Archive of obsolete content
window.addeventlistener("load", function() { let settargetoriginal = nscontextmenu.prototype.settarget; components.utils.reporterror(settargetoriginal); nscontextmenu.prototype.settarget = function(anode, arangeparent, arangeoffset) { settargetoriginal.apply(this, arguments); if (this.istargetaformcontrol(anode)) this.shoulddisplay =
true; }; }, false); this code, which is run when the window is opened up, works by replacing the settarget() routine for the prototype of nscontextmenu with one that forces the context menu to display if the target of the menu is a form control.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
listing 3: an example of a class definition in javascript function myclass() { } myclass.prototype = { property1 :
true, property2 : 'string', method : function() { alert('hello, world!'); } }; var obj = new myclass(); obj.method(); dom: an api for manipulating xml documents the document object model (dom) is a technical standard promulgated by the w3c, and is an api for manipulating the contents of xml documents as objects.
Adding windows and dialogs - Archive of obsolete content
// 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.
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
so, if we were to use fuel, we can do the following in the init function: init : function() { let firstrunpref = "extensions.xulschoolhello.firstrundone"; if (!application.prefs.getvalue(firstrunpref, false)) { application.prefs.setvalue(firstrunpref,
true); // all the rest of the first run code goes here.
Appendix D: Loading Scripts - Archive of obsolete content
wantxrays:
true }); // the script that will be executed: let script = string(); // evaluate the script: components.utils.evalinsandbox(script, sandbox, // the javascript version "1.8", // the apparent script filename: "zz-9://plural/zed/alpha", // the appare...
User Notifications and Alerts - Archive of obsolete content
erts service is similar to using notification boxes: let alertsservice = cc["@mozilla.org/alerts-service;1"].getservice(ci.nsialertsservice); let title = this._bundle.getstring("xulschoolhello.greeting.title"); let message = this._bundle.getstring("xulschoolhello.greeting.label"); alertsservice.showalertnotification( "chrome://xulschoolhello/skin/hello-notification.png", title, message,
true, "", this, "xulschool hello message"); we pass this as an argument, assuming that this is an object that implements nsiobserver.
XPCOM Objects - Archive of obsolete content
on(acompmgr, alocation, aloaderstr, atype) { let categorymanager = cc[@mozilla.org/categorymanager;1].getservice(ci.nsicategorymanager); acompmgr.queryinterface(ci.nsicomponentregistrar); acompmgr.registerfactorylocation( class_id, class_name, contract_id, alocation, aloaderstr, atype); categorymanager.addcategoryentry( "content-policy", "xulschool hello world", contract_id,
true,
true); }, in this case the component would need to implement nsicontentpolicy.
Creating reusable content with CSS and XBL - Archive of obsolete content
ument.getanonymouselementbyattribute(this, "anonid", "square") ]]></field> <field name="button"><![cdata[ document.getanonymouselementbyattribute(this, "anonid", "button") ]]></field> <method name="dodemo"> <body><![cdata[ this.square.style.backgroundcolor = "#cf4" this.square.style.marginleft = "20em" this.button.setattribute("disabled", "
true") settimeout(this.cleardemo, 2000, this) ]]></body> </method> <method name="cleardemo"> <parameter name="me"/> <body><![cdata[ me.square.style.backgroundcolor = "transparent" me.square.style.marginleft = "0" me.button.removeattribute("disabled") ]]></body> </method> </implementation> <handlers> <handler event...
MozOrientation - Archive of obsolete content
* (180 / math.pi)); evt.beta = -(evt.y * (180 / math.pi)); } // use evt.gamma, evt.beta, and evt.alpha // according to dev.w3.org/geo/api/spec-source-orientation } window.addeventlistener('deviceorientation', orientationhandler, false); window.addeventlistener('mozorientation', orientationhandler, false); example window.addeventlistener("mozorientation", dofunc,
true); the example below simply displays the raw accelerometer data in the browser window as the events arrive.
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
age.</p> <br /> <!-- ***** this code dynamically creates the tabbed menu if the browser has support to xmlhttprequest, since the mechanism used here is xmlhttprequest ***** --> <script type="text/javascript" language="javascript"> //// /// object detection // var xcomp=null; var testxmlhttprequest=false; try { xcomp = new xmlhttprequest(); if(xcomp) testxmlhttprequest=
true; } catch (e) { try { xcomp = new activexobject("microsoft.xmlhttp"); if(xcomp) testxmlhttprequest=
true; } catch (e) { } } if(testxmlhttprequest&&document.getelementsbytagname) { document.write("<span style=\"margin-left:1em;\"> <a href=\"javascript:\" class=\"tab \" onclick=\"calldevedge('/viewsource/catalog-new_en.xml',this);return false;\">devedge news</a> <a href=\"javascript...
Visualizing an audio spectrum - Archive of obsolete content
<!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="
true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate ...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
usage insert some html like this into your content: <object classid="clsid:dbb2de32-61f1-4f7f-beb8-a37f5bc24ee2" width="500" height="300"> <param name="type" value="video/quicktime"/> <param name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- custom arguments --> <param name="loop" value="
true"/> </object> the classid attribute tells ie to create an instance of the plug-in hosting control, the width and height specify the dimensions in pixels.
Automated testing tips and tricks - Archive of obsolete content
in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled",
true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome ...
Structure of an installable bundle - Archive of obsolete content
basic structure of a bundle a bundle may include any of the following files: path from the root of the bundle description version information /install.rdf extension/theme install manifest /application.ini application launch manifest /bootstrap.js the bootstrap script for extensions not requiring a restart (those with <em:bootstrap>
true</em:bootstrap> in their install.rdf).
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <rdf:seq about="urn:mozilla:package:root"> <rdf:li resource="urn:mozilla:package:tinderstatus"/> </rdf:seq> <rdf:description about="urn:mozilla:package:tinderstatus" chrome:displayname="mozilla tinderstatus extension" chrome:author="myk melez" chrome:name="tinderstatus" chrome:extension="
true" chrome:description="displays tinderbox status for the mozilla codebase."> </rdf:description> <rdf:seq about="urn:mozilla:overlays"> <rdf:li resource="chrome://navigator/content/navigator.xul"/> </rdf:seq> <rdf:seq about="chrome://navigator/content/navigator.xul"> <rdf:li>chrome://tinderstatus/content/tinderstatusoverlay.xul</rdf:li> </rdf:seq> </rdf:rdf> install.js, on the other h...
In-Depth - Archive of obsolete content
to cut the pieces out you need to define rectangles in the css file like this: #button-send { -moz-image-region: rect(294px 23px 315px 0px); } #button-send:hover { -moz-image-region: rect(294px 46px 315px 23px); } #button-send:hover:active { -moz-image-region: rect(294px 69px 315px 46px); } #button-send[disabled="
true"] { -moz-image-region: rect(294px 92px 315px 69px) !important; } the properties for rect are listed in a clockwise fashion - top, right, bottom, left.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
first, the java application must find a suitable xulrunner installation: mozilla mozilla = mozilla.getinstance(); greversionrange[] range = new greversionrange[1]; range[0] = new greversionrange("1.8.0",
true, "1.9", false); // work with trunk nightly version 1.9a1 ^^ try { file grepath = mozilla.getgrepathwithproperties(range, null); locationprovider locprovider = new locationprovider(grepath); mozilla.initembedding(grepath, grepath, locprovider); } catch (filenotfoundexception e) { // this exception is thrown if gregrepathwithproperties cannot find a gre } catch (xpcomexception e...
Hidden prefs - Archive of obsolete content
mail/news prefs "autcollect addresses" prefs from mailnews.js: // by default, only collect addresses the user sends to (outgoing) pref("mail.collect_email_address_incoming", false); pref("mail.collect_email_address_outgoing",
true); pref("mail.collect_email_address_newsgroup", false); // by default, use the personal addressbook for collection pref("mail.collect_addressbook","moz-abmdbdirectory://abook.mab"); for the reasons why the defaults changed, see this document on the collected address book.
Settings - Archive of obsolete content
}, { name: "password", type: "password", label: "password" } ] }, { name: "facebook", type: "group", label: "facebook", settings: [ { name: "username", type: "text", label: "username", default: "jdoe" }, { name: "password", type: "password", label: "secret" } ] }, { name: "music", type: "boolean", label: "music", default:
true }, { name: "volume", type: "range", label: "volume", min: 0, max: 10, default: 5 } ] }; // import after defining manifest!
Jetpack Snippets - Archive of obsolete content
','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.body.appendchild(firebug); (function(){if(window.firebug.version){firebug.init();}else{settimeout(arguments.callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onselect: function(slide) { slide.slide(800,
true); }}); calling into a slidebar from the global jetpack scope jetpack.slidebar.append({ onready: function (slide) { // call out to a global function, passing the slidebar object exinitslidebar(slide); }, ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelem...
Settings - Archive of obsolete content
}, { name: "password", type: "password", label: "password" } ] }, { name: "facebook", type: "group", label: "facebook", settings: [ { name: "username", type: "text", label: "username", default: "jdoe" }, { name: "password", type: "password", label: "secret" } ] }, { name: "music", type: "boolean", label: "music", default:
true }, { name: "volume", type: "range", label: "volume", min: 0, max: 10, default: 5 } ] }; // import after defining manifest!
Makefile.mozextension.2 - Archive of obsolete content
ote: @echo silent; without @ the command is written in stdout project=test project_name=testworld #~ project_id={xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} project_id=test@testworld.ext project_version=1.0 project_desc="a $(project_name) project with advanced features" project_author=author name # mkdir=$(shell which mkdir) mkdir=/bin/mkdir zipprog=/usr/bin/zip shell = /bin/sh noop = $(shell) -c
true noecho = @ rm_rf=rm -f cp=/bin/cp -i .phony: all all :: make_structure make_files $(noecho) $(noop) package:: make_xpi $(noecho) $(noop) #install :: make_xpi make_install # $(noecho) $(noop) clean :: make_clean $(noecho) $(noop) make_structure: @$(mkdir) $(project) || { echo "creating directory failed; it probably exists.
Monitoring downloads - Archive of obsolete content
onload: function() { // initialization code this.initialized =
true; this.strings = document.getelementbyid("downloadlogger-strings"); this.dlmgr = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); this.dlmgr.addlistener(downloadlogger); // open the database, placing its file in the profile directory this.dbfile = components.classes["@mozilla.org/file/directory...
LIR - Archive of obsolete content
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 void a jump target (no machine code is emitted for this) 42 not in use guards 43 x void exit always 44 xt void exit if
true 45 xf void exit if false 46 xtbl void exit via indirect jump 47 xbarrier void...
Plugin Architecture - Archive of obsolete content
sequence of events in content a content node for a plugin dom element gets created in bindtotree (usually) or another function, it calls loadobject loadobject either notices directly that it is dealing with a plugin, or it starts a network request and notices this in onstartrequest when it realizes that, it tries to create a frame, if anotify is
true and no frame exists yet if a frame exists now, it is asked to instantiate the plugin that was the normal case.
New Skin Notes - Archive of obsolete content
your statement that "it looks odd when someone who uses devmo on regular basis sees some violet links just because he already worked with this site yesterday" holds
true for every single place on the web, yet visited links use different styling on most sites.
Remotely debugging Firefox for Metro - Archive of obsolete content
set up firefox for metro go to about:config in firefox for metro, and set the following required preference: devtools.debugger.remote-enabled =
true you may also want to set these optional preferences: devtools.debugger.force-local = false (if you want to connect from a different machine over the network) devtools.debugger.remote-host (to change the tcp hostname where firefox will listen for connections) devtools.debugger.remote-port (to change the tcp port number where firefox will listen for connections) devtools.debugger.prompt-con...
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 push
true // expected pushnull pushnull lessequals // actual callpropvoid compare_stricteq 3 // use .try / .catch to catch typeerror // convert_o null .try { pushnull convert_o pop findproperty fail pushstring "convert_o null" pushstr...
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.
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
wcondvar(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_secondstointerval(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) ?
DOM Interfaces - Archive of obsolete content
if (element.ownerdocument instanceof ci.nsidomdocumentxbl) { var anonchildren = element.ownerdocument.getanonymousnodes(element); if (anonchildren) { for (var i = 0; i < anonchildren.length; i++) { if (anonchildren[i].nodetype == 1) return false; } } } return
true; ...
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
var xpisrc = "misc.exe"; var vi = "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(); ...
modDateChanged - Archive of obsolete content
err3 = file.moddatechanged(filesource2, err1); logcomment("file.moddatechanged should return '
true' = " + err2); // the reason it expects
true is we're comparing // the return 'time stamp' value for // file1.txt with another file, file2.txt, with a different // 'time stamp' value.
confirm - Archive of obsolete content
acheckstate an object with a boolean value property representing the state of the checkbox: when the dialog box is shown, its checkbox will be checked when this object's value is
true.
wait-cursor - Archive of obsolete content
« xul reference home wait-cursor type: boolean set this attribute to
true to have the cursor switch to a waiting cursor while the mouse is hovering over the element.
How to implement a custom XUL query processor component - Archive of obsolete content
lateresult(adata) { this._data = adata; // just make a random number for the id this._id = 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 ?
How to Quit a XUL Application - Archive of obsolete content
components.interfaces.nsiappstartup.eforcequit : components.interfaces.nsiappstartup.eattemptquit; appstartup.quit(quitseverity); } </script> calling this function if there is an uncaught exception, to force the application to quit: <script> try { dosomething(); } catch (e) { quit(
true); } </script> the "quit" menuitem should typically prompt the user if there is unsaved data: <menuitem label="quit" oncommand="quit(false);"/> ...
Introduction to XUL - Archive of obsolete content
<html:script type="application/javascript"> // dialog initialization code function initwindow() { var checkbox = document.getelementbyid("remember"); if (checkbox) checkbox.checked =
true; } </html:script> javascript can be referenced as in html documents: as onclick handlers and the like.
List of commands - Archive of obsolete content
help cmd_paste - paste a selection from the clipboard cmd_printsetup cmd_quit cmd_redo cmd_savepage cmd_scrollpagedown cmd_scrollpageup cmd_selectall cmd_switchdocumentdirection cmd_switchtextdirection cmd_textzoomenlarge cmd_textzoomreduce cmd_textzoomreset cmd_undo cmd_viewcomponentbar cmd_viewlinktoolbar cmd_viewlinktoolbar_false cmd_viewlinktoolbar_maybe cmd_viewlinktoolbar_
true cmd_viewnavbar cmd_viewpersonaltoolbar cmd_viewtaskbar cmd_zoomwindow thanks for help of joe.user0 in compiling: http://readlist.com/lists/mozilla.or...l/3/15261.html .
onFindAgainCommand - Archive of obsolete content
you should specify
true as the input parameter to perform a "find previous" operation, or false to perform a "find next." example typically, you'll simply bind this method to your "find next" and "find previous" commands, like this: <command name="cmd_find_previous" oncommand="gfindbar.onfindagaincommand(
true);"/> <command name="cmd_find_next" oncommand="gfindbar.onfindagaincommand(false);"/> ...
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.
instantApply - Archive of obsolete content
« xul referenceinstantapplytype: booleanyou can set this attribute to
true to make the preference apply instantly, even when the global setting is not to use instant apply.
isWaiting - Archive of obsolete content
« xul reference iswaiting type: boolean this property is set to
true during the period while waiting for the timeout between the time when a user has pressed a key and a search is performed.
locked - Archive of obsolete content
« xul reference locked type: boolean if
true, the preference has been locked and disabled in the system configuration, preventing the value from being changed.
Providing Command-Line Options - Archive of obsolete content
mmandlinehandler */ handle : function clh_handle(cmdline) { try { // changeme: change "viewapp" to your command line flag that takes an argument var uristr = cmdline.handleflagwithparam("viewapp", false); if (uristr) { // convert uristr to an nsiuri var uri = cmdline.resolveuri(uristr); openwindow(chrome_uri, uri); cmdline.preventdefault =
true; } } catch (e) { components.utils.reporterror("incorrect parameter passed to -viewapp on the command line."); } // changeme: change "myapp" to your command line flag (no argument) if (cmdline.handleflag("myapp", false)) { openwindow(chrome_uri, null); cmdline.preventdefault =
true; } }, // changeme: change the help info as appropriate, but /...
RDF Modifications - Archive of obsolete content
for instance, an assert call looks like the following: var source = rdf.getresource("http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg"); var predicate = rdf.getresource("http://purl.org/dc/elements/1.1/description"); var target = rdf.getliteral("one of the thirty or so egyptian obelisks"); datasource.assert(source, predicate, target,
true); the assert call adds a new triple to the rdf datasource.
RDF Query Syntax - Archive of obsolete content
internally, this isn't quite
true; the builder actually maintains only one copy of the similar data but uses data structures in such a way which make it appear as if it were duplicated.
Static Content - Archive of obsolete content
<radiogroup datasources="template-guide-photos4.rdf" ref="http://www.daml.org/2001/09/countries/country-ont#country" onselect="applyfilter(event.target.value);"> <radio label="all" selected="
true"/> <template> <query> <content uri="?start"/> <triple subject="?country" predicate="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" object="?start"/> <triple subject="?country" predicate="http://purl.org/dc/elements/1.1/title" object="?countrytitle"/> </query> <action> <radio uri="?country" label="?coun...
Using Recursive Templates - Archive of obsolete content
<vbox id="row2" container="
true" empty="false" class="indent"> <label value="male"/> <vbox id="row4" class="indent"><label value="napoleon bonaparte"/></vbox> <vbox id="row5" class="indent"><label value="julius caesar"/></vbox> <vbox id="row6" class="indent"><label value="ferdinand magellan"/></vbox> </vbox> <vbox id="row3" container="
true" empty="false" class="indent"> <label value="female"/> <vbox ...
Adding HTML Elements - Archive of obsolete content
<html:img src="banner.jpg"/> <html:input type="checkbox" value="
true"/> <html:table> <html:tr> <html:td> a simple table </html:td> </html:tr> </html:table> these examples will create an image from the file banner.jpg, a checkbox and a single-cell table.
Adding Style Sheets - Archive of obsolete content
nuitem label="size"/> <menuitem label="date modified"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="searchmode"> <menupopup> <menuitem label="is"/> <menuitem label="is not"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="find-text" flex="1" editable="
true" datasources="file:///mozilla/recents.rdf" ref="http://www.xulplanet.com/rdf/recent/all"/> ...
Advanced Rules - Archive of obsolete content
you can view the rdf file separately: wheater.rdf example 1 : source <tree id="weathertree" flex="1" datasources="weather.rdf" ref="http://www.xulplanet.com/rdf/weather/cities"> <treecols> <treecol id="city" label="city" primary="
true" flex="1"/> <treecol id="pred" label="prediction" flex="1"/> </treecols> <template> <rule> <conditions> <content uri="?list"/> <member container="?list" child="?city"/> <triple subject="?city" predicate="http://www.xulplanet.com/rdf/weather#name" object="?name"/> <triple subject="?city" predicate="h...
More Event Handlers - Archive of obsolete content
example 2 : source view <hbox id="outerbox"> <button id="okbutton" label="ok"/> </hbox> <script> function buttonpressed(event){ alert('button was pressed!'); } function boxpressed(event){ alert('box was pressed!'); event.stoppropagation(); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command',buttonpressed,
true); var outerbox = document.getelementbyid("outerbox"); outerbox.addeventlistener('command',boxpressed,
true); </script> here, an event listener has been added to the button and another event listener has been added to the box.
Popup Menus - Archive of obsolete content
let's have the popup appear when clicking over the first tab panel: <popupset> <menupopup id="editpopup"> <menuitem label="cut" accesskey="t"/> <menuitem label="copy" accesskey="c"/> <menuitem label="paste" accesskey="p" disabled="
true"/> </menupopup> </popupset> <vbox flex="1"> .
Progress Meters - Archive of obsolete content
<textbox id="find-text"/> <html:progress value="50" max="100" style="margin: 4px;"/> <button id="find-button" label="find" default="
true"/> the value has been set to 50% so that we can see the meter on the window.
RDF Datasources - Archive of obsolete content
the rdf file is fairly large and can be viewed separately: source rdf example 2 : source view <tree flex="1" width="200" height="200" datasources="animals.rdf" ref="http://www.some-fictitious-zoo.com/all-animals"> <treecols> <treecol id="name" label="name" primary="
true" flex="1"/> <treecol id="species" label="species" flex="1"/> </treecols> <template> <rule> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:http://www.some-fictitious-zoo.com/rdf#name"/> <treecell label="rdf:http://www.some-fictitious-zoo.com/rdf#species"/> </treerow> </treeitem> </treechildren> ...
XUL Event Propagation - Archive of obsolete content
in another example, an onload event handler for a xul window can register a box element to capture all the click events that are raised from its child elements: var bbox = document.getelementbyid("bigbox"); if (bbox) bbox.addeventlistener("click", function() { alert('captured'); },
true); ...
commandset - Archive of obsolete content
attributes commandupdater, events, oncommandupdate, targets example <commandset> <command id="cmd_open" oncommand="alert('open!');"/> <command id="cmd_help" oncommand="alert('help!');"/> </commandset> attributes commandupdater type: boolean if
true, the commandset is used for updating commands.
grid - Archive of obsolete content
<groupbox> <caption label="details"/> <grid> <columns> <column flex="1"/> <column flex="2"/> </columns> <rows> <row> <label value="user name"/> <textbox id="user"/> </row> <row> <label value="group"/> <menulist> <menupopup> <menuitem label="accounts"/> <menuitem label="sales" selected="
true"/> <menuitem label="support"/> </menupopup> </menulist> </row> </rows> </grid> </groupbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertb...
menubar - Archive of obsolete content
attributes grippyhidden, statusbar properties accessibletype, statusbar examples <menubar id="sample-menubar"> <menu id="action-menu" label="action"> <menupopup id="action-popup"> <menuitem label="new"/> <menuitem label="save" disabled="
true"/> <menuitem label="close"/> <menuseparator/> <menuitem label="quit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> attributes grippyhidden seamonkey only type: boolean when set to
true, the grippy will be hidden.
progressmeter - Archive of obsolete content
attributes max, mode, value properties accessibletype, max, mode, value examples <progressmeter mode="determined" value="82"/> <progressmeter mode="undetermined"/> <!-- switching modes while the mouse is over a button --> <progressmeter mode="determined" id="myprogress"/> <button label="example" onmouseover="setloading(
true)" onmouseout="setloading(false)"/> function setloading(state){ document.getelementbyid('myprogress').mode = (state) ?
resizer - Archive of obsolete content
attributes dir, element, type examples resizing a window <window xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul" hidechrome="
true" windowtype="main" orient="vertical" sizemode="normal" width="400" height="300" persist="screenx screeny width height"> <hbox flex="1"> <vbox width="2" style="background-color: grey;"> <resizer dir="topleft" height="2" style="cursor: nw-resize;"/> <resizer dir="left" flex="1" style="cursor: w-resize;"/> <resizer dir="bottomleft" height="2" style="cursor: sw-resize;"/> </vbox> ...
splitter - Archive of obsolete content
<tree id="tree1" flex="1" height="300" enablecolumndrag="
true"> <treecols> <treecol id="name" label="name" flex="1"/> <splitter class="tree-splitter"/> <treecol id="id" label="id" flex="1"/> <splitter class="tree-splitter"/> <treecol id="date" label="date" flex="1"/> <splitter class="tree-splitter"/> </treecols> <treechildren/> </tree> splitter resizing and overflow the degree to which a splitter will resize a box, and what ...
toolbaritem - Archive of obsolete content
examples <toolbaritem> <menulist label="bus"> <menupopup> <menuitem label="car"/> <menuitem label="taxi"/> <menuitem label="bus" selected="
true"/> <menuitem label="train"/> </menupopup> </menulist> </toolbaritem> <toolbaritem id="sample-toolbutton-unified"> <toolbarbutton id="myext-button1" class="toolbarbutton-1" label="label1" /> <toolbarbutton id="myext-button2" class="toolbarbutton-1" label="labe2l" /> </toolbaritem> attributes inherited from xul element align, allowevents, allown...
toolbox - Archive of obsolete content
w" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="toolbox example" width="300"> <toolbox> <toolbar> <toolbarbutton label="back"/> <toolbarbutton label="forward"/> <toolbarbutton label="home"/> </toolbar> <toolbar> <toolbarbutton label="stop"/> <toolbarbutton label="reload"/> </toolbar> </toolbox> <textbox multiline="
true" value="we have two toolbars inside of one toolbox above." width="20"/> </window> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, ...
treechildren - Archive of obsolete content
attributes alternatingbackground attributes alternatingbackground obsolete since gecko 2.0 type: boolean if
true, the background of the tree's rows will alternate between two colors.
Building XULRunner with Python - Archive of obsolete content
using python in xul applications add the following to yourprefs.js during development pref("browser.dom.window.dump.enabled",
true); pref("javascript.options.showinconsole",
true); pref("javascript.options.strict",
true); pref("nglayout.debug.disable_xul_cache",
true); pref("nglayout.debug.disable_xul_fastload",
true); html <script> tags specify that python is used withtype="application/x-python" attribute.
Dialogs in XULRunner - Archive of obsolete content
tekeeper/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"/> <radiogroup> <radio id="1" label="oranges because they are fruity"/> <radio id="2" selected="
true" label="strawberries because of color"/> <radio id="3" label="bananna becaus...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
client.charset + "\"", < beforesend: function(req) { < req.setrequestheader("method", "post"); < req.setrequestheader("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,...
xulauncher - Archive of obsolete content
me.manifest file ############################################################################## echo " content $xulname file:$xulname/ ">$xulmanifest # create prefs.js file ############################################################################## echo " pref(\"toolkit.defaultchromeuri\", \"chrome://$xulname/content/$xulfile\"); /* debugging prefs */ pref(\"browser.dom.window.dump.enabled\",
true); pref(\"javascript.options.showinconsole\",
true); pref(\"javascript.options.strict\",
true); pref(\"nglayout.debug.disable_xul_cache\",
true); pref(\"nglayout.debug.disable_xul_fastload\",
true); ">$xulprefs # copy xul file to right location and run it ############################################################################## cp $xulfile $xuldir xulrunner $xulappini $@ ...
Adobe Flash - Archive of obsolete content
mands demonstrated in example 3: <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" id="myflash" width="250" height="150" viewastext> <param name="movie" value="js2flash.swf" /> <param name="quality" value="high"></param> <embed src="js2flash.swf" width="250" height="150" swliveconnect="
true" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" name="myflash"> </embed> </object> .....
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
rn:mozilla:install-manifest"> <em:id>mypluginid@myplugin.com</em:id> <em:name>my plugin</em:name> <em:version>1.0</em:version> <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>1.5</em:minversion> <em:maxversion>4.0.*</em:maxversion> </description> </em:targetapplication> <em:unpack>
true</em:unpack> </description> </rdf> this contains 5 required pieces of information.
Introduction to Public-Key Cryptography - Archive of obsolete content
however, it's important to note that these two assumptions are
true only if unauthorized personnel have not gained access to the user's machine or password, the password for the client software's private key database has been set, and the software is set up to request the password at reasonable frequent intervals.
Developing cross-browser and cross-platform pages - Archive of obsolete content
// bad sample if (navigator.appversion.charat(0) == "8") { if (navigator.appname == "netscape") { isns8 =
true; alert("netscape 8"); }; } else if (navigator.appversion.indexof("msie") != -1) { isie =
true; alert("internet explorer"); }; while this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when internet explorer 8 is released or when an opera 8.x user visits the page or even when an user with any non-netscape browser starting with a "8" c...
Using workers in extensions - Archive of obsolete content
shinformation() { if (!symbol) { throw "no symbol set!"; } var fullurl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function inforeceived() { var output = httprequest.responsetext; if (output) { postmessage(output.trim()); } httprequest = null; } var httprequest = new xmlhttprequest(); httprequest.open("get", fullurl,
true); httprequest.onload = inforeceived; httprequest.send(null); } setinterval(function() { refreshinformation(); }, 10*60*1000); onmessage = function(event) { if (event.data) { symbol = event.data.touppercase(); } refreshinformation(); } when the worker thread is started, the main body of this code (in lines 26-35) is executed.
-ms-filter - Archive of obsolete content
terfrom.filters.item(0).transition=12; imagefrom.style.visibility = "hidden"; filterto.style.visibility = ""; filterfrom.filters.item(0).play(14); } </script> </body> gradient progid:dximagetransform.microsoft.gradient( <properties> ) where <properties> = [ <enabled> | <endcolor> | <endcolorstr> | <gradienttype> | <startcolor> | <startcolorstr> ]# where <enabled> = 'enabled=' [
true | false ] <endcolor> = 'startcolor=' <color> <endcolorstr> = 'startcolorstr=' <color> <gradienttype> = 'gradienttype=' <integer> <startcolor> = 'startcolor=' <color> <startcolorstr> = 'startcolorstr=' <color> enabled default:
true set to false to disable.
Introduction - Archive of obsolete content
the most basic is appendchild var element1 = <foo/>; var element2 = <bar/>; element1.appendchild(element2); which produces exactly the xml document you'd expect <foo> <bar/> </foo> javascript variables the
true power of e4x only begins to come to light, however, when the xml document can interact closely with other javascript.
Iterator - Archive of obsolete content
name, value] in iterator(a)) { console.log(name, value); // x 10 // y 20 } iterating with for-of var a = { x: 10, y: 20, }; for (var [name, value] of iterator(a)) { // @@iterator is used console.log(name, value); // x 10 // y 20 } iterates over property name var a = { x: 10, y: 20, }; for (var name in iterator(a,
true)) { console.log(name); // x // y } passing generator instance function* f() { yield 'a'; yield 'b'; } var g = f(); console.log(g == iterator(g)); //
true for (var v in iterator(g)) { console.log(v); // a // b } passing iterator instance var a = { x: 10, y: 20, }; var i = iterator(a); console.log(i == iterator(i)); //
true spec...
Expression closures - Archive of obsolete content
examples a shorthand for binding event listeners: document.addeventlistener('click', function() false,
true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) elem.type == 'text'); ...
Function.prototype.isGenerator() - Archive of obsolete content
examples function f() {} function* g() { yield 42; } console.log('f.isgenerator() = ' + f.isgenerator()); // f.isgenerator() = false console.log('g.isgenerator() = ' + g.isgenerator()); // g.isgenerator() =
true specifications not part of any standard.
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
}, 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
}, 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.
JavaObject - Archive of obsolete content
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.
Packages - Archive of obsolete content
examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner = new packages.java.awt.frame(); var thewindow = new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(
true); } in the previous example, the function instantiates thewindow as a new packages object.
XForms Range Element - Archive of obsolete content
characteristics analogous widget is <xul:scale/>, which is available in fx 3.0 only if the incremental attribute has the value
true, the value of the bound node will be updated upon each movement of the slider's thumb.
XForms Secret Element - Archive of obsolete content
characteristics analogous widgets are <xhtml:input type="password"/> and <xul:textbox type="password"/> if the incremental attribute is present and has the value
true, then the bound instance node is updated on every user input.
XForms Select1 Element - Archive of obsolete content
incremental - supported, default value is
true properties selection - see corresponding attribute incremental - see corresponding attribute type restrictions the select1 element can be bound to a node containing simple content.
Displaying a graphic with audio samples - Archive of obsolete content
<!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="
true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { chann...
Building up a basic demo with A-Frame - Game development
add this just before the closing </a-scene> element: <a-camera position="0 1 4" cursor-visible="
true" cursor-scale="2" cursor-color="#0095dd" cursor-opacity="0.5"> </a-camera> we've also defined a cursor for the given camera, using the cursor-* attributes (by default it is invisible.) — we've set its scale so it will more easily visible, its color, and some opacity so it won't completely covering the objects behind it.
Building up a basic demo with Three.js - Game development
var renderer = new three.webglrenderer({antialias:
true}); renderer.setsize(width, height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); we are creating a new webgl renderer, setting its size to fit the whole available space on the screen, and appending the dom structure to the page.
GLSL Shaders - Game development
sition = projectionmatrix * modelviewmatrix * vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } </script> <script id="fragmentshader" type="x-shader/x-fragment"> void main() { gl_fragcolor = vec4(0.0, 0.58, 0.86, 1.0); } </script> javascript var width = window.innerwidth; var height = window.innerheight; var renderer = new three.webglrenderer({antialias:
true}); renderer.setsize(width, height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); var scene = new three.scene(); var camera = new three.perspectivecamera(70, width/height); camera.position.z = 50; scene.add(camera); var boxgeometry = new three.boxgeometry(10, 10, 10); var shadermaterial = new three.shadermaterial( { ...
Mobile touch controls - Game development
moving the player could be managed by creating the four directional buttons, but we can take the advantage of touch screens and drag the player's ship around: var player = this.game.add.sprite(30, 30, 'ship'); player.inputenabled =
true; player.input.enabledrag(); player.events.ondragstart.add(ondragstart, this); player.events.ondragstop.add(ondragstop, this); function ondragstart(sprite, pointer) { // do something when dragging } we can pull the ship around and do something in the meantime, and react when the drag is stopped.
Bounce off the walls - Game development
we could merge those two statements into one to save on code verbosity: if(y + dy > canvas.height || y + dy < 0) { dy = -dy; } if either of the two statements is
true, reverse the movement of the ball.
Collision detection - Game development
for the center of the ball to be inside the brick, all four of the following statements need to be
true: the x position of the ball is greater than the x position of the brick.
Create the Canvas and draw on it - Game development
it takes six parameters: x and y coordinates of the arc's center arc radius start angle and end angle (what angle to start and finish drawing the circle, in radians) direction of drawing (false for clockwise, the default, or
true for anti-clockwise.) this last parameter is optional.
Animations and tweens - Game development
that's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, phaser.easing.elastic.out,
true, 100); this tween will double the brick's scale in half a second using elastic easing, will start automatically, and have a delay of 100 miliseconds.
Bounce off the walls - Game development
add this line right after the existing game.physics.enable() method call: ball.body.collideworldbounds =
true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce.
Buttons - Game development
now we need to define the startgame() function referenced in the code above: function startgame() { startbutton.destroy(); ball.body.velocity.set(150, -150); playing =
true; } when the button is pressed, we remove the button, sets the ball's initial velocity and set the playing variable to
true.
Extra lives - Game development
add the ballleavescreen() function definition at the end of our code: function ballleavescreen() { lives--; if(lives) { livestext.settext('lives: '+lives); lifelosttext.visible =
true; ball.reset(game.world.width*0.5, game.world.height-25); paddle.reset(game.world.width*0.5, game.world.height-5); game.input.ondown.addonce(function(){ lifelosttext.visible = false; ball.body.velocity.set(150, -150); }, this); } else { alert('you lost, game over!'); location.reload(); } } instead of instantly pr...
Game over - Game development
add the following lines just below the previous new one: ball.checkworldbounds =
true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event.
Physics - Game development
final code check the latest code should look like this: var ball; function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally =
true; game.scale.pagealignvertically =
true; game.stage.backgroundcolor = '#eee'; game.load.image('ball', 'img/ball.png'); } function create() { game.physics.startsystem(phaser.physics.arcade); ball = game.add.sprite(50, 50, 'ball'); game.physics.enable(ball, phaser.physics.arcade); ball.body.velocity.set(150, 150); } function update() { } try reloading index.html again...
Scaling - Game development
update your existing preload() function as follows: function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally =
true; game.scale.pagealignvertically =
true; } scalemode has a few different options available for how the canvas can be scaled: no_scale — nothing is scaled.
Win the game - Game development
add the following new code into your ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive ==
true) { count_alive++; } } if (count_alive == 0) { alert('you won the game, congratulations!'); location.reload(); } } we loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method.
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()!
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", ...
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
in ember, you can conditionally render parts of the template using conditional content; a simple block example looks something like this: {{#if this.thingis
true}} content for the block form of "if" {{/if}} so let's try replacing this part of footer.hbs: <strong>{{this.todos.incomplete.length}}</strong> todos left with the following: <strong>{{this.todos.incomplete.length}}</strong> {{#if this.todos.incomplete.length === 1}} todo {{else}} todos {{/if}} left this will give us an error, however — in ember, these simple if statemen...
Deployment and next steps - Learn web development
if we have a look at the rollup.config.js file, we can see that the svelte compiler is just a rollup plugin: import svelte from 'rollup-plugin-svelte'; [...] import { terser } from 'rollup-plugin-terser'; const production = !process.env.rollup_watch; export default { input: 'src/main.js', output: { sourcemap:
true, format: 'iife', name: 'app', file: 'public/build/bundle.js' }, plugins: [ svelte({ // enable run-time checks when not in production dev: !production, // we'll extract any component css out into // a separate file - better for performance css: css => { css.write('public/build/bundle.css'); } }), later on in the same file you'l...
Command line crash course - Learn web development
tter programs exist for providing a terminal experience on windows, such as powershell (see here to find installers), and gitbash (which comes as part of the git for windows toolset) however, the best option for windows in the modern day is the windows subsystem for linux (wsl) — a compatibility layer for running linux operating systems directly from inside windows 10, allowing you to run a “
true terminal” directly on windows, without needing a virtual machine.
CSUN Firefox Materials
many users are finding the
true greatness of firefox lies in support for third party extensions.
Testopia
new reports: worst offender and case roll-up set priorities on indidual case-runs new clone options uses the latest extjs 3.0 library converts testopia into a
true bugzilla extension numerous bug fixes integration points testopia integrates with bugzilla products, components, versions, and milestones to allow a single management interface for high level objects.
What to do and what not to do in Bugzilla
the same is
true for editbugs: leave comments with the information you'd like to be able to edit into the bug, and that will help you get the editbugs permissions quickly.
Creating a spell check dictionary add-on
<?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>locale-code@dictionaries.addons.mozilla.org</em:id> <em:version>version number</em:version> <em:type>64</em:type> <em:unpack>
true</em:unpack> <em:name>name</em:name> <!-- other install.rdf metadata such as em:localized, em:description, em:creator, em:developer, em:translator, em:contributor or em:homepageurl --> <!-- firefox --> <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>18.0a1</em:minversion> ...
Adding APIs to the navigator object
programmatically adding an object to navigator var categorymanager = components.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); categorymanager.addcategoryentry("javascript-navigator-property", "myapi", my_contract_id, false,
true); this adds a new object, myapi, to the window.navigator object.
Obsolete Build Caveats and Tips
this note below seems redundant as this is
true by default https://msdn.microsoft.com/en-us/library/dh8che7s%28v=vs.110%29.aspx note: starting with gecko 7.0, you should no longer include "-zc:wchar_t-" in the command line when building on windows.
mach
here is a minimal mach command module: from __future__ import print_function, unicode_literals from mach.decorators import ( commandargument, commandprovider, command, ) @commandprovider class machcommands(object): @command('doit', description='run it!') @commandargument('--debug', '-d', action='store_
true', help='do it in debug mode.') def doit(self, debug=false): print('i did it!') from mach.decorators we import some python decorators which are used to define what python code corresponds to mach commands.
Limitations of chrome scripts
for example: addeventlistener("load", handler,
true) // for example if you need to contact the chrome process when that happens, send it a message.
Process scripts
the following code uses the global parent process message manager, which will load the script into the the chrome process and any child processes: // chrome code let ppmm = cc["@mozilla.org/parentprocessmessagemanager;1"] .getservice(ci.nsiprocessscriptloader); ppmm.loadprocessscript("chrome://whatever/process-script.js",
true); ppmm.addmessagelistener("hello", function(msg) { ...
HTMLIFrameElement.clearMatch()
searchtoggle.addeventlistener('touchend',function() { if(search.getattribute('class') === 'search') { search.setattribute('class', 'search shifted'); } else if(search.getattribute('class') === 'search shifted') { search.setattribute('class', 'search'); if(searchactive) { browser.clearmatch(); searchactive = false; prev.disabled =
true; next.disabled =
true; searchbar.value = ''; } } }); specification not part of any specification.
HTMLIFrameElement.findAll()
searchform.addeventlistener('submit', function(e) { e.preventdefault(); browser.findall(searchbar.value, 'case-sensitive'); searchactive =
true; prev.disabled = false; next.disabled = false; searchbar.blur(); }); specification not part of any specification.
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.
mozbrowsercontextmenu
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.
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.
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.reload()
parameters hardreload optional a boolean that indicates whether all the resources to reload must be revalidated (
true) or may be taken directly from the browser cache (false).
:-moz-lwtheme-brighttext
the :-moz-lwtheme-brighttext pseudo-class matches in chrome documents when :-moz-lwtheme is
true and a lightweight theme with a bright text color is selected.
:-moz-lwtheme-darktext
the :-moz-lwtheme-darktext pseudo-class matches in chrome documents when :-moz-lwtheme is
true and a lightweight theme with a dark text color is selected.
:-moz-lwtheme
the :-moz-lwtheme pseudo-class matches in chrome documents when the root element's lightweightthemes attribute is
true and a theme is selected.
Chrome-only CSS reference
it only works in chrome code, and only on mac os x.:-moz-lwthemethe :-moz-lwtheme pseudo-class matches in chrome documents when the root element's lightweightthemes attribute is
true and a theme is selected.:-moz-lwtheme-brighttextthe :-moz-lwtheme-brighttext pseudo-class matches in chrome documents when :-moz-lwtheme is
true and a lightweight theme with a bright text color is selected.:-moz-lwtheme-darktextthe :-moz-lwtheme-darktext pseudo-class matches in chrome documents when :-moz-lwtheme is
true and a lightweight theme with a dark text color is selected.::-moz-tree-cella...
Embedding the editor
thence, lots of javascript in editor.js, composercommands.js and the various dialog js files assume that they can get at the one
true editor via window.editorshell.
How to Report a Hung Firefox
appinfo = components.classes["@mozilla.org/xre/app-info;1"];if (appinfo && appinfo.getservice(components.interfaces.nsixulruntime).processtype != components.interfaces.nsixulruntime.process_type_default) {components.utils.import("resource://gre/modules/ctypes.jsm");var zero = new ctypes.intptr_t(8);var badptr = ctypes.cast(zero, ctypes.pointertype(ctypes.int32_t));var crash = badptr.contents;}',
true); } other techniques on os x if you use a nightly build (>= firefox 16), you can use activity monitor's "sample process" feature to generate a sample.
IPDL Best Practices
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.
Creating a New Protocol
writing the tests protocols which are managed by pbrowser must be tested using the mochitest-chrome test framework with a <browser remote="
true">.
IPDL Type Serialization
param.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.
Integrated Authentication
if you wish to use non-fully-qualified entries of the form mydomain.com in the above preferences for ntlm and spnego authentication, you will also need to set the preferences network.automatic-ntlm-auth.allow-non-fqdn and network.negotiate-auth.allow-non-fqdn (respectively) to
true.
Code Samples
var beinguninstalled; let listener = { onuninstalling: function(addon) { if (addon.id == "youraddon@youraddon.com") { beinguninstalled =
true; } }, onoperationcancelled: function(addon) { if (addon.id == "youraddon@youraddon.com") { beinguninstalled = (addon.pendingoperations & addonmanager.pending_uninstall) != 0; } } } try { components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.addaddonlistener(listener); } catch (ex) {} ...
InstallListener
void onexternalinstall( in addon addon, in addon existingaddon, in boolean needsrestart ) parameters addon the newly installed addon existingaddon an addon that will be replaced by this install or null if no add-on is being replaced needsrestart
true if the installation requires a restart ...
TypeListener
void ontypeadded( in addontype type ) parameters type the addontype that is being added needsrestart
true if an application restart is necessary for the change to take effect ontyperemoved() called when an add-on type has been removed.
Add-on Repository
issearching boolean
true if a search is currently in progress; otherwise false.
AsyncShutdown.jsm
return value returns
true if a blocker has been removed, or false otherwise.
DownloadList
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.
PerfMeasurement.jsm
return value if even one of the event types can be recorded, this will return
true.
Index
here, we'll continue to stay
true to the original intent of this guide and only present you with the technical information you need to become an official release.
Release phase
here, we'll continue to stay
true to the original intent of this guide and only present you with the technical information you need to become an official release.
Localization technical reviews
more intl.properties checkpoints, cont we also check the plural rule for the locale, that the general.useragent.locale is set to the locale code, that accept-lang shows the locale code(s) (like ab, ab-cd,...) and is followed by en and en-us, and finally that intl.menuitems.insertseparatorbeforeaccesskeys =
true, where "
true" should be left untranslated.
gettext
this is particularly
true for short strings, like "file" or "log in".
MathML Demo: <mspace> - space
e="decrease height">-</a> width <a class="control" href="javascript:upwidth();" title="increase width">+</a>/ <a class="control" href="javascript:downwidth();" title="decrease width">-</a> depth <a class="control" href="javascript:updepth();" title="increase depth">+</a>/ <a class="control" href="javascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="
true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> javascript content var height=0; var width=0; var depth=0; function upheight() { height++; document.getelementbyid("thespace").setattribute("height",height+".1ex"); } function downheight() { height--; docu...
Mozilla Web Developer FAQ
downloadable fonts in
truetype and opentype formats (.ttf and .otf) are supported since firefox 3.5.
Mozilla Style System
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(); ...
Scroll-linked effects
crolly) < 200) { scrollto(window.scrollx, window.scrolly + ((destination - window.scrolly) / 2)); settimeout(snap, 20, destination); } } var timeoutid = null; addeventlistener("scroll", function() { if (timeoutid) cleartimeout(timeoutid); timeoutid = settimeout(snap, 200, parseint(document.getelementbyid('snaptarget').style.top)); },
true); </script> <div id="snaptarget" class="snaptarget" style="position: relative; top: 200px; width: 100%; height: 200px; background-color: green"></div> </body> in this example, there is a scroll event listener which detects if the scroll position is within 200 pixels of the top of the "snaptarget" div.
browser.altClickSave
type:boolean default value: false exists by default: yes application support:firefox 13.0 status: active; last updated 2012-03-19 introduction: pushed to nightly on 2012-03-02 bugs: bug 713052 values
true clicking a link while holding the alt key starts the download of that link.
browser.dom.window.dump.file
browser.dom.window.dump.file redirects the ouput of window.dump() calls to a file whose address is specified in this preference if browser.dom.window.dump.enabled is set to
true.
browser.search.context.loadInBackground
type:boolean default value:false exists by default: yes application support: firefox 13.0 status: active; last updated 2012-02-17 introduction: pushed to nightly on 2012-02-15 bugs: bug 727131 values
true new tab with search results will be opened in the background, focus stays on the current tab.
browser.urlbar.formatting.enabled
type:boolean default value:
true exists by default: yes application support:firefox 6.0 status: active; last updated 2012-04-03 introduction: pushed to nightly on 2011-05-03 bugs: bug 451833 values
true (default) the domain name including the top level domain is highlighted in the address bar by coloring it black and the other parts grey.
browser.urlbar.trimURLs
type:boolean default value:
true exists by default: yes application support:firefox 7.0 status: active; last updated 2012-04-03 introduction: pushed to nightly on 2011-06-23 bugs: bug 665580 values
true (default) if the active url is exactly the domain name, the trailing slash (/) behind the top level domain will be hidden.
dom.event.clipboardevents.enabled
type:boolean default value:
true exists by default: no application support: gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) status: active; last updated 2012-02-15 introduction: pushed to nightly on 2012-02-14 bugs: bug 542938 values
true (default) the oncopy, oncut and onpaste events are enabled for web content.
PR_STATIC_ASSERT
syntax #include <prlog.h> pr_static_assert ( expression ); parameters the macro has this parameter: expression any valid expression which evaluates at compile-time to
true or false.
PR_SetConcurrency
since global threads are scheduled by the host operating system, this model is particularly applicable to multiprocessor architectures, where
true parallelism is possible.
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.
JSS FAQ
upgrade to the latest jss, or, in the cryptomanager.initializationvalues object you pass to cryptomanager.initialize(), set removesunproivider=
true.
NSS 3.17 release notes
the ssl_reuse_server_ecdhe_key option defaults to pr_
true, which means the server's ephemeral ecdh key is reused for multiple handshakes.
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'; } /* decrypt buf2, result will be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &out...
NSS Sample Code sample6
* 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_fin...
Python binding for NSS
certificate() constructor signature changed from certificate(data=none, der_is_signed=
true) to certificate(data, certdb=cert_get_default_certdb(), perm=false, nickname=none) this change was necessary because all certs should be added to the nss temporary database when they are loaded, but earlier code failed to to that.
FC_GetSlotList
syntax ck_rv fc_getslotlist( ck_bbool tokenpresent, ck_slot_id_ptr pslotlist, ck_ulong_ptr pulcount ); parameters tokenpresent [in] if
true only slots with a token present are included in the list, otherwise all slots are included.
FC_GetTokenInfo
if login is required (which is
true for the fips mode of operation), this flag means the user's password has been initialized.
sslcrt.html
pr_
true means certificate signatures are to be checked.
Necko Architecture
the channel does the
true work of protocol interpretation and data movement (if any).
Pork Tools
then nuke the declaration // nsresult rv; // move outparam to 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>.
Rhino shell
note if the shell is invoked with the system property rhino.use_java_policy_security set to
true and with a security manager installed, the shell restricts scripts permissions based on their urls according to java policy settings.
SpiderMonkey Build Documentation
ompiler cannot create executables." you can try configuring like so: cc=clang cxx=clang++ ../configure it is also possible that baldrdash may fail to compile with /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found, err:
true this is because, starting from mohave, headers are no longer installed in /usr/include.
Hacking Tips
bool codegeneratorx86shared::visitguardshape(lguardshape *guard) { if (info().script()->lineno == 16934 && guard->id() == 522) { [… another impl only for this one …] return
true; } [… old impl …] [hack] spewing all compiled code i usually just add this to the apropriate executablecopy.
How to embed the JavaScript engine
* args.rval().setint32(args[0].toint32() + args[1].toint32()); */ return
true; } then to wire it up to js, you could write: ok = js_definefunction(cx, global, "doit", doit, doit_minargs, 0); or, if you had a bunch of native functions to define, you would probably put them in a table: static jsfunctionspec my_functions[] = { js_fn("doit", doit, doit_minargs, 0), /* etc...
Exact Stack Rooting
however, this does not hold
true for temporaries: they are undeclared, after all.
Statistics API
var prefs = require("api-utils/preferences-service"); components.utils.import('resource://gre/modules/services.jsm'); function observer(subject, topic, json) { var data = json.parse(json); // process the data } prefs.set("javascript.options.mem.notify",
true); services.obs.addobserver(observer, "garbage-collection-statistics", false); the toplevel json object contains these fields: timestamp: integer (microseconds) - time at which the gc ended, measured from epoch.
Property cache
entry value words for the .vword member of a non-adding property cache entry, one of the following is
true: vword.isshape() vword.toshape() points to the js::shape that describes the property in question.
SpiderMonkey Internals
there are a few special values: nullvalue(), undefinedvalue(),
truevalue() and falsevalue().
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).
JS::AutoIdArray
methods method description bool operator!() const return
true if this has no owned array.
JS::BooleanValue
see also mxr id search for js::booleanvalue js::value js::
truevalue js::falsevalue ...
JS::ToUint16
on success, js::toint16 stores the converted value in *out and returns
true.
JS::ToUint32
on success, js::touint32 stores the converted value in *out and returns
true.
JS::ToUint64
on success, js::toint64 stores the converted value in *out and returns
true.
JS::UndefinedHandleValue
see also mxr id search for js::undefinedhandlevalue js::nullhandlevalue js::
truehandlevalue js::falsehandlevalue bug 865969 ...
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.flags
an object obj that emulates undefined behaves like any other object, except in the following ways: typeof obj === "undefined" obj converts to false when obj is converted to a boolean when used in boolean contexts (if conditions, loop continuation/termination conditions [for/while/do { } while], the condition in a ternary ?: expression, and so on) (obj == undefined) is
true, and (obj != undefined) is false (obj == null) is
true, and (obj != null) is false == and != comparisons to values other than null or undefined (including to an object that emulates undefined) are unaffected by this flag.
JSClass
* 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, null, null, null); } see also mxr id search for jsclass jsclass.flags js_getclass js_initclass js_newobject js_newobjectforconstructor js_instanceof bug 638291 - added trace bug 702507 - removed jsclass_construct_prototype bug 726944 - removed xdrobject, reserved0 and reserved1 b...
JSConvertOp
(support for the other types may eventually be removed.) the callback returns
true to indicate success or false to indicate failure.
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.
JSIteratorOp
keysonly jsbool if
true, the iterator should yield keys only, not [key, value] pairs.
Querying Places
queryoptions var options = placesutils.history.getnewqueryoptions(); // execute the query // see : https://developer.mozilla.org/en/nsinavhistoryservice#executequery() var result = placesutils.history.executequery(query, options); // using the results by traversing a container // see : https://developer.mozilla.org/en/nsinavhistorycontainerresultnode var cont = result.root; cont.containeropen =
true; for (var i = 0; i < cont.childcount; i ++) { var node = cont.getchild(i); // "node" attributes contains the information (e.g.
extIExtension
enabled readonly attribute boolean
true if the extension is currently enabled.
extISessionStorage
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.
XPCOM array guide
for instance: pr_callback prbool getfirstvisible(nsielement* element, void* closure) { prbool isvisible; element->isvisible(&isvisible); // stop at first object if (isvisible) { ns_static_cast(closureobject*,closure)->element = element; return pr_false; } return pr_
true; } ...
Avoiding leaks in JavaScript XPCOM components
) { switch (anode.localname) { case "radio": return nodefilter.filter_accept; case "template": case "radiogroup": return nodefilter.filter_reject; default: return nodefilter.filter_skip; } } var iterator = this.ownerdocument.createtreewalker(this, nodefilter.show_element, _filterradiogroup,
true); while (iterator.nextnode()) radiochildren.push(iterator.currentnode); return this.mradiochildren = radiochildren; in this example, the iterator object is an xpcom object that is wrapped so the javascript code can use it.
Building the WebLock UI
the xul that defines the radiogroup in the web lock manager dialog is this: <radiogroup> <radio label="lock"/> <radio label="unlock" selected="
true"/> </radiogroup> since the weblock component always starts up in the unlocked position, you can add the selected="
true" attribute and value on the unlock radio button and reset it dynamically as the user takes action.
Components.utils.createObjectIn
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 o...
Components.utils.import
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.waiveXrays
example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content window with xray vision, but the chrome code can waive xray protection: // chrome code // contentwindow is an xray var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); //
true // expandos are not visible in xrays var foo = gbrowser.contentwindow.foo; // undefined // you can waive xray vision for an object var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waived); // false foo = waived.foo; // "i'm an expando"...
Language bindings
o 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.
nsScriptableInputStream
example code const nsiscriptableinputstream = components.interfaces.nsiscriptableinputstream; function consumestream(inputstream) { var factory = components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createinstance(nsiscriptableinputstream); sis.init(inputstream); try { while (
true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's data.
nsIEditorDocShell
void makeeditable( in boolean inwaitforuriload ); parameters inwaitforuriload
true to wait for a uri before creating the editor.
nsIEnvironment
return value if the variable has been set, the value returned is pr_
true.
nsIEventTarget
return value returns
true if events dispatched to this event target will run on the current thread (that is, the thread calling this method).
nsIFactory
void lockfactory( in prbool lock ); parameters lock
true to lock the factory, and false to unlock the factory.
nsIFaviconService
return value returns
true if the favicon is in the failed cache, meaning you probably shouldn't try to load it.
nsIFilePicker
ilter(in astring title, in astring filter); void appendfilters(in long filtermask); void init(in nsidomwindow parent, in astring title, in short mode); void open(in nsifilepickershowncallback afilepickershowncallback); short show(); obsolete since gecko 57.0 attributes attribute type description addtorecentdocs boolean if
true, the file is added to the operating system's "recent documents" list (if the operating system has one; nothing happens if there is no such concept on the user's platform).
nsIGeolocationProvider
return value
true if the device is ready and has a position available to return; otherwise false.
nsIGlobalHistory3
otherwise, nsiglobalhistory2.adduri() should be called with redirect=
true.
nsIHttpActivityObserver
introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void observeactivity(in nsisupports ahttpchannel, in pruint32 aactivitytype, in pruint32 aactivitysubtype, in prtime atimestamp, in pruint64 aextrasizedata, in acstring aextrastringdata); attributes attribute type description isactive boolean
true when the interface is active and should observe http activity, otherwise false.
nsIHttpHeaderVisitor
mynsihttpheadervisitor = 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 = compo...
nsIHttpServer
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...
nsIInstallLocation
return value
true if the item's resources are managed independently of the extension system, false otherwise.
nsIJSON
writebom specify
true if you wish to write a byte-order mark (bom) into the stream, otherwise specify false.
XPCOM reference
rss feeds are implemented by nslocalmailfolder.ns ensure successmacrons ensure
truemacrons_abort_if_falsethis was removed in bug 1127201ns_addrefmacrons_assertionmacrons_ensure_arg_pointermacrons_errorthrows a assertion (ns_assertion) with the text "error: (error text)", so writes this text to console (stderr) and to debug logs (nspr logging).
Status, Recent Changes, and Plans
recent changes to this document removed the statement that == and != between an nscomptr and a raw pointer or literal 0 does not work on some compilers since it is no longer
true.
Using the clipboard
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.
XPIDL Syntax
literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= string_literal / char_literal literal /= "
true" / "false" ; in regex: /"[^"\n]*["\n]/.
MailNews fakeserver
setmultiline the new value of multiline nothing the value is a boolean, with
true invoking multiline mode.
Adding items to the Folder Pane
t event: let gnumbersext = { load: function gne_load() { window.removeeventlistener("load", gnumbersext.load, false); let tree = document.getelementbyid("foldertree"); tree.addeventlistener("maprebuild", gnumbersext._insert, false); }, _insert: function gne__insert() { // this function is called when a rebuild occurs } }; window.addeventlistener("load", gnumbersext.load,
true); the structure of folder-tree-items the folder pane stores its current display data in a property called _rowmap.
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
const cc = components.classes; const ci = components.interfaces; var tbirdsqlite = { onload: function() { // initialization code this.initialized =
true; this.dbinit(); }, dbconnection: null, dbschema: { tables: { attachments:"id integer primary key, \ name text \ encoded text not null" } }, dbinit: function() { var dirservice = cc["@mozilla.org/file/directory_service;1"].
customDBHeaders Preference
o 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("colsuperfluous",columnhandler); dump("column handler being added: " + columnhandler + "\n"); } var createdbobserver = { // components.interfaces.nsiobserver obser...
Working with windows in chrome code
// in the calling code var args = { param1:
true, param2: 42 }; args.wrappedjsobject = args; var watcher = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); watcher.openwindow(null, url, windowname, features, args); // in the window code var args = window.arguments[0].wrappedjsobject; this uses the wrappedjsobject trick.
Using COM from js-ctypes
let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); // some groundwork let is64bit; if (ctypes.voidptr_t.size == 4 /* 32-bit */) { is64bit = false; } else if (ctypes.voidptr_t.size == 8 /* 64-bit */) { is64bit =
true; } let winabi = is64bit ?
Using Objective-C from js-ctypes
1', [ { isa: ctypes.voidptr_t }, { flags: ctypes.int32_t }, { reserved: ctypes.int32_t }, { invoke: ctypes.voidptr_t }, { descriptor: block_descriptor_1.ptr } ]); var block_const = { block_has_copy_dispose: 1 << 25, block_has_ctor: 1 << 26, block_is_global: 1 << 28, block_has_stret: 1 << 29, block_has_signature: 1 << 30 }; // based on work from here: https://github.com/
trueinteractions/tint2/blob/f6ce18b16ada165b98b07869314dad1d7bee0252/modules/bridge/core.js#l370-l394 var bl = block_literal_1(); // set the class of the instance bl.isa = _nsconcreteglobalblock; // global flags bl.flags = block_const.block_has_stret; bl.reserved = 0; bl.invoke = afunctypeptr; // create descriptor var desc = block_descriptor_1(); desc.reserved = 0; desc.size = block_liter...
Declaring and Using Callbacks
var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myjscallback(cint, cptr) { return
true; // as the return of the functiontype was ctypes.bool we must make our javascript callback return bool otherwise js-ctypes will throw error saying unexpected type return } var myccallback = myfunctypedeclaration.ptr(myjscallback); example 2 this callback that returns void and no arguments.
Declaring types
this works around the lack of
true forward references in javascript.
CData
attempts to do readstring on it, if it errors then it tries to read it in another way, so this is an alternative to readstringreplacemalformed, it is an attempt at readingmalformed function readaschar8thenaschar16(stringptr, known_len, jschar) { // when reading as jschar it assumes max length of 500 // stringptr is either char or jschar, if you know its jschar for sure, pass 2nd arg as
true // if known_len is passed, then assumption is not made, at the known_len position in array we will see a null char // i tried getting known_len from stringptr but its not possible, it has be known, i tried this: //"stringptr.contents.tostring()" "95" //"stringptr.tostring()" "ctypes.unsigned_char.ptr(ctypes.uint64("0x7f73d5c87650"))" // so as we see neither of thes...
PointerType
return value
true if the pointer's value is null, otherwise false.
Initialization and Destruction - Plugins
for example, the following embed element has the standard attributes src, height, and width and the private attribute loop: <embed src="movie.avi" height="100" width="100" loop="
true"> with the embed element in the example, the browser passes the values in argv to the plug-in instance: argc = 4 argn = { "src", "height", "width", "loop" } argv = { "movie.avi", "100", "100", "
true" } the saved parameter allows an instance of a plug-in to save its data and, when the instance is destroyed, pass the data to the next instance of the plug-in at the same url.
Streams - Plugins
the seekable parameter specifies whether the stream is seekable (
true) or not (false).
Network request details - Firefox Developer Tools
"name": "content-encoding", "value": "gzip" }, { "name": "content-length", "value": "673" }, { "name": "content-type", "value": "text/javascript; charset=utf-8" }, { "name": "date", "value": "tue, 11 jun 2019 13:01:39 gmt" }, { "name": "mediawiki-login-suppressed", "value": "
true" }, { "name": "p3p", "value": "cp=\"this is not a p3p policy!
Animation inspector example: Web Animations API - Firefox Developer Tools
var notekeyframeoptions = { duration: 500, fill: 'forwards', 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); ...
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).
AbortSignal - Web APIs
abortsignal.aborted read only a boolean that indicates whether the request(s) the signal is communicating with is/are aborted (
true) or not (false).
AbstractRange - Web APIs
1" y="1" width="130" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="66" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">abstractrange</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties collapsed read only a boolean value which is
true if the range is collapsed.
AesCtrParams - Web APIs
the counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then the following must be
true: n <= 2m.
AnalyserNode.getFloatFrequencyData() - Web APIs
microphone input const audioele = new audio(); audioele.src = 'my-audio.mp3';//insert file name here audioele.autoplay =
true; audioele.preload = 'auto'; const audiosourcenode = audioctx.createmediaelementsource(audioele); //create analyser node const analysernode = audioctx.createanalyser(); analysernode.fftsize = 256; const bufferlength = analysernode.frequencybincount; const dataarray = new float32array(bufferlength); //set up audio node network audiosourcenode.connect(analysernode); analysernode.connect(audioctx.d...
AudioBufferSourceNode.playbackRate - Web APIs
<input class="playback-rate-control" type="range" min="0.25" max="3" step="0.05" value="1"> <span class="playback-rate-value">1.0</span> function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop =
true; }, function(e){"er...
AudioContext() - Web APIs
the user agent may or may not choose to meet this request; check the value of audiocontext.baselatency to determine the
true latency after creating the context.
AudioContext.createMediaStreamDestination() - Web APIs
var ac = new audiocontext(); var osc = ac.createoscillator(); var dest = ac.createmediastreamdestination(); var mediarecorder = new mediarecorder(dest.stream); osc.connect(dest); b.addeventlistener("click", function(e) { if (!clicked) { mediarecorder.start(); osc.start(0); e.target.innerhtml = "stop recording"; clicked =
true; } else { mediarecorder.stop(); osc.stop(0); e.target.disabled =
true; } }); mediarecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediarecorder.onstop = function(evt) { // make blob out of our blobs, and open it.
AudioContext.createMediaStreamSource() - Web APIs
'pre'); var video = document.queryselector('video'); var myscript = document.queryselector('script'); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio:
true, video:
true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted =
true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); ...
AudioContext.createMediaStreamTrackSource() - Web APIs
navigator.mediadevices.getusermedia ({audio:
true, video: false}) .then(function(stream) { audio.srcobject = stream; audio.onloadedmetadata = function(e) { audio.play(); audio.muted =
true; }; let audioctx = new audiocontext(); let source = audioctx.createmediastreamsource(stream); let biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 3000; biquadfilter.gain.v...
AudioContextOptions - Web APIs
the user agent may or may not choose to meet this request; check the value of audiocontext.baselatency to determine the
true latency after creating the context.
AudioNode.context - Web APIs
example const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.context); // audiocontext console.log(oscillator.context === audioctx); //
true specifications specification status comment web audio apithe definition of 'context' in that specification.
AudioParam.defaultValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); const defaultval = gainnode.gain.defaultvalue; console.log(defaultval); // 1 console.log(defaultval === gainnode.gain.value); //
true specifications specification status comment web audio apithe definition of 'defaultvalue' in that specification.
AudioParam.value - Web APIs
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.
AudioParamDescriptor - Web APIs
} }) 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.
AudioProcessingEvent - Web APIs
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = f...
AudioTrack.enabled - Web APIs
syntax isaudioenabled = audiotrack.enabled; audiotrack.enabled =
true | false; value the enabled property is a boolean whose value is
true if the track is enabled; enabled tracks produce audio while the media is playing.
AudioTrack - Web APIs
tracks.foreach(function(track) { if (track.language === userlanguage) { track.enabled =
true; } else { track.enabled = false; } }); the language is in standard (rfc 5646) format.
AudioWorkletGlobalScope.registerProcessor - Web APIs
// 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.
AudioWorkletGlobalScope - Web APIs
{ 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', tes...
AudioWorkletNode.parameters - Web APIs
} }) 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.
AudioWorkletNode.port - Web APIs
// 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.
AudioWorkletNode - Web APIs
// 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
// 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
// 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
// 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.
BaseAudioContext.createConvolver() - Web APIs
// grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg',
true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
BaseAudioContext.createDelay() - Web APIs
var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.loop =
true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function() { synthsource.disconnect(synthdelay); synthdelay.disconnect(destination); synthsource.stop(); playsynth.removeattribute('disabled'); } ...
BaseAudioContext.createDynamicsCompressor() - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
BaseAudioContext.createGain() - Web APIs
ic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio:
true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
BaseAudioContext.createScriptProcessor() - Web APIs
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = f...
BaseAudioContext.decodeAudioData() - Web APIs
// then we put the buffer into the source function getdata() { source = audioctx.createbuffersource(); var request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { source.buffer = buffer; source.connect(audioctx.destination); source.loop =
true; }, function(e){ console.log("error with decoding audio data" + e.err); }); } request.send(); } //...
BasicCardRequest - Web APIs
'discover', 'mir', 'unionpay'] } }]; var details = { total: {label: 'donation', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected:
true } ] }; var options = {requestshipping:
true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
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.
BeforeInstallPromptEvent.prompt() - Web APIs
example var istoosoon =
true; window.addeventlistener("beforeinstallprompt", function(e) { if (istoosoon) { e.preventdefault(); // prevents prompt display // prompt later instead: settimeout(function() { istoosoon = false; e.prompt(); // throws if called more than once or default not prevented }, 10000); } // the event was re-dispatched in response to our request // ...
Bluetooth.requestDevice() - Web APIs
for example, options.filters is present and options.acceptalldevices is
true, or if options.filters is not present and options.acceptalldevices is false.
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.
BluetoothRemoteGATTServer - Web APIs
; 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.
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.
CSSPseudoElement.element - Web APIs
examples the example below demonstrates the relationship between csspseudoelement.element and element.pseudo(): const myelement = document.queryselector('q'); const csspseudoelement = myelement.pseudo('::after'); const originatingelement = csspseudoelement.element; console.log(myelement === originatingelement); // outputs
true console.log(myelement.parentelement === originatingelement); // outputs false console.log(myelement.lastelementchild === csspseudoelement); // outputs false console.log(myelement.lastchild === csspseudoelement); // outputs false console.log(myelement.nextelementsibling === csspseudoelement); // outputs false console.log(myelement.nextsibling === csspseudoelement); // outputs ...
CSSPseudoElement.type - Web APIs
lues: "::before" "::after" "::marker" examples the example below demonstrates the relationship between csspseudoelement.type and element.pseudo(): const myelement = document.queryselector('q'); const myselector = '::after'; const csspseudoelement = myelement.pseudo(myselector); const typeofpseudoelement = csspseudoelement.type; console.log(myselector === typeofpseudoelement); // outputs
true specifications specification status comment css pseudo-elements level 4the definition of 'type' in that specification.
CSSStyleSheet.insertRule() - Web APIs
* @param {array} rules accepts an array of json-encoded declarations * @example addstylesheetrules([ ['h2', // also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green',
true] // '
true' for !important rules ], ['.myclass', ['background-color', 'yellow'] ] ]); */ function addstylesheetrules (rules) { var styleel = document.createelement('style'); // append <style> element to <head> document.head.appendchild(styleel); // grab style element's sheet var stylesheet = styleel.sheet; for (var i = 0; i < rules.length; i++) { var j = 1, rul...
CSS Painting API - Web APIs
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 strokewidth = parseint(args[1]); console.log(thecolor); if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.l...
CSS Typed Object Model API - Web APIs
cssnumericvalue.min - returns the minimum value passed cssnumericvalue.max - returns the maximum value passed cssnumericvalue.equals - returns
true if all the values are the exact same type and value, in the same order.
Cache - Web APIs
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.
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
html <canvas id="canvas"> <button id="button1">continue</button> <button id="button2">quit</button> </canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const button1 = document.getelementbyid('button1'); const button2 = document.getelementbyid('button2'); document.addeventlistener('focus', redraw,
true); document.addeventlistener('blur', redraw,
true); canvas.addeventlistener('click', handleclick, false); redraw(); function redraw() { ctx.clearrect(0, 0, canvas.width, canvas.height); drawbutton(button1, 20, 20); drawbutton(button2, 20, 80); } function handleclick(e) { // calculate click coordinates const x = e.clientx - canvas.offsetleft; const y = e.clienty - canvas.offsettop; ...
CanvasRenderingContext2D.globalAlpha - Web APIs
le = '#fd0'; ctx.fillrect(0, 0, 75, 75); ctx.fillstyle = '#6c0'; ctx.fillrect(75, 0, 75, 75); ctx.fillstyle = '#09f'; ctx.fillrect(0, 75, 75, 75); ctx.fillstyle = '#f30'; ctx.fillrect(75, 75, 75, 75); ctx.fillstyle = '#fff'; // set transparency value ctx.globalalpha = 0.2; // draw transparent circles for (let i = 0; i < 7; i++) { ctx.beginpath(); ctx.arc(75, 75, 10 + 10 * i, 0, math.pi * 2,
true); ctx.fill(); } screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.globalalpha' in that specification.
CanvasRenderingContext2D.strokeStyle - Web APIs
fixed value.) <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); for (let i = 0; i < 6; i++) { for (let j = 0; j < 6; j++) { ctx.strokestyle = `rgb( 0, ${math.floor(255 - 42.5 * i)}, ${math.floor(255 - 42.5 * j)})`; ctx.beginpath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, math.pi * 2,
true); ctx.stroke(); } } the result looks like this: screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.strokestyle' in that specification.
CanvasRenderingContext2D - Web APIs
blink only canvasrenderingcontext2d.iscontextlost() inspired by the same webglrenderingcontext method it returns
true if the canvas context has been lost, or false if not.
Manipulating video using canvas - Web APIs
ackground: black; color:#cccccc; } #c2 { background-image: url(media/foo.png); background-repeat: no-repeat; } div { float: left; border :1px solid #444444; padding:10px; margin: 10px; background:#3b3b3b; } </style> </head> <body> <div> <video id="video" src="media/video.mp4" controls="
true" crossorigin="anonymous"/> </div> <div> <canvas id="c1" width="160" height="96"></canvas> <canvas id="c2" width="160" height="96"></canvas> </div> <script type="text/javascript" src="processor.js"></script> </body> </html> the key bits to take away from this are: this document establishes two canvas elements, with the ids c1 and c2.
Basic animations - Web APIs
ctx.linewidth = 10; ctx.beginpath(); ctx.moveto(-28, 0); ctx.lineto(112, 0); ctx.stroke(); ctx.restore(); // write seconds ctx.save(); ctx.rotate(sec * math.pi / 30); ctx.strokestyle = '#d40000'; ctx.fillstyle = '#d40000'; ctx.linewidth = 6; ctx.beginpath(); ctx.moveto(-30, 0); ctx.lineto(83, 0); ctx.stroke(); ctx.beginpath(); ctx.arc(0, 0, 10, 0, math.pi * 2,
true); ctx.fill(); ctx.beginpath(); ctx.arc(95, 0, 10, 0, math.pi * 2,
true); ctx.stroke(); ctx.fillstyle = 'rgba(0, 0, 0, 0)'; ctx.arc(0, 0, 3, 0, math.pi * 2,
true); ctx.fill(); ctx.restore(); ctx.beginpath(); ctx.linewidth = 14; ctx.strokestyle = '#325fa2'; ctx.arc(0, 0, 142, 0, math.pi * 2,
true); ctx.stroke(); ctx.restore(); window.requestanimationframe(clock); } ...
Compositing and clipping - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.fillrect(0, 0, 150, 150); ctx.translate(75, 75); // create a circular clipping path ctx.beginpath(); ctx.arc(0, 0, 60, 0, math.pi * 2,
true); ctx.clip(); // draw background var lingrad = ctx.createlineargradient(0, -75, 0, 75); lingrad.addcolorstop(0, '#232256'); lingrad.addcolorstop(1, '#143778'); ctx.fillstyle = lingrad; ctx.fillrect(-75, -75, 150, 150); // draw stars for (var j = 1; j < 50; j++) { ctx.save(); ctx.fillstyle = '#fff'; ctx.translate(75 - math.floor(math.random() * 150), ...
ChildNode.after() - Web APIs
nceerror: 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
or: 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(isnode ?
ChildNode.remove() - Web APIs
ror: 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 'childnode.remove' in that specification.
Clients.matchAll() - Web APIs
available options are: includeuncontrolled: a boolean — if set to
true, the matching operation will return all service worker clients who share the same origin as the current service worker.
Clients - Web APIs
addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await clients.matchall({ includeuncontrolled:
true }); let chatclient; // let's see if we already have a chat window open: for (const client of allclients) { const url = new url(client.url); if (url.pathname == '/chat/') { // excellent, let's use it!
ConstrainBoolean - Web APIs
you can also specify the value of the property as simply
true or false, in which case the user agent will use that value if possible once all efforts have been made to match the exact and ideal values for other properties.
ConvolverNode.buffer - Web APIs
// grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg',
true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
CustomElementRegistry.get() - Web APIs
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.
CustomEvent() - Web APIs
example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new customevent("cat", { detail: { hazcheeseburger:
true } }); obj.dispatchevent(event); additional examples can be found at creating and triggering events.
CustomEvent.detail - Web APIs
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.
CustomEvent - Web APIs
setting its value to
true before returning from an event handler prevents propagation of the event.
DOMImplementation.createHTMLDocument() - Web APIs
doc = document.implementation.createhtmldocument("new document"); let p = doc.createelement("p"); p.innerhtml = "this is a new paragraph."; try { doc.body.appendchild(p); } catch(e) { console.log(e); } // copy the new html document into the frame let destdocument = frame.contentdocument; let srcnode = doc.documentelement; let newnode = destdocument.importnode(srcnode,
true); destdocument.replacechild(newnode, destdocument.documentelement); } the code in lines 4–12 handle creating the new html document and inserting some content into it.
DOMImplementation - Web APIs
this function is unreliable and kept for compatibility purpose alone: except for svg-related queries, it always returns
true.
DataTransfer.dropEffect - Web APIs
html content <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.
DataTransfer.effectAllowed - Web APIs
er: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples <code>datatransfer</code>.{<code>dropeffect</code>, <code>effectallowed</code>} properties</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'effectallowed' in that specification.
DataTransfer.getData() - Web APIs
html content <div id="div1" ondrop="drop(event)" ondragover="allowdrop(event)"> <span id="drag" draggable="
true" ondragstart="drag(event)">drag me to the other box</span> </div> <div id="div2" ondrop="drop(event)" ondragover="allowdrop(event)"></div> css content #div1, #div2 { width:100px; height:50px; padding:10px; border:1px solid #aaaaaa; } javascript content function allowdrop(allowdropevent) { allowdropevent.target.style.color = 'blue'; allowdropevent.preventdefault(); } ...
DataTransfer.items - Web APIs
d + " ; type = " + ev.datatransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples of <code>datatransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="
true">drag item 1 to the drop zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="
true">drag item 2 to the drop zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'items' in that specific...
DataTransfer.setData() - Web APIs
var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // clear the drag data cache (for all formats/types) ev.datatransfer.cleardata(); } </script> <body> <h1>examples of <code>datatransfer</code>: <code>setdata()</code>, <code>getdata()</code>, <code>cleardata()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'setdata()' in that specification.
DataTransfer.setDragImage() - Web APIs
eventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); // get the data, which is the id of the drop target var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } </script> <body> <h1>example of <code>datatransfer.setdragimage()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'setdragimage()' in that specification.
DataTransfer.types - Web APIs
d + " ; type = " + ev.datatransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples of <code>datatransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="
true">drag item 1 to the drop zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="
true">drag item 2 to the drop zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'types' in that specific...
DataTransfer - Web APIs
datatransfer.mozusercancelled read only this property applies only to the dragend event, and is
true if the user canceled the drag operation by pressing escape.
DataTransferItemList.DataTransferItem() - Web APIs
) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; // clear any remaining drag data datalist.clear(); } html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } result drag and drop demo link spec...
DataTransferItemList.add() - Web APIs
html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript function dragstart_handler(ev) { ...
DataTransferItemList.clear() - Web APIs
html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript functio...
DataTransferItemList.length - Web APIs
) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; // clear any remaining drag data datalist.clear(); } html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } result drag and drop demo link spec...
DataTransferItemList.remove() - Web APIs
{ console.log("dragend"); var datalist = ev.datatransfer.items; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } html <h1>example uses of <code>datatransferitemlist</code> methods and property</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } specifications...
DelayNode.delayTime - Web APIs
var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.loop =
true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function() { synthsource.disconnect(synthdelay); synthdelay.disconnect(destination); synthsource.stop(); playsynth.removeattribute('disabled'); } ...
DelayNode - Web APIs
var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.loop =
true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function() { synthsource.disconnect(synthdelay); synthdelay.disconnect(destination); synthsource.stop(); playsynth.removeattribute('disabled'); } ...
DeprecationReportBody - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); because of the event han...
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.
Document: DOMContentLoaded event - Web APIs
-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.queryselector('.event-log-contents'); const reload = document.queryselector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(
true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('readystatechange', (event) => { log.textcontent = log.textcontent + `readystate: ${document.readystate}\n`; }); document.addeventlistener('domcontentloaded', (event) => { log.textcontent = log.textcontent + `domcontentloaded\n`; }); result ...
Document.cookie - Web APIs
function doonce() { if (!document.cookie.split('; ').find(row => row.startswith('dosomethingonlyonce'))) { alert("do something here!"); document.cookie = "dosomethingonlyonce=
true; expires=fri, 31 dec 9999 23: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(';').
Document.createProcessingInstruction() - Web APIs
exceptions dom_invalid_character throws if either of the following are
true: the processing instruction target is invalid — it should be a valid xml name that doesn't contain "xml", "xml", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>.
Document: drag event - Web APIs
html <div class="dropzone"> <div id="draggable" draggable="
true" ondragstart="event.datatransfer.setdata('text/plain',null)"> this div is draggable </div> </div> <div class="dropzone"></div> <div class="dropzone"></div> <div class="dropzone"></div> css #draggable { width: 200px; height: 20px; text-align: center; background: white; } .dropzone { width: 200px; height: 20px; background: blueviolet; margin-bottom: 10px; padding: 10px; ...
Document.fonts - Web APIs
0edge full support 79firefox full support 41 full support 41 no support 35 — 41disabled disabled from version 35 until version 41 (exclusive): this feature is behind the layout.css.font-loading-api.enabled preference (needs to be set to
true).
Document.fullscreenEnabled - Web APIs
syntax var isfullscreenavailable = document.fullscreenenabled; value a boolean value which is
true if the document and the elements within can be placed into full-screen mode by calling element.requestfullscreen().
Document.hasFocus() - Web APIs
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.head - Web APIs
example <!doctype html> <head id="my-document-head"> <title>example: using document.head</title> </head> <script> var thehead = document.head; console.log(thehead.id); // "my-document-head"; console.log( thehead === document.queryselector("head") ); //
true </script> notes document.head is read-only.
Document.implementation - Web APIs
syntax domimpobj = document.implementation; example var modname = "html"; var modver = "2.0"; var conformtest = document.implementation.hasfeature( modname, modver ); alert( "dom " + modname + " " + modver + " supported?: " + conformtest ); // alerts with: "dom html 2.0 supported?:
true" if dom level 2 html module is supported.
Document.onafterscriptexecute - Web APIs
example function finished(e) { logmessage(`finished script with id: ${e.target.id}`); } document.addeventlistener('afterscriptexecute', finished,
true); view live example specification html5 ...
Document.onbeforescriptexecute - Web APIs
example function starting(e) { logmessage("starting script with id: " + e.target.id); } document.addeventlistener("beforescriptexecute", starting,
true); view live examples specification html5 ...
Document.ononline - Web APIs
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
this call, for example opens github.com in a new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=
true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g.
Document.queryCommandState() - Web APIs
example html <div contenteditable="
true">select a part of this text!</div> <button onclick="makebold();">test the state of the 'bold' command</button> javascript function makebold() { var state = document.querycommandstate("bold"); switch (state) { case
true: alert("the bold formatting will be removed from the selected text."); break; case false: alert("the selected text will be displayed in bold."); break; case null: al...
Document: readystatechange event - Web APIs
-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.queryselector('.event-log-contents'); const reload = document.queryselector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(
true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('readystatechange', (event) => { log.textcontent = log.textcontent + `readystate: ${document.readystate}\n`; }); document.addeventlistener('domcontentloaded', (event) => { log.textcontent = log.textcontent + `domcontentloaded\n`; }); result ...
Document: scroll event - Web APIs
tions/ let last_known_scroll_position = 0; let ticking = false; function dosomething(scroll_pos) { // do something with the scroll position } window.addeventlistener('scroll', function(e) { last_known_scroll_position = window.scrolly; if (!ticking) { window.requestanimationframe(function() { dosomething(last_known_scroll_position); ticking = false; }); ticking =
true; } }); see more, similar examples on the resize event page.
DynamicsCompressorNode.attack - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
DynamicsCompressorNode.knee - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
DynamicsCompressorNode.ratio - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
DynamicsCompressorNode.release - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
DynamicsCompressorNode.threshold - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
DynamicsCompressorNode - Web APIs
eattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(active == 'false') { button.setattribute('data-active', '
true'); button.innerhtml = 'remove compression'; source.disconnect(audioctx.destination); source.connect(compressor); compressor.connect(audioctx.destination); } else if(active == '
true') { button.setattribute('data-active', 'false'); button.innerhtml = 'add compression'; source.disconnect(compressor); compressor.disconnect(audioctx.destination); source.connect(...
Element.attachShadow() - Web APIs
an 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.
Element: copy event - Web APIs
examples live example html <div class="source" contenteditable="
true">try copying text from this box...</div> <div class="target" contenteditable="
true">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const source = document.queryselector('div.source'); source.addeventlistener('copy', (event) => { const selection =...
Element: cut event - Web APIs
examples live example html <div class="source" contenteditable="
true">try cutting text from this box...</div> <div class="target" contenteditable="
true">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const source = document.queryselector('div.source'); source.addeventlistener('cut', (event) => { const selection = ...
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.
Element.scrollIntoView() - Web APIs
the element interface's scrollintoview() method scrolls the element's parent container such that the element on which scrollintoview() is called is visible to the user syntax element.scrollintoview(); element.scrollintoview(aligntotop); // boolean parameter element.scrollintoview(scrollintoviewoptions); // object parameter parameters aligntotop optional is a boolean value: if
true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor.
Element: scroll event - Web APIs
tions/ let last_known_scroll_position = 0; let ticking = false; function dosomething(scroll_pos) { // do something with the scroll position } window.addeventlistener('scroll', function(e) { last_known_scroll_position = window.scrolly; if (!ticking) { window.requestanimationframe(function() { dosomething(last_known_scroll_position); ticking = false; }); ticking =
true; } }); note: you can find more examples on the resize event page.
Element.setAttributeNode() - Web APIs
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
example // <div id="one" xmlns: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.setCapture() - Web APIs
syntax element.setcapture(retargettoelement); retargettoelement if
true, all events are targeted directly to this element; if false, events can also fire at descendants of this element.
Event() - Web APIs
example // create a look event that bubbles up and cannot be canceled const evt = new event("look", {"bubbles":
true, "cancelable":false}); document.dispatchevent(evt); // event can be dispatched from any element, not only the document mydiv.dispatchevent(evt); specifications specification status comment domthe definition of 'event()' in that specification.
Event.defaultPrevented - Web APIs
syntax var defaultwasprevented = event.defaultprevented; value a boolean, where
true indicates that the default user agent action was prevented, and false indicates that it was not.
Event.initEvent() - Web APIs
var event = document.createevent('event'); // create a click event that bubbles up and // cannot be canceled event.initevent('click',
true, false); // listen for the event.
Event.isTrusted - Web APIs
the istrusted read-only property of the event interface is a boolean that is
true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via eventtarget.dispatchevent().
Event.preventDefault() - Web APIs
as noted below, calling preventdefault() for a non-cancelable event, such as one dispatched via eventtarget.dispatchevent(), without specifying cancelable:
true has no effect.
Event - Web APIs
setting its value to
true before returning from an event handler prevents propagation of the event.
EventSource.withCredentials - Web APIs
syntax var mywithcredentials = eventsource.withcredentials; value a boolean indicating whether the eventsource object was instantiated with cors credentials set (
true), or not (false, the default).
EventSource - Web APIs
eventsource.withcredentials read only a boolean indicating whether the eventsource object was instantiated with cross-origin (cors) credentials set (
true), or not (false, the default).
EventTarget - Web APIs
enttarget.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.
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.
Using files from web applications - Web APIs
]['name']); exit; } ?><!doctype html> <html> <head> <title>dnd binary upload</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="application/javascript"> function sendfile(file) { const uri = "/index.php"; const xhr = new xmlhttprequest(); const fd = new formdata(); xhr.open("post", uri,
true); xhr.onreadystatechange = function() { if (xhr.readystate == 4 && xhr.status == 200) { alert(xhr.responsetext); // handle response.
FileException - Web APIs
var fileentry = fs.root.getfile('log.txt', {create:
true, exclusive:
true}0; } catch (e) { onerrror(e); } the sample code was borrowed from html5rocks attribute attribute type description code unsigned short the most appropriate error code for the condition.
FileList - Web APIs
starting with gecko 1.9.2, if the input element's multiple attribute is
true, the filelist may contain multiple files.
FileSystemDirectoryEntry - Web APIs
function onfs(fs){ fs.root.getdirectory('documents', {create:
true}, function(directoryentry){ //directoryentry.isfile === false //directoryentry.isdirectory ===
true //directoryentry.name === 'documents' //directoryentry.fullpath === '/documents' }, onerror); } // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, onfs, onerror); properties this interface has no properties of its own, b...
FileSystemEntry.fullPath - Web APIs
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.isDirectory - Web APIs
the read-only isdirectory property of the filesystementry interface is
true if the entry represents a directory (meaning it's a filesystemdirectoryentry) and false if it's not.
FileSystemEntry.isFile - Web APIs
the read-only isfile property of the filesystementry interface is
true if the entry represents a file (meaning it's a filesystemfileentry) and false if it's not.
FileSystemEntry.name - Web APIs
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.
FileSystemFileEntry - Web APIs
function oninitfs(fs) { fs.root.getfile('log.txt', {create:
true}, function(fileentry) { // create a filewriter object for our filesystemfileentry (log.txt).
File and Directory Entries API - Web APIs
if htmlinputelement.webkitdirectory is
true, the <input> element is instead a directory picker, and you get filesystemdirectoryentry objects for each selected directory.
Using FormData Objects - Web APIs
tash the file!" /> </form> <div></div> then you can send it using code like the following: var form = document.forms.nameditem("fileinfo"); form.addeventlistener('submit', function(ev) { var ooutput = document.queryselector("div"), odata = new formdata(form); odata.append("customfield", "this is some extra data"); var oreq = new xmlhttprequest(); oreq.open("post", "stash.php",
true); oreq.onload = function(oevent) { if (oreq.status == 200) { ooutput.innerhtml = "uploaded!"; } else { ooutput.innerhtml = "error " + oreq.status + " occurred when trying to upload your file.<br \/>"; } }; oreq.send(odata); ev.preventdefault(); }, false); note: if you pass in a reference to the form, the request method specified in the form will be used over th...
FormData.append() - Web APIs
if the sent value is different than string or blob it will be automatically converted to string: formdata.append('name',
true); formdata.append('name', 74); formdata.append('name', 'john'); formdata.getall('name'); // ["
true", "74", "john"] specifications specification status comment xmlhttprequestthe definition of 'append()' in that specification.
FormData.has() - Web APIs
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.
GainNode.gain - Web APIs
ic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio:
true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
GainNode - Web APIs
ic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio:
true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
Geolocation.getCurrentPosition() - Web APIs
enablehighaccuracy: false |
true examples var options = { enablehighaccuracy:
true, timeout: 5000, maximumage: 0 }; function success(pos) { var crd = pos.coords; console.log('your current position is:'); console.log(`latitude : ${crd.latitude}`); console.log(`longitude: ${crd.longitude}`); console.log(`more or less ${crd.accuracy} meters.`); } function error(err) { console.warn(`error(${err.code}): ${...
Using the Geolocation API - Web APIs
a call to watchposition could look like: function success(position) { dosomething(position.coords.latitude, position.coords.longitude); } function error() { alert('sorry, no position available.'); } const options = { enablehighaccuracy:
true, maximumage: 30000, timeout: 27000 }; const watchid = navigator.geolocation.watchposition(success, error, options); describing a position the user's location is described using a geolocationposition object instance, which itself contains a geolocationcoordinates object instance.
GlobalEventHandlers.ondrag - Web APIs
rget.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondrag' in that specification.
GlobalEventHandlers.ondragend - Web APIs
etelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragend' in that specification.
GlobalEventHandlers.ondragenter - Web APIs
etelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragenter' in that specification.
GlobalEventHandlers.ondragexit - Web APIs
etelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragexit' in that specification.
GlobalEventHandlers.ondragleave - Web APIs
etelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragleave' in that specification.
GlobalEventHandlers.ondragover - Web APIs
ansfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragover' in that specification.
GlobalEventHandlers.ondragstart - Web APIs
ansfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragstart' in that specification.
GlobalEventHandlers.ondrop - Web APIs
"text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="
true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondrop' in that specification.
HTMLButtonElement - Web APIs
it is false if any conditions bar it from constraint validation, including: its type property is reset or button; it has a <datalist> ancestor; or the disabled property is set to
true.
HTMLCollection - Web APIs
for example, assuming there is one <form> element in the document and its id is myform: var elem1, elem2; // document.forms is an htmlcollection elem1 = document.forms[0]; elem2 = document.forms.item(0); alert(elem1 === elem2); // shows: "
true" elem1 = document.forms.myform; elem2 = document.forms.nameditem("myform"); alert(elem1 === elem2); // shows: "
true" elem1 = document.forms["named.item.with.periods"]; specifications specification status comment domthe definition of 'htmlcollection' in that specification.
HTMLOutputElement - Web APIs
if there are problems, fires an invalid event at the element, and returns false; if there are no problems, it returns
true.
HTMLScriptElement - Web APIs
htmlscriptelement.nomodule is a boolean that if
true, stops the script's execution in browsers that support es2015 modules — used to run fallback scripts in older browsers that do not support javascript modules.
HTMLSelectElement.disabled - Web APIs
r</option> <option value="3">pepsi</option> <option value="4">whisky</option> </select> javascript var allowdrinkscheckbox = document.getelementbyid("allow-drinks"); var drinkselect = document.getelementbyid("drink-select"); allowdrinkscheckbox.addeventlistener("change", function(event) { if (event.target.checked) { drinkselect.disabled = false; } else { drinkselect.disabled =
true; } }, false); result specifications specification status comment html living standardthe definition of 'disabled' in that specification.
HTMLTableElement.createTFoot() - Web APIs
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
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.
HTMLTemplateElement.content - Web APIs
syntax var documentfragment = templateelement.content example var templateelement = document.queryselector("#foo"); var documentfragment = templateelement.content.clonenode(
true); specifications specification status comment html living standardthe definition of 'htmltemplateelement interface' in that specification.
HTMLVideoElement.msFrameStep() - Web APIs
syntax htmlvideoelement.msframestep(forward); parameters forward a boolean which if set to
true steps the video forward by one frame, if false steps the video backwards by one frame.
Headers.has() - Web APIs
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, 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.
IDBDatabase.transaction() - Web APIs
you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to
true in about:config.
IDBIndexSync - Web APIs
unique readonly boolean if
true, a key can have only one value within the index; if false, a key can have duplicate values.
IDBKeyRange.bound() - Web APIs
if we used idbkeyrange.bound("a", "f",
true,
true);, then the range would not include "a" and "f", only the values between them.
IDBOpenDBRequest.onupgradeneeded - Web APIs
var store = db.createobjectstore("books", {keypath: "isbn"}); var titleindex = store.createindex("by_title", "title", {unique:
true}); var authorindex = store.createindex("by_author", "author"); } if (event.oldversion < 2) { // version 2 introduces a new index of books by year.
IDBTransaction.oncomplete - Web APIs
you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to
true in about:config.
IdleDeadline - Web APIs
properties idledeadline.didtimeout read only a boolean whose value is
true if the callback is being executed because the timeout specified when the idle callback was installed has expired.
ImageCapture() constructor - Web APIs
navigator.mediadevices.getusermedia({video:
true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in that specification.
ImageCapture.getPhotoCapabilities() - Web APIs
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...
ImageCapture.getPhotoSettings() - Web APIs
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...
ImageCapture - Web APIs
var imagecapture; function ongetusermediabuttonclick() { navigator.mediadevices.getusermedia({video:
true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); } function ongrabframebuttonclick() { imagecapture.grabframe() .then(imagebitmap => { const canvas = document.queryselector('#grabframecanvas'); drawcanvas(ca...
Basic concepts - Web APIs
you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to
true in about:config.
LockedFile - Web APIs
lockedfile.active read only a flag indicating if the file can be accessed (
true) or not (false).
MSGraphicsTrust - Web APIs
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.
MediaDevices - Web APIs
var video = document.queryselector('video'); var constraints = window.constraints = { audio: false, video:
true }; var errorelement = document.queryselector('#errormsg'); navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var videotracks = stream.getvideotracks(); console.log('got stream with constraints:', constraints); console.log('using video device: ' + videotracks[0].label); stream.onremovetrack = function() { console.log('stream ended'); }; window.stream = stre...
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() - Web APIs
if (navigator.mediadevices.getusermedia) { var constraints = { audio:
true, video:
true }; var chunks = []; var onsuccess = function(stream) { var options = { audiobitspersecond : 128000, videobitspersecond : 2500000, mimetype : 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; ...
MediaRecorder: error event - Web APIs
examples using addeventlistener to listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio:
true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia({audio:
true}); const recorder = ne...
MediaRecorder.mimeType - Web APIs
if (navigator.mediadevices) { console.log('getusermedia supported.'); 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' ...
MediaRecorder.ondataavailable - Web APIs
var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls =
true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder.onstop - Web APIs
mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls =
true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder.stream - Web APIs
example if (navigator.getusermedia) { console.log('getusermedia supported.'); navigator.getusermedia ( // constraints - only audio needed for this app { audio:
true }, // success callback function(stream) { var mediarecorder = new mediarecorder(stream); var mystream = mediarecorder.stream; console.log(mystream); ...
Media Session action types - Web APIs
if you intend to perform multiple seekto operations in rapid succession, you can also specify the mediasessionactiondetails property fastseek property with a value of
true.
MediaSessionActionDetails.seekTime - Web APIs
usage notes to perform a "fast" seek (such as when issuing multiple seekto actions in sequence while handling a scrubbing operation, the details object's fastseek property's value is set to
true, indicating that you should minimize or eliminate anything you do while handling the action that is only necessary at the final step.
MediaSessionActionDetails - Web APIs
if you intend to perform multiple seekto operations in rapid succession, you can also specify the mediasessionactiondetails property fastseek property with a value of
true.
MediaSettingsRange - Web APIs
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...
MediaSource.duration - Web APIs
their sourcebuffer.updating property is
true.) example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistene...
MediaSource.endOfStream() - Web APIs
their sourcebuffer.updating property is
true.) example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasourc...
MediaStream.getAudioTracks() - Web APIs
navigator.mediadevices.getusermedia({audio:
true, video:
true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the audio stream after 5 seconds settimeout(() => { const tracks = mediastream.getaudiotracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'getaudiotracks()' in that specificat...
MediaStream.getTrackById() - Web APIs
stream.gettrackbyid("primary-audio-track").applyconstraints({ volume: 0.5 }); stream.gettrackbyid("commentary-track").enabled =
true; specifications specification status comment media capture and streamsthe definition of 'gettrackbyid()' in that specification.
MediaStream.getTracks() - Web APIs
example navigator.mediadevices.getusermedia({audio: false, video:
true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the stream after 5 seconds settimeout(() => { const tracks = mediastream.gettracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'gettracks()' in that specification.
MediaStream.getVideoTracks() - Web APIs
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.
MediaStream.id - Web APIs
syntax var id = mediastream.id; example var p = navigator.mediadevices.getusermedia({ audio:
true, video:
true }); p.then(function(stream) { console.log(stream.id); }) specifications specification status comment media capture and streamsthe definition of 'mediastream.id' in that specification.
MediaStreamAudioSourceNode() - Web APIs
// define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints: audio and video for this app { audio:
true, video: false }).then(function(stream) { var options = { mediastream : stream } var source = new mediastreamaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported ...
MediaStreamAudioSourceNode - Web APIs
'pre'); var video = document.queryselector('video'); var myscript = document.queryselector('script'); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio:
true, video:
true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted =
true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); ...
MediaStreamTrack.applyConstraints() - Web APIs
const constraints = { width: {min: 640, ideal: 1280}, height: {min: 480, ideal: 720}, advanced: [ {width: 1920, height: 1280}, {aspectratio: 1.333} ] }; navigator.mediadevices.getusermedia({ video:
true }) .then(mediastream => { const track = mediastream.getvideotracks()[0]; track.applyconstraints(constraints) .then(() => { // do something with the track such as using the image capture api.
MediaStreamTrack.muted - Web APIs
syntax const mutedflag = track.muted value a boolean which is
true if the track is currently muted, or false if the track is currently unmuted.
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.
MediaStreamTrackAudioSourceNode() - Web APIs
let audioctx = new (window.audiocontext || window.webkitaudiocontext)(); if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio:
true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not ...
MediaStreamTrackAudioSourceNode - Web APIs
'pre'); var video = document.queryselector('video'); var myscript = document.queryselector('script'); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio:
true, video:
true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted =
true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); ...
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
let audioctx = new (window.audiocontext || window.webkitaudiocontext)(); if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio:
true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not ...
Recording a media element - Web APIs
getting an input stream and setting up the recorder now let's look at the most intricate piece of code in this example: our event handler for clicks on the start button: startbutton.addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video:
true, audio:
true }).then(stream => { preview.srcobject = stream; downloadbutton.href = stream; preview.capturestream = preview.capturestream || preview.mozcapturestream; return new promise(resolve => preview.onplaying = resolve); }).then(() => startrecording(preview.capturestream(), recordingtimems)) .then (recordedchunks => { let recordedblob = new blob(recordedchunks, ...
Using the MediaStream Recording API - Web APIs
op = document.queryselector('.stop'); const soundclips = document.queryselector('.sound-clips'); finally for this section, we set up the basic getusermedia structure: if (navigator.mediadevices && navigator.mediadevices.getusermedia) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio:
true }) // success callback .then(function(stream) { }) // error callback .catch(function(err) { console.log('the following getusermedia error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } the whole thing is wrapped in a test that checks whether getusermedia is supported before running anythi...
MediaTrackConstraints.autoGainControl - Web APIs
syntax var constraintsobject = { autogaincontrol: constraint }; constraintsobject.autogaincontrol = constraint; value if this value is a simple
true or false, the user agent will attempt to obtain media with automatic gain control enabled or disabled as specified, if possible, but will not fail if this can't be done.
MediaTrackConstraints.displaySurface - Web APIs
r example, if your app needs to know that the surface being shared is a monitor or application—meaning that there's possibly a non-content backdrop—it can use code similar to this: let mayhavebackdropflag = false; let displaysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || displaysurface ==="application") { mayhavebackdropflag =
true; } following this code, mayhavebackdrop is
true if the display surface contained in the stream is of type monitor or application; either of these may have non-content backdrop areas.
MediaTrackConstraints.echoCancellation - Web APIs
syntax var constraintsobject = { echocancellation: constraint }; constraintsobject.echocancellation = constraint; value if this value is a simple
true or false, the user agent will attempt to obtain media with echo cancellation enabled or disabled as specified, if possible, but will not fail if this can't be done.
MediaTrackConstraints.noiseSuppression - Web APIs
syntax var constraintsobject = { noisesuppression: constraint }; constraintsobject.noisesuppression = constraint; value if this value is a simple
true or false, the user agent will attempt to obtain media with noise suppression enabled or disabled as specified, if possible, but will not fail if this can't be done.
MediaTrackSettings.echoCancellation - Web APIs
syntax var echocancellation = mediatracksettings.echocancellation; value a boolean value which is
true if the track has echo cancellation functionality enabled or false if echo cancellation is disabled.
Metadata.modificationTime - Web APIs
workingdirectory.getfile("tmp/workfile.json", { create:
true }, function(fileentry) { fileentry.getmetadata(function(metadata) { if ((new date().getfullyear() - metadata.modificationtime.getfullyear()) >= 5) { fileentry.remove(function() { workingdirectory.getfile("tmp/workfile.json", { create:
true }, function(newentry) { fileentry = newentry; }); }); } }); }, handleerror); this api has no official w3c o...
MouseEvent.altKey - Web APIs
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.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.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.
MouseEvent.initMouseEvent() - Web APIs
<div style="background:red; width:180px; padding:10px;"> <div id="out"></div> <input type="text"> </div> javascript document.body.onclick = function(){ e = arguments[0]; var dt = e.target,stag = dt.tagname.tolowercase(); document.getelementbyid("out").innerhtml = stag; }; var simulateclick = function(){ var evt = document.createevent("mouseevents"); evt.initmouseevent("click",
true,
true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); document.body.dispatchevent(evt); } simulateclick(); result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.initmouseevent()' in that specification.
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.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.
msPlayToDisabled - Web APIs
syntax ptr = object.msplaytodisabled; value boolean value set to
true indicates that the playto device is disabled.
msPlayToPrimary - Web APIs
syntax ptr = object.msplaytoprimary; value boolean value set to
true indicates that the device is the primary dlna playto device, otherwise false.
msRealTime - Web APIs
syntax ptr = object.msrealtime; value boolean value set to
true indicates that low-latency playback will be enabled on the media element.
MutationObserver.disconnect() - Web APIs
const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist:
true, attributes:
true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* some time later...
MutationObserver.takeRecords() - Web APIs
const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist:
true, attributes:
true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing...
MutationObserver - Web APIs
// select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config = { attributes:
true, childlist:
true, subtree:
true }; // callback function to execute when mutations are observed const callback = function(mutationslist, observer) { // use traditional 'for loops' for ie 11 for(let mutation of mutationslist) { if (mutation.type === 'childlist') { console.log('a child node has been added or removed.'); } else if (mutation.type === 'attri...
MutationRecord - Web APIs
note that for this to work as expected, attributeoldvalue or characterdataoldvalue must be set to
true in the corresponding mutationobserverinit parameter of the mutationobserver observe method specifications specification status comment domthe definition of 'mutationrecord' in that specification.
NDEFReader.scan() - Web APIs
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.
NDEFWriter.write() - Web APIs
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.
Navigator.credentials - Web APIs
example if ('credentials' in navigator) { navigator.credentials.get({password:
true}) .then(function(creds) { //do something with the credentials.
Navigator.getBattery() - Web APIs
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.getUserMedia() - Web APIs
navigator.getusermedia = navigator.getusermedia || navigator.webkitgetusermedia || navigator.mozgetusermedia; if (navigator.getusermedia) { navigator.getusermedia({ audio:
true, video: { width: 1280, height: 720 } }, function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); }; }, function(err) { console.log("the following error occurred: " + err.name); } ); } else { console.log("getusermedia not suppor...
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
4" linux output of uname -sm x.y refers to the version of the operating system example function osinfo() { alert(window.navigator.oscpu); } osinfo(); // alerts "windows nt 6.0" for example usage notes unless your code is privileged (chrome or at least has the universalbrowserread privilege), it may get the value of the general.oscpu.override preference instead of the
true platform.
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.
NetworkInformation - Web APIs
networkinformation.savedata read only returns
true if the user has set a reduced data usage option on the user agent.
Network Information API - Web APIs
let preloadvideo =
true; var connection = navigator.connection || navigator.mozconnection || navigator.webkitconnection; if (connection) { if (connection.effectivetype === 'slow-2g') { preloadvideo = false; } } interfaces networkinformation provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type change...
Node.nodeType - Web APIs
examples different types of nodes document.nodetype === node.document_node; //
true document.doctype.nodetype === node.document_type_node; //
true document.createdocumentfragment().nodetype === node.document_fragment_node; //
true var p = document.createelement("p"); p.textcontent = "once upon a time…"; p.nodetype === node.element_node; //
true p.firstchild.nodetype === node.text_node; //
true comments this example checks if the first node inside the document element is ...
Node.setUserData() - Web APIs
example var d = document.implementation.createdocument('', 'test', null); d.documentelement.setuserdata('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object element]::[object element] console.log(d.documentelement.getuserdata('key')); // 15 var e = document.importnode(d.documentelement,
true); // causes handler to be called console.log(e.getuserdata('key')); // null since user data is not copied specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.setuserdata()' 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.
NodeIterator - Web APIs
nodeiterator.pointerbeforereferencenode read only returns a boolean flag that indicates whether the nodeiterator is anchored before, the flag being
true, or after, the flag being false, the anchor node.
NonDocumentTypeChildNode.nextElementSibling - Web APIs
urn 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:
true, 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 ...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
} }); } 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', { configurable:
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 o...
Notification.requireInteraction - Web APIs
note: this can be set when the notification is first created by setting the requireinteraction option to
true in the options object of the notification.notification() constructor.
OfflineAudioContext.startRendering() - Web APIs
rce code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop =
true; offlinectx.startrendering().then(function(renderedbuffer) { ...
OfflineAudioContext - Web APIs
rce code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop =
true; offlinectx.startrendering().then(function(renderedbuffer) { ...
Page Visibility API - Web APIs
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.
ParentNode.append() - Web APIs
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(isnode ?
ParentNode.prepend() - Web APIs
d("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(isnode ?
PaymentAddress - Web APIs
ods: "basic-card", }, ]; const details = { total: { label: "donation", amount: { currency: "usd", value: "65.00" } }, displayitems: [ { label: "original donation amount", amount: { currency: "usd", value: "65.00" }, }, ], shippingoptions: [ { id: "standard", label: "standard shipping", amount: { currency: "usd", value: "0.00" }, selected:
true, }, ], }; const options = { requestshipping:
true }; async function dopaymentrequest() { const request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
PaymentCurrencyAmount.value - Web APIs
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.
PaymentDetailsUpdate.error - Web APIs
this happens if both of the following are
true: the paymentrequest specifies using its requestshipping property that shipping information is required.
PaymentItem - Web APIs
pending secure context a boolean value which is
true if the specified amount has not yet been finalized.
PaymentRequest: paymentmethodchange event - Web APIs
const options = { requestshipping:
true }; const paymentrequest = new paymentrequest(paymentmethods, detailsforshipping("ground"), options); paymentrequest.addeventlistener("paymentmethodchange", handlepaymentchange, false); paymentrequest.show() .then(response => response.complete("success")) .catch(err => console.log("error handling payment request: " + err)); the event handler function itself, handlepaymentchange(), looks...
PaymentRequest.show() - Web APIs
yment as failed: async function validateresponse(response) { try { if (await checkallvalues(response)) { await response.complete("success"); } else { await response.complete("fail"); } } catch(err) { await response.complete("fail"); } } here, a custom function called checkallvalues() looks at each value in the response and ensures that they're valid, returning
true if every field is valid or false if any are not.
PaymentResponse.onpayerdetailchange - Web APIs
const options = { requestshipping:
true, requestpayeremail:
true, requestpayername:
true, requestpayerphone:
true, }; const request = new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections a...
PayerResponse.payerPhone - Web APIs
this option is only present when the requestpayerphone option is set to
true in the paymentoptions object passed to the paymentrequest constructor.
PaymentResponse: payerdetailchange event - Web APIs
const options = { requestshipping:
true, requestpayeremail:
true, requestpayername:
true, requestpayerphone:
true, }; const request = new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections a...
PeriodicWave - Web APIs
var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization:
true}); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a sine wave here, we create a periodicwave with two values.
Permissions.query() - Web APIs
by the user, in the relevant permissions dialog), navigator.permissions.query() will return
true for both notifications and push.
Permissions.revoke() - Web APIs
by the user, in the relevant permissions dialog), navigator.permissions.query() will return
true for both notifications and push.
PhotoCapabilities - Web APIs
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...
PointerEvent.PointerEvent() - Web APIs
example var moveevent = new pointerevent("pointermove"); var downevent = new pointerevent("pointerdown", {pointerid: 1, bubbles:
true, cancelable:
true, pointertype: "touch", width: 100, height: 100, isprimary:
true }); ...
PointerEvent.getCoalescedEvents() - Web APIs
nowebview android full support 58chrome android full support 58firefox android partial support 59disabled partial support 59disabled disabled from version 59: this feature is behind the dom.w3c_pointer_events.enabled preference (needs to be set to
true).
Pointer Lock API - Web APIs
y; if (!animation) { animation = requestanimationframe(function() { animation = null; canvasdraw(); }); } } the canvasdraw() function draws the ball in the current x and y positions: function canvasdraw() { ctx.fillstyle = "black"; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = "#f00"; ctx.beginpath(); ctx.arc(x, y, radius, 0, degtorad(360),
true); ctx.fill(); } iframe limitations pointer lock can only lock one iframe at a time.
Multi-touch interaction - Web APIs
false :
true; } function log(name, ev) { var o = document.getelementsbytagname('output')[0]; var s = name + ": pointerid = " + ev.pointerid + " ; pointertype = " + ev.pointertype + " ; isprimary = " + ev.isprimary; o.innerhtml += s + " "; } function clearlog(event) { var o = document.getelementsbytagname('output')[0]; o.innerhtml = ""; } ...
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 = ""; } ...
PublicKeyCredential.getClientExtensionResults() - Web APIs
examples var publickey = { // here are the extensions (as "inputs") extensions: { "loc":
true, // this extension has been defined to include location information in attestation "uvi":
true // user verification index: how the user was verified }, challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe...
PublicKeyCredentialCreationOptions - Web APIs
smith", }, // requested format of new keypair pubkeycredparams: [{ type: "public-key", alg: cose_alg_ecdsa_w_sha256, }], // timeout after 1 minute timeout: 60000, // do not send the authenticator's origin attestation attestation: "none", extensions: { uvm:
true, exts:
true }, // filter out authenticators which are bound to the device authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey:
true, userverification: "preferred" }, // exclude already existing credentials for the user excludecredentials: [ { type: "publ...
PublicKeyCredentialRequestOptions - Web APIs
mple.com */ userverification: "preferred", timeout: 60000, // wait for a minute allowcredentials: [ { transports: "usb", type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: "internal", type: "public-key", id: new uint8array(26) // actually provided by the server } ], extensions: { uvm:
true, // rp wants to know how the user was verified loc: false, txauthsimple: "could you please verify yourself?" } }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specification...
PushManager.getSubscription() - Web APIs
et 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.debug.log('error during getsubscription()', err); }); }); specifications specification status comment push apithe definition of 'getsubscription()' in that specification.
PushManager.subscribe() - Web APIs
} navigator.serviceworker.register('serviceworker.js'); // use serviceworker.ready to ensure that you can subscribe for push navigator.serviceworker.ready.then( function(serviceworkerregistration) { var options = { uservisibleonly:
true, applicationserverkey: applicationserverkey }; serviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
PushSubscription.endpoint - Web APIs
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.subscribe({uservisibleonly:
true}).then(function(subscription) { console.log(subscription.endpoint); // at this point you would most likely send the subscription // endpoint to your server, save it, then use it to send a // push message at a later date }) }) specifications specification status comment push apithe definition of 'endpoint' in that specification.
PushSubscription.getKey() - Web APIs
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'); ...
RTCDataChannel.id - Web APIs
this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is
true).
RTCDataChannel.onclose - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("messagechannel")}}; dc.onopen = function(event) { document.getelementbyid("messagebox").disabled = false; document.getelementbyid("sendbutton").disabled = false; }; dc.onclose = function(event) { document.getelementbyid("messagebox").disabled =
true; document.getelementbyid("sendbutton").disabled =
true; } /* now negotiate the connection, etc...
RTCDataChannel.stream - Web APIs
this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is
true).
RTCDataChannel - Web APIs
ly 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 property ordered indicates whether or not the data channel guarantees in-order delivery of messages; the default is
true, which indicates that the data channel is indeed ordered.protocol read only the read-only rtcdatachannel property protocol returns a domstring containing the name of the subprotocol in use.
RTCIceCandidate.address - Web APIs
security notes it's important to note here that although webrtc does not require the two peers on an rtcpeerconnection to know one another's
true ip addresses, the address property on rtcicecandidate can expose more information about the source of the remote peer than the user expects.
RTCIceCandidate.type - Web APIs
host the candidate is a host candidate, whose ip address as specified in the rtcicecandidate.ip property is in fact the
true address of the remote peer.
RTCIceCandidatePairStats.nominated - Web APIs
syntax nominated = rtcicecandidatepairstats.nominated; value a boolean value which is set to
true by the ice layer if the controlling user agent has indicated that the candidate pair should be used to configure the webrtc connection between the two peers.
RTCIceCandidatePairStats.readable - Web APIs
syntax isreadable = rtcicecandidatepairstats.readable; value a boolean value which is
true if the connection described by this candidate pair has received at least one valid ice request, and is therefore ready to be read from.
RTCIceCandidatePairStats.writable - Web APIs
syntax iswritable = rtcicecandidatepairstats.writable; value a boolean value which is
true if the connection described by this candidate pair has received acknowledgement of receipt (ack) for at least one ice request and that stun consent hasn't expired.
RTCIceCandidateStats.candidateType - Web APIs
syntax candidatetype = rtcicecandidatestats.candidatetype; value a domstring whose value is one of the strings found in the rtcicecandidatetype enumerated type:host the candidate is a host candidate, whose ip address as specified in the rtcicecandidate.ip property is in fact the
true address of the remote peer.
RTCIceCandidateType - Web APIs
host the candidate is a host candidate, whose ip address as specified in the rtcicecandidate.ip property is in fact the
true address of the remote peer.
RTCOfferAnswerOptions - Web APIs
the default value is
true, enabling this functionality specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcofferansweroptions' in that specification.
RTCOfferOptions - Web APIs
icerestart optional a boolean which, when set to
true, tells createoffer() to generate and use new values for the identifying properties of the sdp it creates, resulting in a request that triggers renegotiation of the ice connection.
RTCPeerConnection.addStream() - Web APIs
navigator.mediadevices.getusermedia({video:
true, audio:
true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:
true, audio:
true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); ...
RTCPeerConnection.removeStream() - Web APIs
example var pc, videostream; navigator.getusermedia({video:
true}, function(stream) { pc = new rtcpeerconnection(); videostream = stream; pc.addstream(stream); } document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removestream(videostream); pc.close(); }, false); ...
RTCPeerConnection.removeTrack() - Web APIs
var pc, sender; navigator.getusermedia({video:
true}, function(stream) { pc = new rtcpeerconnection(); var track = stream.getvideotracks()[0]; sender = pc.addtrack(track, stream); }); document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removetrack(sender); pc.close(); }, false); specifications specification status comment webrtc 1.0: real-time communication between browsers...
RTCRtpReceiver.getCapabilities() static function - Web APIs
function canreceiveh264() { let capabilities = rtcrtpreceiver.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { return
true; } }); return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getcapabilities()' in that specification.
RTCRtpSender.getCapabilities() static function - Web APIs
function cansendh264() { let capabilities = rtcrtpsender.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { return
true; } }); return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.getcapabilities()' in that specification.
RTCRtpSynchronizationSource.voiceActivityFlag - Web APIs
syntax var voiceactivity = rtcrtpsynchronizationsource.voiceactivityflag value a boolean value which is
true if voice activity is present in the most recently received rtp packet played by the associated source, or false if voice activity is not present.
RTCRtpTransceiver.currentDirection - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to
true, the sender has an active encoding.
RTCRtpTransceiver.direction - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to
true, the sender has an active encoding.
RTCRtpTransceiver.stopped - Web APIs
syntax var isstopped = rtcrtptransceiver.stopped; value a boolean value which is
true if the transceiver's sender will no longer send data, and its receiver will no longer receive data.
RTCRtpTransceiverDirection - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to
true, the sender has an active encoding.
RTCSessionDescription() - Web APIs
navigator.getusermedia({video:
true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(new rtcsessiondescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling.
Range.collapsed - Web APIs
it returns
true if the start and end boundary points of the range are the same point in the dom, false if not.
ReadableStream.locked - Web APIs
}); 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.
Report.body - Web APIs
examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report body, i.e.
Report.type - Web APIs
examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report type, i.e.
Report.url - Web APIs
examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the url of the document that generated the first report // e.g.
Report - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); because of the event han...
ReportingObserver.disconnect() - Web APIs
syntax reportingobserverinstance.disconnect() examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() ...
ReportingObserver.observe() - Web APIs
syntax reportingobserverinstance.observe() examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() specifications specification status comment reporting apithe definition of 'reportingobserver.observe()' in that specification.
ReportingObserver.takeRecords() - Web APIs
examples let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() // ...
ReportingObserver - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered:
true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example ...
Response.ok - Web APIs
var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns
true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification.
Response.redirected - Web APIs
syntax var isredirected = response.redirected; value a boolean which is
true if the response indicates that your request was redirected.
Response.useFinalURL - Web APIs
example consider a script residing in page index.html: fetch('/test').then((r) => console.log(r.url)) test.html is being controlled by the service worker sw.js: 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.
SVGAnimationElement: endEvent event - Web APIs
'li'); listitem.textcontent = 'endevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = 'repeatevent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) btn.addeventlistener('click', () => { btn.disabled =
true; animateelem.setattribute('repeatcount', '1'); }) event handler property equivalent note that you can also create an event listener for the end event using the onend event handler property: animateelem.onend = () => { console.log('endevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'endevent' in that ...
SVGGraphicsElement: paste event - Web APIs
bubbles yes cancelable yes interface clipboardevent event handler property onpaste if the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to
true) then the default action is to insert the contents of the clipboard into the document at the cursor position.
SVGTests - Web APIs
methods svgtests.hasextension() read only returns
true if the browser supports the given extension, specified by a uri.
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.
Screen Wake Lock API - Web APIs
if ('wakelock' in navigator) { issupported =
true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled =
true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object.
ScriptProcessorNode.bufferSize - Web APIs
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = func...
ScriptProcessorNode.onaudioprocess - Web APIs
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = f...
ScriptProcessorNode - Web APIs
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg',
true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = func...
ServiceWorker.onstatechange - Web APIs
for example: navigator.serviceworker.register(..).then(function(swr) { swr.installing.state == "installing" swr.installing.onstatechange = function() { swr.installing == null; // at this point, swr.waiting or swr.active might be
true.
Using Service Workers - Web APIs
if however you find that demo code is not working in your installed versions, you might need to enable a pref: firefox nightly: go to about:config and set dom.serviceworkers.enabled to
true; restart browser.
SourceBuffer.appendBufferAsync() - Web APIs
async function fillsourcebuffer(buffer, msbuffer) { try { while(
true) { await msbuffer.appendbufferasync(buffer); } } catch(e) { handleexception(e); } } specifications not currently part of any specification.
SourceBuffer.mode - Web APIs
its sourcebuffer.updating property is currently
true), the last media segment appended to this sourcebuffer is incomplete, or this sourcebuffer has been removed from the mediasource.
SourceBuffer.remove() - Web APIs
invalidstateerror the sourcebuffer.updating property is equal to
true, or this sourcebuffer has been removed from the mediasource.
SourceBuffer.timestampOffset - Web APIs
their sourcebuffer.updating property is currently
true), a media segment inside the sourcebuffer is currently being parsed, or this sourcebuffer has been removed from the mediasource.
SpeechRecognition - Web APIs
defaults to single (false.) speechrecognition.interimresults controls whether interim results should be returned (
true) or not (false.) interim results are results that are not yet final (e.g.
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.
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.
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.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.
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.
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.
StyleSheet.disabled - Web APIs
a style sheet may be disabled by manually setting this property to
true or if it's an inactive alternative style sheet.
SubtleCrypto.deriveKey() - Web APIs
enc.encode(password), "pbkdf2", false, ["derivebits", "derivekey"] ); } async function encrypt(plaintext, salt, iv) { let keymaterial = await getkeymaterial(); let key = await window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256},
true, [ "encrypt", "decrypt" ] ); return window.crypto.subtle.encrypt( { name: "aes-gcm", iv: iv }, key, plaintext ); } specifications specification status comment web cryptography apithe definition of 'subtlecrypto.derivekey()' in that specification.
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.
SyncEvent - Web APIs
syncevent.lastchance read only returns
true if the user agent will not make further synchronization attempts after the current attempt.
TextDecoder() - Web APIs
example var textdecoder1 = new textdecoder("iso-8859-2"); var textdecoder2 = new textdecoder(); var textdecoder3 = new textdecoder("csiso2022kr", {fatal:
true}); // allows encodingerror exception to be thrown.
TouchEvent - Web APIs
the exception to this is chrome, starting with version 56 (desktop, chrome for android, and android webview), where the default value for the passive option for touchstart and touchmove is
true and calls to preventdefault() will have no effect.
Touch events - Web APIs
eevents"); 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]; break; } newevt.initmouseevent(type,
true,
true, evt.originaltarget.ownerdocument.defaultview, 0, touch.screenx, touch.screeny, touch.clientx, touch.clienty, evt.ctrlkey, evt.altkey, evt.shiftkey, evt.metakey, 0, null); evt.originaltarget.dispatchevent(newevt); } calling preventdefault() only on a second touch one technique for preventing things like pinchzoom on a page is to call preventdefault() on the second touch in a se...
UIEvent.initUIEvent() - Web APIs
example var e = document.createevent("uievent"); // creates a click event that bubbles, can be cancelled, // and with its view and detail property initialized to window and 1, // respectively e.inituievent("click",
true,
true, window, 1); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'uievent.inituievent()' in that specification.
UIEvent.isChar - Web APIs
syntax var ischar = uievent.ischar; value a boolean which is
true if the event produces a character; otherwise false.
URLSearchParams.has() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); params.has('bar') ===
true; //
true specifications specification status comment urlthe definition of 'has()' in that specification.
URLSearchParams.set() - Web APIs
k:", "", "// eslint-disable-next-line no-unused-vars", "lockpref( 'keyword.url',\t\t'https://duckduckgo.com/html/?q=!+' )\t// test", "/*", " * bla bla ", "*/", "", "/* bla bla */", "", "// bla bla ", "", "these shouldn\'t work:", "console.log(\"http://foo.co.uk/\")", "var url = \"http://regexr.com/foo.html?q=bar\"", "alert(\"https://mediatemple.net\")", ] ,
true ) console.info( url, url.tostring() ) // window.open( url, 'regex_site' ) specifications specification status comment urlthe definition of 'set()' in that specification.
USBDevice.clearHalt() - Web APIs
while (
true) { let result = await data.transferin(1, 6); if (result.data && result.data.bytelength === 6) { console.log('channel 1: ' + result.data.getuint16(0)); console.log('channel 2: ' + result.data.getuint16(2)); console.log('channel 5: ' + result.data.getuint16(4)); } if (result.status === 'stall') { console.warn('endpoint stalled.
VTTCue - Web APIs
vttcue.snaptolines returns
true if the vttcue.line attribute is an integer number of lines or a percentage of the video size.
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.
WebGLRenderingContext.blendEquation() - Web APIs
gl.getparameter(gl.blend_equation_rgb) === gl.func_add; //
true gl.getparameter(gl.blend_equation_alpha) === gl.func_add; //
true specifications specification status comment webgl 1.0the definition of 'blendequation' in that specification.
WebGLRenderingContext.blendEquationSeparate() - Web APIs
gl.getparameter(gl.blend_equation_rgb) === gl.func_add; //
true gl.getparameter(gl.blend_equation_alpha) === gl.func_add; //
true specifications specification status comment webgl 1.0the definition of 'blendequationseparate' in that specification.
WebGLRenderingContext.blendFunc() - Web APIs
gl.enable(gl.blend); gl.blendfunc(gl.src_color, gl.dst_color); gl.getparameter(gl.blend_src_rgb) == gl.src_color; //
true specifications specification status comment webgl 1.0the definition of 'blendfunc' in that specification.
WebGLRenderingContext.blendFuncSeparate() - Web APIs
gl.enable(gl.blend); gl.blendfuncseparate(gl.src_color, gl.dst_color, gl.one, gl.zero); gl.getparameter(gl.blend_src_rgb) == gl.src_color; //
true specifications specification status comment webgl 1.0the definition of 'blendfunc' in that specification.
WebGLRenderingContext.enable() - Web APIs
examples gl.enable(gl.dither); to check if a capability is enabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); //
true specifications specification status comment webgl 1.0the definition of 'enable' in that specification.
WebGLRenderingContext.getContextAttributes() - Web APIs
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, ...
Hello vertex attributes - Web APIs
tic_draw); gl.drawarrays(gl.points, 0, 1); }, false); } 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]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } window.addeventlistener("beforeunload", cleanup,
true); function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } 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) { ...
WebGL model view projection - Web APIs
the value of w is used as a divisor for the other components of the coordinate, so that the
true values of x, y, and z are computed as x/w, y/w, and z/w (and w is then also w/w, becoming 1).
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
async function disablehold(micstream) { await audiotransceiver.sender.replacetrack(micstream.getaudiotracks()[0]); audiotransceiver.receiver.track.enabled =
true; audiotransceiver.direction = "sendrecv"; } this reverses the steps taken in enablehold() as follows: the audio transceiver's rtcrtpsender's track is replaced with the specified stream's first audio track.
Fundamentals of WebXR - Web APIs
the most obvious difference, at the highest level, is that webxr supports not just virtual reality applications, but also augmented reality, which blends virtual objects with the user's
true physical environment.
Inputs and input sources - Web APIs
because this use of the gamepad interface is a convenience rather than a
true application of the gamepad api, there are several differences between how it's used with webxr and how it's used in gamepad api applications.
WebXR Device API - Web APIs
if the context was not initially created with the xrcompatible property set to
true, you must call makexrcompatible() prior to attempting to use the webgl context for webxr rendering.
Using the Web Audio API - Web APIs
t playbutton = document.queryselector('button'); playbutton.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audiocontext.state === 'suspended') { audiocontext.resume(); } // play or pause track depending on state if (this.dataset.playing === 'false') { audioelement.play(); this.dataset.playing = '
true'; } else if (this.dataset.playing === '
true') { audioelement.pause(); this.dataset.playing = 'false'; } }, false); we also need to take into account what to do when the track finishes playing.
Using the Web Storage API - Web APIs
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 === 'ns...
Using Web Workers - Web APIs
which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa: function emulatemessage(vval) { return eval('(' + json.stringify(vval) + ')'); } // tests // test #1 var example1 = new number(3); console.log(typeof example1); // object console.log(typeof emulatemessage(example1)); // number // test #2 var example2 =
true; console.log(typeof example2); // boolean console.log(typeof emulatemessage(example2)); // boolean // test #3 var example3 = new string('hello world'); console.log(typeof example3); // object console.log(typeof emulatemessage(example3)); // string // test #4 var example4 = { 'name': 'john smith', "age": 43 }; console.log(typeof example4); // object console.log(typeof emulatemessage(exam...
Window: devicemotion event - Web APIs
} window.addeventlistener("devicemotion", handlemotionevent,
true); specifications specification status deviceorientation event specificationthe definition of 'devicemotion event' in that specification.
Window: deviceorientation event - Web APIs
deviceorientationevent) { window.addeventlistener("deviceorientation", function(event) { // alpha: rotation around z-axis var rotatedegrees = event.alpha; // gamma: left to right var lefttoright = event.gamma; // beta: front back motion var fronttoback = event.beta; handleorientationevent(fronttoback, lefttoright, rotatedegrees); },
true); } var handleorientationevent = function(fronttoback, lefttoright, rotatedegrees) { // do something amazing }; specifications specification status deviceorientation event specificationthe definition of 'deviceorientation event' in that specification.
window.dump() - Web APIs
to see the dump output you have to enable it by setting the preference browser.dom.window.dump.enabled to
true.
Window: load event - Web APIs
y-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.queryselector('.event-log-contents'); const reload = document.queryselector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(
true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('readystatechange', (event) => { log.textcontent = log.textcontent + `readystate: ${document.readystate}\n`; }); document.addeventlistener('domcontentloaded', (event) => { log.textcontent = log.textcontent + `domcontentloaded\n`; }); result ...
Window: online event - Web APIs
the online event of the window interface is fired when the browser has gained access to the network and the value of navigator.online switches to
true.
Obsolete features - Web APIs
mozilla and firefox users can force new windows to always render the personal toolbar/bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to
true in about:config or in their user.js file.
Window: popstate event - Web APIs
if new-entry's document is already fully loaded and ready—that is, its readystate is complete—and the document is not already visible, it's made visible and the pageshow event is fired at the document with the pagetransitionevent's persisted attribute set to
true.
Window.scrollX - Web APIs
if (window.scrollx > 400) { window.scroll(0,0); } notes the pagexoffset property is an alias for the scrollx property: window.pagexoffset == window.scrollx; // always
true for cross-browser compatibility, use window.pagexoffset instead of window.scrollx.
Window.scrollY - Web APIs
the pageyoffset property is an alias for the scrolly property: window.pageyoffset === window.scrolly; // always
true for cross-browser compatibility, use window.pageyoffset instead of window.scrolly.
WindowEventHandlers.onhashchange - Web APIs
polyfill for event.newurl and event.oldurl // let this snippet run before your hashchange event binding code if (!window.hashchangeevent)(function(){ var lasturl = document.url; window.addeventlistener("hashchange", function(event){ object.defineproperty(event, "oldurl", {enumerable:
true,configurable:
true,value:lasturl}); object.defineproperty(event, "newurl", {enumerable:
true,configurable:
true,value:document.url}); lasturl = document.url; }); }()); specifications specification status comment html living standardthe definition of 'onhashchange' in that specification.
WritableStream.locked - Web APIs
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.
WritableStreamDefaultWriter.ready - Web APIs
function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder = new textencoder(); var encoded = encoder.encode(message, {stream:
true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
cert.sha1fingerprint + "\n"); var validity = cert.validity.queryinterface(ci.nsix509certvalidity); dump("\tvalid from " + validity.notbeforegmt + "\n"); dump("\tvalid until " + validity.notaftergmt + "\n"); } } catch(err) { alert(err); } } function test(url) { var req = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('get', url,
true); req.addeventlistener("error", function(e) { var error = createtcperrorfromfailedxhr(req); dumpsecurityinfo(req, error); }, false); req.onload = function(e) { dumpsecurityinfo(req); }; req.send(); } then test("https://addons.mozilla.org"); produced the following output in my console: connection status: succeeded security info: security sta...
XMLHttpRequest.abort() - Web APIs
var xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url,
true); xhr.send(); if (oh_noes_we_need_to_cancel_right_now_or_else) { xhr.abort(); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
var request = new xmlhttprequest(); request.open("get", "foo.txt",
true); request.send(); request.onreadystatechange = function() { if(this.readystate == this.headers_received) { // get the raw header string var headers = request.getallresponseheaders(); // convert the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of header names to values var headermap = {}; arr.f...
XMLHttpRequest.getResponseHeader() - Web APIs
var client = new xmlhttprequest(); client.open("get", "unicorns-are-teh-awesome.txt",
true); client.send(); client.onreadystatechange = function() { if(this.readystate == this.headers_received) { var contenttype = client.getresponseheader("content-type"); if (contenttype != my_expected_type) { client.abort(); } } } specifications specification status comment xmlhttprequestthe definition of 'getresponseheader()' in that specification.
XMLHttpRequest.onreadystatechange - Web APIs
examples const xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url,
true); xhr.onreadystatechange = function () { // in local files, status is 0 upon success in mozilla firefox if(xhr.readystate === xmlhttprequest.done) { var status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // the request has been completed successfully console.log(xhr.responsetext); } else { // oh no!
XMLHttpRequest.readyState - Web APIs
example var xhr = new xmlhttprequest(); console.log('unsent', xhr.readystate); // readystate will be 0 xhr.open('get', '/api',
true); console.log('opened', xhr.readystate); // readystate will be 1 xhr.onprogress = function () { console.log('loading', xhr.readystate); // readystate will be 3 }; xhr.onload = function () { console.log('done', xhr.readystate); // readystate will be 4 }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg liv...
XMLHttpRequest.response - Web APIs
var url = 'somepage.html'; //a local page function load(url, callback) { var xhr = new xmlhttprequest(); xhr.onreadystatechange = function() { if (xhr.readystate === 4) { callback(xhr.response); } } xhr.open('get', url,
true); xhr.send(''); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.responseText - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', '/server',
true); // if specified, responsetype must be empty string or "text" xhr.responsetype = 'text'; xhr.onload = function () { if (xhr.readystate === xhr.done) { if (xhr.status === 200) { console.log(xhr.response); console.log(xhr.responsetext); } } }; xhr.send(null); specifications specification status comment xmlhttprequest ...
XMLHttpRequest.responseURL - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/test',
true); xhr.onload = function () { console.log(xhr.responseurl); // http://example.com/test }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.statusText - Web APIs
example var xhr = new xmlhttprequest(); console.log('0 unsent', xhr.statustext); xhr.open('get', '/server',
true); console.log('1 opened', xhr.statustext); xhr.onprogress = function () { console.log('3 loading', xhr.statustext); }; xhr.onload = function () { console.log('4 done', xhr.statustext); }; xhr.send(null); /** * outputs the following: * * 0 unsent * 1 opened * 3 loading ok * 4 done ok */ specifications specification status comment xmlhttprequest living s...
XMLHttpRequest.timeout - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', '/server',
true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished.
XMLHttpRequestEventTarget.onabort - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url,
true); xmlhttp.onabort = function () { console.log('** the request was aborted'); }; xmlhttp.send(); //..
XMLHttpRequestEventTarget.onerror - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url,
true); xmlhttp.onerror = function () { console.log("** an error occurred during the transaction"); }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onload - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url,
true); xmlhttp.onload = function () { // do something with the retrieved data ( found in xmlhttp.response ) }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onloadstart - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url,
true); xmlhttp.onloadstart = function () { console.log("download underway"); }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onprogress - Web APIs
xmlhttprequest.onprogress = function (event) { event.loaded; event.total; }; example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url,
true); xmlhttp.onprogress = function () { //do something }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
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.
XRInputSource.targetRaySpace - Web APIs
the target ray space reported by tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the
true spatial position and orientation of the input device.
XRPose - Web APIs
if any component of the transform is computed or created artificially (such as by using mouse or keyboard controls to move through space), this value is instead
true, indicating that the transform is in part emulated in software.
XRReferenceSpace: reset event - Web APIs
if a jump in the viewer's position coincides with emulatedposition toggling from
true to false, the viewer has regained tracking, and that their new position represents a correction from the previously emulated values.
XRRenderState.baseLayer - Web APIs
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.
XRRigidTransform.position - Web APIs
pacecreated); } } function refspacecreated(refspace) { if (immersivesession) { xrreferencespace = refspace; } else { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -1.5}); ); } xrsession.requestanimationframe(onframe); } after setting up the graphics context for webxr use, this begins by looking to see if a variable immersivesession is
true; if so, we first request a bounded-floor reference space.
XRSession.requestReferenceSpace() - Web APIs
exceptions rather than throwing
true exceptions, requestreferencespace() rejects the returned promise with a domexception whose name is found in the list below: notsupportederror the requested reference space is not supported.
XRSession: visibilitychange event - Web APIs
examples this example demonstrates how to listen for a visibilitychange event on a webxr session, using addeventlistener() to begin listening for the event: navigator.xr.requestsession("inline").then((xrsession) => { xrsession.addeventlistener("visibilitychange", e => { switch(e.session.visiblitystate) { case "visible": case "visible-blurred": mysessionvisible(
true); break; case "hidden": mysessionvisible(false); break; } }); }); when a visibility state change occurs, the event is received and dispatched to a function mysessionvisible(), with a boolean parameter indicating whether or not the session is presently being displayed to the user.
XRSessionEvent() - Web APIs
xrsession.addeventlistener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mysessionvisible(
true); break; case "hidden": mysessionvisible(false); break; } }); specifications specification status comment webxr device apithe definition of 'xrsessionevent() constructor' in that specification.
XRSessionEvent.session - Web APIs
xrsession.addeventlistener("visibilitychange", e => { switch(e.session.visibilitystate) { case "hidden": myenablerendering(
true); break; case "visible": case "visible-blurred": myenablerendering(false); break; } }); this calls a function that reacts to the session's visibility state change.
XRSessionEvent - Web APIs
xrsession.addeventlistener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mysessionvisible(
true); break; case "hidden": mysessionvisible(false); break; } }); specifications specification status comment webxr device apithe definition of 'xrsessionevent' in that specification.
XRSystem: devicechange event - Web APIs
if (navigator.xr) { navigator.xr.addeventlistener("devicechange", event => { navigator.xr.issessionsupported("immersive-vr") .then(immersiveok) => { if (immersiveok) { enablexrbutton.disabled = false; } else { enablexrbutton.disabled =
true; } }); }); } when devicechange is received, the handler set up in this code calls the xr method issessionsupported() to find out if there's a device available that can handle immersive vr presentations.
XRSystem: requestSession() - Web APIs
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.
XRView - Web APIs
quat.identity(inverseorientation); quat.rotatex(inverseorientation, inverseorientation, -mousepitch); quat.rotatey(inverseorientation, inverseorientation, -mouseyaw); // compute the
true "up" vector for our object.
Using the aria-labelledby attribute - Accessibility
<dt id="homily">homily</dt> <dd role="definition" aria-labelledby="homily">a usually short sermon</dd> <dd role="definition" aria-labelledby="homily">a lecture or discourse on or of a moral theme</dd> </dl> example 7: menus in the example below, a popup menu is associated with its label using the aria-labelledby attribute: <div role="menubar"> <div role="menuitem" aria-haspopup="
true" id="filemenu">file</div> <div role="menu" aria-labelledby="filemenu"> <div role="menuitem">open</div> <div role="menuitem">save</div> <div role="menuitem">save as ...</div> ...
Using the group role - Accessibility
<div id="tree1" role="tree" tabindex="-1"> <div id="animals" class="groupheader" role="presentation" aria-owns="animalgroup" aria-expanded="
true"> <img role="presentation" tabindex="-1" src="images/treeexpanded.gif" /> <span role="treeitem" tabindex="0">animals</span> </div> <div id="animalgroup" role="group"> <div id="birds" role="treeitem"> <span tabindex="-1">birds</span> </div> <div id="cats" class="groupheader" role="presentation" aria-owns="catgroup" aria-expanded="false"> <img role="presentation"...
Using the radio role - Accessibility
class="radiogroup" id="rg1" role="radiogroup" aria-labelledby="rg1_label"> <li id="r1" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> thai </li> <li id="r2" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> subway </li> <li id="r3" tabindex="0" role="radio" aria-checked="
true"> <img role="presentation" src="radio-checked.gif" /> radio maria </li> </ul> working examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
ARIA: tabpanel role - Accessibility
<div role="tablist"> <div role="tab" aria-selected="
true" aria-controls="tabpanel-id" id="tab-id" tabindex="0">tab label</div> accessibility concerns optionally, warn of any potential accessibility concerns that exist with using this property, and how to work around them.
ARIA: document role - Accessibility
associated wai-aria roles, states, and properties aria-expanded include with a value of
true or false if the document element is collapsible, to indicate if the document is currently expanded or collapsed.
ARIA: gridcell role - Accessibility
<td contenteditable="
true">notes</td> <div role="gridcell" contenteditable="
true">item cost</div> contenteditable will make the element it is applied to focusable via the tab key.
HTML To MSAA - Accessibility
tem_ 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 is cha...
Accessibility Information for Web Authors - Accessibility
it not only checks and reports possible markup errors and warnings (based on w3c tidy and/or based on
true sgml validation) but it can also report accessibility errors and warnings according to selectable accessibility guidelines (section 508, wcag priorities 1, 2 or 3).
Mobile accessibility checklist - Accessibility
for touch events, at least one of the following must be
true (wcag 2.1: pointer cancellation): the down-event should not be used to trigger any action the action is triggered on the up event and an option to abort the action before its completion is available or an option to undo the action after its completion the up-event will undo any action that was triggered on a down event it is essential to trigger the action on the down event.
Perceivable - Accessibility
1.4.8 visual presentation (aaa) for text content presentation, the following should be
true: foreground and background colors should be user-selectable.
Understandable - Accessibility
3.3.4 error prevention (legal, financial, data) (aa) in the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be
true: submissions are reversible.
:-moz-focusring - CSS: Cascading Style Sheets
if :-moz-focusring matches, then :focus also matches, but the converse is not always
true: it depends on whether the user agent has focus ring drawing enabled and how the element was focused.
::spelling-error - CSS: Cascading Style Sheets
html <p contenteditable spellcheck="
true">my friends are coegdfgfddffbgning to the party tonight.</p> css ::spelling-error { text-decoration: wavy red; } result specifications specification status comment css pseudo-elements level 4the definition of '::spelling-error' in that specification.
CSS Box Alignment - CSS: Cascading Style Sheets
when aligning items on the inline axis you will use the properties which begin with justify-: justify-items justify-self justify-content when aligning items on the block axis you will use the properties that begin align-: align-items align-self align-content flexbox adds an additional complication in that the above is
true when flex-direction is set to row.
Variable fonts guide - CSS: Cascading Style Sheets
slant slant (represented by the slnt tag), or as it's often referred to, 'oblique' — is different to
true italics in that it changes the angle of the letterforms but doesn’t perform any kind of character substitution.
Using CSS transitions - CSS: Cascading Style Sheets
as usual, you can use the addeventlistener() method to monitor for this event: el.addeventlistener("transitionend", updatetransition,
true); you detect the beginning of a transition using transitionrun (fires before any delay) and transitionstart (fires after any delay), in the same kind of fashion: el.addeventlistener("transitionrun", signalstart,
true); el.addeventlistener("transitionstart", signalstart,
true); note: the transitionend event doesn't fire if the transition is aborted before the transition is completed because ei...
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 =...
background-color - CSS: Cascading Style Sheets
though technically removing the transparent keyword, this doesn't change anything as it has been incorporated as a
true <color> backgrounds level 3 github issues css level 2 (revision 1)the definition of 'background-color' in that specification.
font-style - CSS: Cascading Style Sheets
for
truetype or opentype variable fonts, the "slnt" variation is used to implement varying slant angles for oblique, and the "ital" variation with a value of 1 is used to implement italic values.
overflow - CSS: Cascading Style Sheets
in about:config, set layout.css.overflow.moz-scrollbars.enabled to
true description overflow options include clipping, showing scrollbars, or displaying the content flowing out of its container into the surrounding area.
Video player styling basics - Developer guides
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() function does the same thing as the altervolume() but it also sets the state of the mute button depending on the video's current volume setting.
Challenge solutions - Developer guides
the following script achieves the desired result: // javascript demonstration function dodemo (button) { var square = document.getelementbyid("square"); square.style.backgroundcolor = "#fa4"; square.style.marginleft = "20em"; 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 ov...
Mutation events - Developer guides
tion) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); // allow garbage collection observer.disconnect(); observer = undefined; } }); }); }); observer.observe(document, { childlist:
true, subtree:
true }); }; usage you can register a listener for mutation events using element.addeventlistener as follows: element.addeventlistener("domnodeinserted", function (event) { // ...
Constraint validation - Developer guides
e value rangeoverflow constraint violation date, month, week a valid date datetime, datetime-local, time a valid date and time required text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; also on the <select> and <textarea> elements none as it is a boolean attribute: its presence means
true, its absence means false there must be a value (if set).
Concurrency model and the event loop - JavaScript
console.log("ran after " + (new date().getseconds() - s) + " seconds"); }, 500) while (
true) { if (new date().getseconds() - s >= 2) { console.log("good, looped for 2 seconds") break; } } zero delays zero delay doesn't actually mean the call back will fire-off after zero milliseconds.
Keyed collections - JavaScript
let myset = new set(); myset.add(1); myset.add('some text'); myset.add('foo'); myset.has(1); //
true myset.delete('foo'); myset.size; // 2 for (let item of myset) console.log(item); // 1 // "some text" converting between array and set you can create an array from a set using array.from or the spread operator.
Inheritance and the prototype chain - JavaScript
to give you a concrete example, let's take the above graph example code to illustrate it: console.log(g.hasownproperty('vertices')); //
true console.log(g.hasownproperty('nope')); // false console.log(g.hasownproperty('addvertex')); // false console.log(g.__proto__.hasownproperty('addvertex')); //
true hasownproperty is the only thing in javascript which deals with properties and does not traverse the prototype chain.
constructor - JavaScript
class polygon { constructor() { this.name = "polygon"; } } class square extends polygon { constructor() { super(); } } class rectangle {} object.setprototypeof(square.prototype, rectangle.prototype); console.log(object.getprototypeof(square.prototype) === polygon.prototype); //false console.log(object.getprototypeof(square.prototype) === rectangle.prototype); //
true let newinstance = new square(); console.log(newinstance.name); //polygon specifications specification ecmascript (ecma-262)the definition of 'constructor method' in that specification.
Classes - JavaScript
the symbol.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 super class calls with super the super keyword is used to call corresponding methods of super class.
TypeError: "x" is not a constructor - JavaScript
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); ...
Method definitions - JavaScript
// using a named property const obj2 = { g: function* () { let index = 0 while (
true) { yield index++ } } }; // the same object using shorthand syntax const obj2 = { * g() { let index = 0 while (
true) { yield index++ } } }; const it = obj2.g() console.log(it.next().value) // 0 console.log(it.next().value) // 1 async methods async methods can also be defined using the shorthand syntax.
arguments.callee - JavaScript
ning and tail recursion impossible in the general case (you can achieve it in select cases through tracing, etc., but even the best code is suboptimal due to checks that would not otherwise be necessary.) the other major issue is that the recursive call will get a different this value, e.g.: var global = this; var sillyfunction = function(recursed) { if (!recursed) { return arguments.callee(
true); } if (this !== global) { alert('this is: ' + this); } else { alert('this is the global'); } } sillyfunction(); ecmascript 3 resolved these issues by allowing named function expressions.
getter - JavaScript
class example { get hello() { return 'world'; } } const obj = new example(); console.log(obj.hello); // "world" console.log(object.getownpropertydescriptor(obj, 'hello')); // undefined console.log( object.getownpropertydescriptor( object.getprototypeof(obj), 'hello' ) ); // { configurable:
true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined } specifications specification ecmascript (ecma-262)the definition of 'method definitions' in that specification.
AggregateError() constructor - JavaScript
examples creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); //
true console.log(e.message); // "hello" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] } specifications specification promise.anythe definition of 'aggregateerror()' in that specification.
AggregateError - JavaScript
examples catching an aggregateerror promise.any([ promise.reject(new error("some error")), ]).catch(e => { console.log(e instanceof aggregateerror); //
true console.log(e.message); // "all promises rejected" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] }); creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); //
true console.log(...
Array.prototype.copyWithin() - JavaScript
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 are subclasses of array var i3...
Array.prototype.join() - JavaScript
function f(a, b, c) { var s = array.prototype.join.call(arguments); console.log(s); // '1,a,
true' } f(1, 'a',
true); //expected output: "1,a,
true" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.join' in that specification.
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.
Boolean() constructor - JavaScript
examples creating boolean objects with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new boolean(null); var bemptystring = new boolean(''); var bfalse = new boolean(false); creating boolean objects with an initial value of
true var b
true = new boolean(
true); var b
truestring = new boolean('
true'); var bfalsestring = new boolean('false'); var bsulin = new boolean('su lin'); var barrayproto = new boolean([]); var bobjproto = new boolean({}); specifications specification ecmascript (ecma-262)the definition of 'boolean constructor' in that specification.
Date.prototype.toLocaleString() - JavaScript
for this reason, you cannot expect to be able to compare the results of tolocalestring() to a static value: "1/1/2019, 01:00:00" === new date("2019-01-01t01:00:00z").tolocalestring("en-us"); //
true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and examples.
Error - JavaScript
ew 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); //customerror console.error(e.foo); //baz console.error(e.message); //bazmessage } specifications specification ecmascript (ecma-26...
EvalError() constructor - JavaScript
creating an evalerror try { throw new evalerror('hello', 'somefile.js', 10); } catch (e) { console.log(e instanceof evalerror); //
true console.log(e.message); // "hello" console.log(e.name); // "evalerror" console.log(e.filename); // "somefile.js" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definitio...
EvalError - JavaScript
creating an evalerror try { throw new evalerror('hello', 'somefile.js', 10); } catch (e) { console.log(e instanceof evalerror); //
true console.log(e.message); // "hello" console.log(e.name); // "evalerror" console.log(e.filename); // "somefile.js" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definitio...
Function.prototype.apply() - JavaScript
urn onew; }; example usage: function myconstructor() { for (let nprop = 0; nprop < arguments.length; nprop++) { this['property' + nprop] = arguments[nprop]; } } let myarray = [4, 'hello world!', false]; let myinstance = myconstructor.construct(myarray); console.log(myinstance.property1); // logs 'hello world!' console.log(myinstance instanceof myconstructor); // logs '
true' console.log(myinstance.constructor); // logs 'myconstructor' note: this non-native function.construct method will not work with some native constructors; like date, for example.
Function.prototype.bind() - JavaScript
is.x},${this.y}`; }; const p = new point(1, 2); p.tostring(); // '1,2' // not supported in the polyfill below, // works fine with native bind: const yaxispoint = point.bind(null, 0/*x*/); const emptyobj = {}; const yaxispoint = point.bind(emptyobj, 0/*x*/); const axispoint = new yaxispoint(5); axispoint.tostring(); // '0,5' axispoint instanceof point; //
true axispoint instanceof yaxispoint; //
true new yaxispoint(17, 42) instanceof point; //
true note that you need not do anything special to create a bound function for use with new.
Function.caller - JavaScript
consider: function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); at the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -> stop() the following is
true: stop.caller === g && f.caller === g && g.caller === f so if you tried to get the stack trace in the stop() function like this: var f = stop; var stack = 'stack trace:'; while (f) { stack += '\n' + f.name; f = f.caller; } the loop would never stop.
Function.name - JavaScript
above class definition in es2015 syntax will behave in chrome or firefox similar to the following snippet in es5 syntax: function foo() {} object.defineproperty(foo, 'name', { writable:
true }); foo.name = function() {}; trying to obtain the class of fooinstance via fooinstance.constructor.name won't give us the class name at all but a reference to the static class method.
Function - JavaScript
this can be seen with the code (function(){}).constructor === function, which returns
true.
Generator - JavaScript
examples an infinite iterator function* infinite() { let index = 0; while (
true) { yield index++; } } const generator = infinite(); // "generator { }" console.log(generator.next().value); // 0 console.log(generator.next().value); // 1 console.log(generator.next().value); // 2 // ...
Intl.DateTimeFormat.prototype.format() - JavaScript
for this reason you cannot expect to be able to compare the results of format() to a static value: let d = new date("2019-01-01t00:00:00.000000z"); let formatteddate = intl.datetimeformat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d); "1.1.2019, 01:00:00" === formatteddate; //
true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and examples.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
examples datetimeformat outputs localized, opaque strings that cannot be manipulated directly: var date = date.utc(2012, 11, 17, 3, 0, 42); var formatter = new intl.datetimeformat('en-us', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalseconddigits: 3, hour12:
true, timezone: 'utc' }); formatter.format(date); // "monday, 12/17/2012, 3:00:42.000 am" however, in many user interfaces there is a desire to customize the formatting of this string.
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
ions(); usedoptions.locale; // "de-de" usedoptions.numberingsystem; // "latn" usedoptions.notation; // "standard" usedoptions.signdisplay; // "auto" usedoption.style; // "decimal" usedoptions.minimumintegerdigits; // 1 usedoptions.minimumfractiondigits; // 0 usedoptions.maximumfractiondigits; // 3 usedoptions.usegrouping; //
true specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.resolvedoptions' in that specification.
JSON - JavaScript
full json syntax the full json syntax is as follows: json = null or
true or false or jsonnumber or jsonstring or jsonobject or jsonarray jsonnumber = - positivenumber or positivenumber positivenumber = decimalnumber or decimalnumber .
Map.prototype.clear() - JavaScript
examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); //
true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification.
Math.fround() - JavaScript
var mantissa = math.round((leading - arg / powexp) * 0x800000); if (mantissa <= -0x800000) return sign * infinity; return sign * powexp * (leading - mantissa / 0x800000); }; examples using math.fround() the number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit: math.fround(1.5); // 1.5 math.fround(1.5) === 1.5; //
true however, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit: math.fround(1.337); // 1.3370000123977661 math.fround(1.337) === 1.337; // false 21502^150 is too big for a 32-bit float, so infinity is returned: 2 ** 150; // 1.42724769270596e+45 math.fround(2 ** 150); // infinity if the parameter cannot be converted to a number, o...
Number() constructor - JavaScript
examples creating number objects const a = new number('123'); // a === 123 is false const b = number('123'); // b === 123 is
true a instanceof number; // is
true b instanceof number; // is false specifications specification ecmascript (ecma-262)the definition of 'number constructor' in that specification.
Number.isSafeInteger() - JavaScript
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 spe...
Number.parseFloat() - JavaScript
polyfill if (number.parsefloat === undefined) { number.parsefloat = parsefloat; } examples number.parsefloat vs parsefloat this method has the same functionality as the global parsefloat() function: number.parsefloat === parsefloat; //
true this method is also part of ecmascript 2015.
Number.parseInt() - JavaScript
polyfill if (number.parseint === undefined) { number.parseint = window.parseint } examples number.parseint vs parseint this method has the same functionality as the global parseint() function: number.parseint === parseint //
true and is part of ecmascript 2015 (its purpose is modularization of globals).
Object.getOwnPropertyNames() - JavaScript
var target = myobject; var enum_and_nonenum = object.getownpropertynames(target); var enum_only = object.keys(target); var nonenum_only = enum_and_nonenum.filter(function(key) { var indexinenum = enum_only.indexof(key); if (indexinenum == -1) { // not found in enum_only keys, // meaning that the key is non-enumerable, // so return
true so we keep this in the filter return
true; } else { return false; } }); console.log(nonenum_only); specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertynames' in that specification.
Object.getPrototypeOf() - JavaScript
examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; //
true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object.
Object.prototype.isPrototypeOf() - JavaScript
examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(bar.prototype); var baz = new baz(); console.log(baz.prototype.isprototypeof(baz)); //
true console.log(bar.prototype.isprototypeof(baz)); //
true console.log(foo.prototype.isprototypeof(baz)); //
true console.log(object.prototype.isprototypeof(baz)); //
true isprototypeof() method, along with the instanceof operator particularly comes in handy if you have code that can only function when dealing with objects descended from a specific prototype chain, e.g., to guarantee that certain m...
Object.seal() - JavaScript
obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = object.seal(obj); o === obj; //
true object.issealed(obj); // ===
true // changing property values on a sealed object // still works.
Object.prototype.valueOf() - JavaScript
ing unary plus +"5" // 5 (string to number) +"" // 0 (string to number) +"1 + 2" // nan (doesn't evaluate) +new date() // same as (new date()).gettime() +"foo" // nan (string to number) +{} // nan +[] // 0 (tostring() returns an empty string list) +[1] // 1 +[1,2] // nan +new set([1]) // nan +bigint(1) // uncaught typeerror: cannot convert a bigint value to a number +undefined // nan +null // 0 +
true // 1 +false // 0 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.valueof' in that specification.
Promise.prototype.finally() - JavaScript
examples using finally let isloading =
true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.error(error); /* this line can also t...
Promise - JavaScript
true : false ; const parityinfo = { thenumber: value, isodd: isodd }; return parityinfo; } function troublewithgetnumber(reason) { console.error(`trouble getting number: ${reason}`); throw -999; // must "throw" something, to maintain error state down the chain } function promisegetword(parityinfo) { // the "tetheredgetword()" function gets "parityinfo" as closure variable.
handler.defineProperty() - JavaScript
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...
handler.deleteProperty() - JavaScript
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 ...
handler.getOwnPropertyDescriptor() - JavaScript
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.
handler.has() - JavaScript
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.
handler.isExtensible() - JavaScript
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.
handler.ownKeys() - JavaScript
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 '[[ownpropert...
Reflect.defineProperty() - JavaScript
examples using reflect.defineproperty() let obj = {} reflect.defineproperty(obj, 'x', {value: 7}) //
true obj.x // 7 checking if property definition has been successful with object.defineproperty, which returns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while defining a property.
Reflect.deleteProperty() - JavaScript
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 ...
RegExp.prototype.flags - JavaScript
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.
RegExp.prototype.source - JavaScript
new regexp().source; // "(?:)" new regexp('\n').source === '\n'; //
true, prior to es5 new regexp('\n').source === '\\n'; //
true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.source' in that specification.
RegExp.prototype.toString() - JavaScript
'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.
RegExp - JavaScript
let str = '#foo#' let regex = /foo/y regex.lastindex = 1 regex.test(str) //
true regex.lastindex = 5 regex.test(str) // false (lastindex is taken into account with sticky flag) regex.lastindex // 0 (reset after match failure) the difference between the sticky flag and the global flag with the sticky flag y, the next match has to happen at the lastindex position, while with the global flag g, the match can happen at the lastindex position or later: re = /\d/y; whi...
Set.prototype.clear() - JavaScript
examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); //
true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification.
String.prototype.codePointAt() - JavaScript
if (second >= 0xdc00 && second <= 0xdfff) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable':
true, 'writable':
true }); } else { string.prototype.codepointat = codepointat; } }()); } examples using codepointat() 'abc'.codepointat(1) // 66 '\ud800\udc00'.codepointat(0) // 65536 'xyz'.codepointat(42) // undefined looping with codepointat() for (let codepoint of '\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codepoint.codepointat(0).t...
String.prototype.concat() - JavaScript
let greetlist = ['hello', ' ', 'venkat', '!'] "".concat(...greetlist) // "hello venkat!" "".concat({}) // [object object] "".concat([]) // "" "".concat(null) // "null" "".concat(
true) // "
true" "".concat(4, 5) // "45" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.concat' in that specification.
String.fromCodePoint() - JavaScript
} if (codelen >= 0x3fff) { result += stringfromcharcode.apply(null, codeunits); codeunits.length = 0; } } return result + stringfromcharcode.apply(null, codeunits); }; try { // ie 8 only supports `object.defineproperty` on dom elements object.defineproperty(string, "fromcodepoint", { "value": fromcodepoint, "configurable":
true, "writable":
true }); } catch(e) { string.fromcodepoint = fromcodepoint; } }(string.fromcharcode)); examples using fromcodepoint() valid input: string.fromcodepoint(42); // "*" string.fromcodepoint(65, 90); // "az" string.fromcodepoint(0x404); // "\u0404" == "Є" string.fromcodepoint(0x2f804); // "\ud87e\udc04" string.fromcodepoint(194564); // "\ud87e\udc04"...
String.prototype.toLocaleLowerCase() - JavaScript
examples using tolocalelowercase() 'alphabet'.tolocalelowercase(); // 'alphabet' '\u0130'.tolocalelowercase('tr') === 'i'; //
true '\u0130'.tolocalelowercase('en-us') === 'i'; // false let locales = ['tr', 'tr', 'tr-tr', 'tr-u-co-search', 'tr-x-turkish']; '\u0130'.tolocalelowercase(locales) === 'i'; //
true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolocalelowercase' in that specification.
String.prototype.toUpperCase() - JavaScript
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'.
String.prototype.trimStart() - JavaScript
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...
Symbol.prototype[@@toPrimitive] - JavaScript
examples using @@toprimitive const sym = symbol("example"); sym === sym[symbol.toprimitive](); //
true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.@@toprimitive' in that specification.
Symbol.for() - JavaScript
examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbol, but not locally symbol.for('bar') === symbol.for('bar'); //
true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: symbol.for('mdn.foo'); symbol.for('mdn.bar'); specifications specification ecmascri...
Symbol.hasInstance - JavaScript
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.isConcatSpreadable - JavaScript
symbol.isconcatspreadable needs to be set to
true in order to get a flattened array: let x = [1, 2, 3] let fakearray = { [symbol.isconcatspreadable]:
true, length: 2, 0: 'hello', 1: 'world' } x.concat(fakearray) // [1, 2, 3, "hello", "world"] note: the length property is used to control the number of object properties to be added.
Symbol.match - JavaScript
var re = /foo/; re[symbol.match] = false; '/foo/'.startswith(re); //
true '/baz/'.endswith(re); // false specifications specification ecmascript (ecma-262)the definition of 'symbol.match' in that specification.
Symbol.species - JavaScript
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.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.
Symbol.toStringTag - JavaScript
ributes of symbol.tostringtag writable no enumerable no configurable no examples default tags object.prototype.tostring.call('foo'); // "[object string]" object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(
true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[object null]" // ...
Symbol.prototype.valueOf() - JavaScript
examples using valueof const sym = symbol("example"); sym === sym.valueof(); //
true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.valueof' in that specification.
SyntaxError() constructor - JavaScript
ry { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e instanceof syntaxerror); //
true console.error(e.message); // hello console.error(e.name); // syntaxerror console.error(e.filename); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } specifications specification ecmascri...
SyntaxError - JavaScript
ry { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e instanceof syntaxerror); //
true console.error(e.message); // hello console.error(e.name); // syntaxerror console.error(e.filename); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } specifications specification ecmascri...
TypedArray.prototype.find() - JavaScript
description the find method executes the callback function once for each element present in the typed array until it finds one where callback returns a
true value.
WeakMap() constructor - JavaScript
wm1.get(o2); // "azerty" wm2.get(o2); // undefined, because there is no key for o2 on wm2 wm2.get(o3); // undefined, because that is the set value wm1.has(o2); //
true wm2.has(o2); // false wm2.has(o3); //
true (even if the value itself is 'undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); //
true wm1.delete(o1); wm1.has(o1); // false specifications specification ecmascript (ecma-262)the definition of 'weakmap constructor' in that specification.
WeakMap.prototype.clear() - JavaScript
syntax wm.clear(); examples using the clear method var wm = new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); //
true wm.has(window); //
true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard.
WeakMap - JavaScript
wm1.get(o2); // "azerty" wm2.get(o2); // undefined, because there is no key for o2 on wm2 wm2.get(o3); // undefined, because that is the set value wm1.has(o2); //
true wm2.has(o2); // false wm2.has(o3); //
true (even if the value itself is 'undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); //
true wm1.delete(o1); wm1.has(o1); // false implementing a weakmap-like class with a .clear() method class clearableweakmap { constructor(init) { this._wm = new weakmap(init); } clear() { this._wm = new weakmap(); } delete(k) { return t...
WeakSet() constructor - JavaScript
examples using the weakset object var ws = new weakset(); var foo = {}; var bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); //
true ws.has(bar); //
true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); //
true, bar is retained note that foo !== bar.
WeakSet.prototype.add() - JavaScript
examples using add var ws = new weakset(); ws.add(window); // add the window object to the weakset ws.has(window); //
true // weakset only takes objects as arguments ws.add(1); // results in "typeerror: invalid value used in weak set" in chrome // and "typeerror: 1 is not a non-null object" in firefox specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.add' in that specification.
WeakSet.prototype.clear() - JavaScript
syntax ws.clear(); examples using the clear method var ws = new weakset(); ws.add(window); ws.has(window); //
true ws.clear(); ws.has(window); // false specifications not part of any standard.
WeakSet - JavaScript
examples using the weakset object const ws = new weakset(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); //
true ws.has(bar); //
true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); //
true, bar is retained note that foo !== bar.
WebAssembly.CompileError() constructor - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', '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.CompileError - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', '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.Global() constructor - JavaScript
got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:
true}, 0); webassembly.instantiatestreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43)...
WebAssembly.Global - JavaScript
got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:
true}, 0); webassembly.instantiatestreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43)...
WebAssembly.LinkError() constructor - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } 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.LinkError - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } 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.Memory - JavaScript
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.RuntimeError() constructor - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', '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.RuntimeError - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', '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
webassembly.validate() validates a given typed array of webassembly binary code, returning whether the bytes are valid webassembly code (
true) or not (false).
eval() - JavaScript
var str = 'if ( a ) { 1 + 1; } else { 1 + 2; }'; var a =
true; var b = eval(str); // returns 2 console.log('b is : ' + b); a = false; b = eval(str); // returns 3 console.log('b is : ' + b); eval as a string defining function requires "(" and ")" as prefix and suffix var fctstr1 = 'function a() {}' var fctstr2 = '(function a() {})' var fct1 = eval(fctstr1) // return undefined var fct2 = eval(fctstr2) // return a function specifications s...
null - JavaScript
typeof null // "object" (not "null" for legacy reasons) typeof undefined // "undefined" null === undefined // false null == undefined //
true null === null //
true null == null //
true !null //
true isnan(1 + null) // false isnan(1 + undefined) //
true specifications specification ecmascript (ecma-262)the definition of 'null value' in that specification.
Addition (+) - JavaScript
syntax operator: x + y examples numeric addition // number + number -> addition 1 + 2 // 3 // boolean + number -> addition
true + 1 // 2 // boolean + boolean -> addition false + false // 0 string concatenation // string + string -> concatenation 'foo' + 'bar' // "foobar" // number + string -> concatenation 5 + 'foo' // "5foo" // string + boolean -> concatenation 'foo' + false // "foofalse" specifications specification ecmascript (ecma-262)the definition of 'addition operator' in that specificatio...
Addition assignment (+=) - JavaScript
syntax operator: x += y meaning: x = x + y examples using addition assignment // assuming the following variables // foo = 'foo' // bar = 5 // baz =
true // number + number -> addition bar += 2 // 7 // boolean + number -> addition baz += 1 // 2 // boolean + boolean -> addition baz += false // 1 // number + string -> concatenation bar += 'foo' // "5foo" // string + boolean -> concatenation foo += false // "foofalse" // string + string -> concatenation foo += 'bar' // "foobar" specifications specification ecmascript (ecma-2...
Operator precedence - JavaScript
(b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined` a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined` examples 3 > 2 && 2 > 1 // returns
true 3 > 2 > 1 // returns false because 3 > 2 is
true, then
true is converted to 1 // in inequality operators, therefore
true > 1 becomes 1 > 1, which // is false.
Spread syntax (...) - JavaScript
(the same is
true with object.assign() and spread syntax.) const a = [[1], [2], [3]]; const b = [...a]; b.shift().shift(); // 1 // oh no!
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.
Function expression - JavaScript
var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); //
true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) examples creating an unnamed function the following example defines an unnamed function and assigns it to x.
super - JavaScript
class x { constructor() { object.defineproperty(this, 'prop', { configurable:
true, writable: false, value: 1 }); } } class y extends x { constructor() { super(); } foo() { super.prop = 2; // cannot overwrite the value.
void operator - JavaScript
button.onclick = () => void dosomething(); this ensures the return value of dosomething changing from undefined to
true will not change the behavior of this code.
empty - JavaScript
if three is
true, nothing will happen, four does not matter, and also the launchrocket() function in the else case will not be executed.
block - JavaScript
the same is
true of const: const c = 1; { const c = 2; } console.log(c); // logs 1 and does not throw syntaxerror...
if...else - JavaScript
in general, it is a good practice to always use block statements, especially in code involving nested if statements: if (condition) { statements1 } else { statements2 } do not confuse the primitive boolean values
true and false with truthiness or falsiness of the boolean object.
label - JavaScript
var allpass =
true; var i, j; top: for (i = 0; items.length; i++) for (j = 0; j < tests.length; i++) if (!tests[j].pass(items[i])) { allpass = false; break top; } using a labeled block with break you can use labels within simple blocks, but only break statements can make use of non-loop labels.
return - JavaScript
the following return statements all break the function execution: return; return
true; return false; return x; return x + y / 3; automatic semicolon insertion the return statement is affected by automatic semicolon insertion (asi).
throw - JavaScript
each of the following throws an exception: throw 'error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw
true; // generates an exception with the value
true throw new error('required'); // generates an error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line terminator between the throw keyword and the expression is allowed.
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.
Trailing commas - JavaScript
nction f(...p,) {} // syntaxerror: parameter after rest parameter (...p,) => {} // syntaxerror: expected closing parenthesis, got ',' trailing commas in destructuring a trailing comma is also allowed on the left-hand side when using destructuring assignment: // array destructuring with trailing comma [a, b,] = [1, 2]; // object destructuring with trailing comma var o = { p: 42, q:
true, }; var {p, q,} = o; again, when using a rest element, a syntaxerror will be thrown: var [a, ...b,] = [1, 2, 3]; // syntaxerror: rest element may not have a trailing comma trailing commas in json trailing commas in objects were only introduced in ecmascript 5.
JavaScript reference - JavaScript
if
true : iffalse) assignment operators = *= /= %= += -= <<= >>= >>>= &= ^= |= [a, b] = [1, 2] {a, b} = {a:1, b:2} functions this chapter documents how to work with javascript functions to develop your applications.
MathML attribute reference - MathML
symmetric <mo> if stretchy is
true, this attribute specifies whether the operator should be vertically symmetric around the imaginary math axis (centered fraction line).
Authoring MathML - MathML
the same is
true for mathml: for example ascii syntaxes as used in calculators or the more powerful latex language, very popular among the scientific community.
<msubsup> - MathML
examples sample rendering: rendering in your browser: ∫ 0 1 <math displaystyle="
true"> <msubsup> <mo> ∫<!--integral --> </mo> <mn> 0 </mn> <mn> 1 </mn> </msubsup> </math> specifications specification status comment mathml 3.0the definition of 'msubsup' in that specification.