Search completed in 0.88 seconds.
2381 results for "false":
Your results are loading. Please wait...
JS::FalseValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value false.
... syntax js::value js::falsevalue() description js::falsevalue creates a js::value that represents the javascript value false.
... see also mxr id search for js::falsevalue js::value js::booleanvalue js::truevalue ...
false - XPath
WebXPathFunctionsfalse
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the false function returns boolean false.
... syntax false() returns boolean false.
... notes this function is useful part of a comparison: <xsl:if test="boolean((1 &gt; 2) = false())"> the expression evaluates as true </xsl:if> defined xpath 1.0 4.3 gecko support supported.
Index - Web APIs
WebAPIIndex
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).
... 116 audiobuffersourcenode.loop api, audio, audiobuffersourcenode, loop, media, property, reference, web audio api, sound the loop property's default value is false.
...if the track is disabled by setting enabled to false, the track is muted and does not produce audio.
...And 91 more matches
jspage - Archive of obsolete content
var mootools={version:"1.2.4",build:"0d9113241a90b9cd5643b926795852a2026710d4"};var native=function(k){k=k||{};var a=k.name;var i=k.legacy;var b=k.protect; var c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterimplement||function(){};var d=f||i;h=h!==false;d.constructor=native;d.$family={name:"native"}; if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.tolowercase();d.prototype.$family={name:e};native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; }if(h){native.genericize(n,l,b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return ...
...!=undefined){return arguments[b];}}return null;}function $random(b,a){return math.floor(math.random()*(a-b+1)+b);}function $splat(b){var a=$type(b); return(a)?((a!="array"&&a!="arguments")?[b]:b):[];}var $time=date.now||function(){return +new date;};function $try(){for(var b=0,a=arguments.length;b<a; b++){try{return arguments[b]();}catch(c){}}return null;}function $type(a){if(a==undefined){return false;}if(a.$family){return(a.$family.name=="number"&&!isfinite(a))?false:a.$family.name; }if(a.nodename){switch(a.nodetype){case 1:return"element";case 3:return(/\s/).test(a.nodevalue)?"textnode":"whitespace";}}else{if(typeof a.length=="number"){if(a.callee){return"arguments"; }else{if(a.item){return"collection";}}}}return typeof a;}function $unlink(c){var b;switch($type(c)){case"object":b={};for(var ...
...d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var browser=$merge({engine:{name:"unknown",version:0},platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].tolowercase()},features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.queryselector)},plugins:{},engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getelementsbyclassname)?950:925)); },trident:function(){return(!window.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==nu...
...And 37 more matches
Index
otherwise, int_fits_in_jsval returns false.
... 42 js::falsevalue jsapi reference, reference, référence(2), spidermonkey js::falsevalue creates a js::value that represents the javascript value false.
... 81 js::truehandlevalue jsapi reference, reference, référence(2), spidermonkey js::truehandlevalue and js::falsehandlevalue are js::handlevalue constants that represent the javascript values true and false.
...And 36 more matches
MathML Torture Test
>i</mi> <mo>&leq;</mo> <mi>m</mi> </mrow> <mrow> <mn>0</mn> <mo>&lt;</mo> <mi>j</mi> <mo>&lt;</mo> <mi>n</mi> </mrow> </mfrac> </mrow> </munder> <mi>p</mi> <mo stretchy="false">(</mo> <mi>i</mi> <mo>,</mo> <mi>j</mi> <mo stretchy="false">)</mo> </mrow> </math> </td></tr> <tr> <td>11</td> <td><img src="https://udn.realityripple.com/samples/17/0564f346b7.png" width="27" height="18" alt="texbook, 16.2-16.3" /></td> <td> <math display="block"> <mrow> <msup> <mi>x</mi> ...
...msup> <mrow> <mo>&part;</mo> <msup> <mi>y</mi> <mn>2</mn> </msup> </mrow> </mfrac> <mo>)</mo> </mrow> <msup> <mrow> <mo minsize="150%">|</mo> <mi>&#x3c6; <!-- \varphi --></mi> <mo stretchy="false">(</mo> <mi>x</mi> <mo>+</mo> <mi mathvariant="normal">i</mi> <mi>y</mi> <mo stretchy="false">)</mo> <mo minsize="150%">|</mo> </mrow> <mn>2</mn> </msup> <mo>=</mo> <mn>0</mn> </mrow> </math> </td></tr> <tr> <td>15</td> <td><img src="h...
... <mn>2</mn> <mi>x</mi> </msup> </msup> </msup> </mrow> </math> </td></tr> <tr> <td>16</td> <td><img src="https://udn.realityripple.com/samples/4c/52718c0fdb.png" width="55" height="49" alt="texbook, 18.10-18.11" /></td> <td> <math display="block"> <mrow> <msubsup> <mo stretchy="false">&int;</mo> <mn>1</mn> <mi>x</mi> </msubsup> <mfrac> <mrow><mi>d</mi><mi>t</mi></mrow> <mi>t</mi> </mfrac> </mrow> </math> </td></tr> <tr> <td>17</td> <td><img src="https://udn.realityripple.com/samples/06/fee7889060.png" width="91" height="47" alt="texbook, 18.12-18.13" /></td> <td> ...
...And 30 more matches
JSAPI Cookbook
l representation, not numeric value bool isnull = v.isnull(); bool isboolean = v.isboolean(); bool isobject = v.isobject(); // note: not broken like typeof === "object" is :-) to set a value use a correspondingly named member mutator function, or assign the result of the correspondingly named standalone function: // javascript var v; v = 0; v = 0.5; v = somestring; v = null; v = undefined; v = false; /* jsapi */ js::rootedvalue v(cx); js::rootedstring somestring(cx, ...); v.setint32(0); // or: v = js::int32value(0); v.setdouble(0.5); // or: v = js::doublevalue(0.5); v.setstring(somestring); // or: v = js::stringvalue(somestring); v.setnull(); // or: v = js::nullvalue(); v.setundefined(); // or: v = js::undefinedvalue(); v.setboolean(false); // or: v ...
...= js::booleanvalue(false); finding the global object many of these recipes require finding the current global object first.
... */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) return false; to define many jsapi functions at once, use js_definefunctions.
...And 28 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 25 more matches
sslfnc.html
the factory setting for this option (which is the default, unless the application changes the default) is off (pr_false), which means that the application will not do simultaneous reads and writes.
... on pr_true turns option on; pr_false turns option off.
... note that calling ssl_enable to set ssl_v2_compatible_hello to pr_false implicitly also sets the ssl_enable_ssl2 option to pr_false for that ssl socket.
...And 18 more matches
Browser Feature Detection - Archive of obsolete content
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.createcdatasection() true false true document.createprocessinginstruction() true false true document.createattribute() true true true document.createentityreference()obsolete since gecko 7 (method present but only returns null: bug 9850) false false document.getelementsbytagname() true true true dom core level 2 support for properties/methods in ...
... document.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.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 properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 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.createattribute() true true true document.getelementsbytagname() true true true document.title true true ...
...And 17 more matches
EventTarget.addEventListener() - Web APIs
if not specified, usecapture defaults to false.
...if true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages).
... for example, if you want to check for the passive option: let passivesupported = false; try { const options = { get passive() { // this function will be called when the browser // attempts to access the passive property.
...And 17 more matches
JSAPI User Guide
on failure, a jsnative calls an error-reporting function, in this case js_reporterror, and returns false.
... if (!js_definefunctions(cx, global, myjs_global_functions)) return false; ...
...simply call js_reporterror, with printf-style arguments, and return false.
...And 15 more matches
nsISelectionController
this will also have the effect of collapsing the selection if the extend = pr_false the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection.
... void charactermove( in boolean forward, in boolean extend ); parameters forward forward or backward if pr_false.
... return value true if visible, false if not.
...And 15 more matches
IAccessibleTable
return value s_false if there is nothing to return, [out] value is null.
...s_false if there is nothing to return, [out] value is null.
... return value s_false if there is no header, [out] values are null and 0 respectively.
...And 14 more matches
JavaScript Daemons Management - Archive of obsolete content
-1 : 1; var bbreak = odmn.task.call(odmn.owner, odmn.index, odmn.length, odmn.backw) === false, bend = odmn.isatend(), binvert = odmn.reversals > 0; if (bend && !binvert || bbreak) { odmn.pause(); return false; } if (bend && binvert) { odmn.backw = !odmn.backw; odmn.reversals--; } return true; }; /* system not required daemon global object methods */ /** * daemon global object optional methods (shortcuts).
... **/ daemon.prototype.start = function (breverse) { var bbackw = boolean(breverse); if (this.backw === bbackw && (this.isatend() || !this.paused)) { return false; } this.backw = bbackw; this.paused = false; if (this.onstart) { this.onstart.call(this.owner, this.index, this.length, this.backw); } this.synchronize(); return true; }; daemon.prototype.stop = function () { this.pause(); if (this.onstop) { this.onstop.call(this.owner, this.index, this.length, this.backw); } delete this.index; delete this.backw; delet...
...-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.paused = true; return false; } if (bend && binvert) { odmn.backw = !odmn.backw; odmn.reversals--; } odmn.synchronize(); return true; }; /* system not required daemon.safe global object methods */ /** * daemon.safe global object optional m...
...And 12 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
if false, the default value, the popup will be hidden.
...if false, the default, the value will not be filled in until the user selects an item.
...if false, only the text that hasn't been entered yet will be filled in.
...And 12 more matches
Client-side form validation - Learn web development
if the control is not a candidate for constraint validation (willvalidate is false) or the element's value satisfies its constraints (is valid), this will return an empty string.
...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.
... toolong: returns true if the value is longer than the maximum length specified by the maxlength attribute, or false if it is shorter than or equal to the maximum.
...And 12 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 12 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
own-list { height: 66px; line-height: 2.5em; overflow: hidden; } #delete-axis { margin: 0 38px 0 0; float: right !important; } /* tool controls */ #tool-section .property .name { width: 150px; } #canvas-bg { width: 16px; height: 16px; margin: 5px; background: url("images/toggle-background.png") center right no-repeat; } #canvas-bg:hover { cursor: pointer; } #canvas-bg[data-alpha='false'] { background-position: center left; } #canvas-bg[data-alpha='true'] { background-position: center right; } /* order gradients */ #order { margin-left: 24px; } #gradient-axes { width: 100%; height: 30px; padding: 0 0 0 15px; display: table; position: relative; } #gradient-axes .axis { width: 50px; height: 20px; margin: 5px 0; background-color: #ddd; text-align: center; float: ...
...' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { return (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue) === false) return; this.r = red | 0; this.g = green | 0; this.b = blue | 0; if (this.isvalidrgbvalue(alpha) === true) this.a = alpha | 0; }; color.
...prototype.setbyname = function setbyname(name, value) { if (name === 'r' || name === 'g' || name === 'b') { if(this.isvalidrgbvalue(value) === false) return; this[name] = value; this.updatehsx(); } }; color.prototype.sethsv = function sethsv(hue, saturation, value) { this.hue = hue; this.saturation = saturation; this.value = value; this.hsvtorgb(); }; color.prototype.sethsl = function sethsl(hue, saturation, lightness) { this.hue = hue; this.saturation = saturation; this.lightness = lightness; this.hsltorgb(); }; color.prototype.sethue = function sethue(value) { if (typeof(value) !== 'number' || isnan(value) === true || value < 0 || value > 359) return; this.hue = value; this.updatergb(); }; color.prototype.setsaturation = function setsa...
...And 12 more matches
source-editor.jsm
r acolumn, [optional] number aalign); void setselection(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.
...set it to false to allow editing.
...And 11 more matches
Bytecode Descriptions
false, true stack: ⇒ true/false push a boolean constant.
...otherwise push false.
...implements: propertydefinitionevaluation for methods, steps 3 and 4, when enumerable is false.
...And 11 more matches
nsITreeView
to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false when the orientation is not drop_on.
... return value true if a drop is allowed at the current location; otherwise false.
...to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false from candropbeforeafter().
...And 11 more matches
Border-image generator - CSS: Cascading Style Sheets
40px !important; } #unit-settings .close { width: 16px; height: 16px; background: url('https://mdn.mozillademos.org/files/6019/close.png') no-repeat center center; background-size: 75%; position: absolute; top: 4px; right: 4px; opacity: 0.5; } #unit-settings .close:hover { cursor: pointer; opacity: 1; } #unit-settings[data-active='true'] { opacity: 1; } #unit-settings[data-active='false'] { opacity: 0; top: -100px !important; } /* * css output code */ #output { padding: 10px; border: 2px dashed #888 !important; box-shadow: none !important; border-radius: 3px; overflow: hidden; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; } @media (min-width: 880px) { #output { width: 63.33% !important; } } @media (max-width: ...
...etvalue = function setvalue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; value = parsefloat(value.tofixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setattribute('data-value', value); slider.setinputvalue(); if (send_notify === false) return; notify.call(slider); }; var setmax = function setmax(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.max = value; setvalue(topic, slider.value); }; var setmin = function setmin(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.min = value; setvalue(topic, slider.value); }; var...
...l) option.setattribute('data-value', uval); list.appendchild(node.firstelementchild); uval++; } node.appendchild(select); node.appendchild(list); select.onclick = this.toggle.bind(this); list.onclick = this.updatevalue.bind(this); document.addeventlistener('click', clickout); this.state = 0; this.time = 0; this.dropmenu = list; this.select = select; this.toggle(false); this.value = {}; this.topic = topic; if (label) select.textcontent = label; else this.setnodevalue(list.children[selected]); dropdowns[topic] = this; }; dropdown.prototype.toggle = function toggle(state) { if (typeof(state) === 'boolean') this.state = state === false ?
...And 11 more matches
Box-shadow generator - CSS: Cascading Style Sheets
true : false; this.topic = topic; this.node = node; var pointer = document.createelement('div'); pointer.classname = 'ui-slider-pointer'; node.appendchild(pointer); this.pointer = pointer; setmousetracking(node, updateslider.bind(this)); sliders[topic] = this; setvalue(topic, this.value); } var setbuttoncomponent = function setbuttoncomponent(node) { var type = node.getattribute('dat...
...var rgb = "(" + this.r + ", " + this.g + ", " + this.b; var a = ''; var v = ''; if (this.a !== 1) { a = 'a'; v = ', ' + this.a; } var value = "rgb" + a + rgb + v + ")"; return value; } color.prototype.getcolor = function getcolor() { if (this.a | 0 === 1) return this.gethexa(); return this.getrgba(); } /** * shadow object */ function shadow() { this.inset = false; this.posx = 5; this.posy = -5; this.blur = 5; this.spread = 0; this.color = new color(); var hue = (math.random() * 360) | 0; var saturation = (math.random() * 75) | 0; var value = (math.random() * 50 + 50) | 0; this.color.sethsv(hue, saturation, value, 1); } shadow.prototype.computecss = function computecss() { var value = ""; if (this.inset === true) val...
...false : true; } shadow.prototype.copy = function copy(obj) { if(obj instanceof shadow !== true) { console.log("typeof instance not shadow"); return; } this.inset = obj.inset; this.posx = obj.posx; this.posy = obj.posy; this.blur = obj.blur; this.spread = obj.spread; this.color.copy(obj.color); } /** * color picker */ var colopicker = (function colopicker() { var colorpicker; v...
...And 11 more matches
Object.defineProperty() - JavaScript
defaults to false.
... defaults to false.
... defaults to false.
...And 11 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.childnod...
...|*| 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++) { ...
...|*| 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 getjxontree (oxmlparent) { var vresult = /* put here the default value for empty nodes!
...And 10 more matches
Tree View Details - Archive of obsolete content
var treeview = { childdata : { solids: ["silver", "gold", "lead"], liquids: ["mercury"], gases: ["helium", "nitrogen"] }, visibledata : [ ["solids", true, false], ["liquids", true, false], ["gases", true, false] ], }; the childdata structure holds an array of the children for each of the three parent nodes.
...obviously, the new inserted child items will have both values set to false.
...unt() { return this.visibledata.length; }, settree: function(treebox) { this.treebox = treebox; }, getcelltext: function(idx, column) { return this.visibledata[idx][0]; }, iscontainer: function(idx) { return this.visibledata[idx][1]; }, iscontaineropen: function(idx) { return this.visibledata[idx][2]; }, iscontainerempty: function(idx) { return false; }, isseparator: function(idx) { return false; }, issorted: function() { return false; }, iseditable: function(idx, column) { return false; }, } the rowcount function will return the length of the visibledata array.
...And 10 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
"-v"); exit(-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); validationf...
... 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 (!certfilena...
...mber> [-x <\"\">] \n"); exit(-1); } } /* * validate the options used for save cert to header command */ static void validatesavecerttoheadercommand(const char *progname, const char *dbdir, const char *nicknamestr, const char *headerfilename) { prbool validationfailed = pr_false; if (!nicknamestr) { pr_fprintf(pr_stderr, "%s -s -d %s -n : nick name is missing\n", progname, dbdir); validationfailed = pr_true; } if (!headerfilename) { pr_fprintf(pr_stderr, "%s -s -d %s -n %s -b : header file name is not found\n", progname, dbdir, nicknamestr); validationfailed = pr_true; } ...
...And 10 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 menu may be closed by a script by setting the open property to false, the reverse of what would be done to open the menu.
... somemenu.open = false; this command will close only a single level of menus, so any parent menus will need to be closed with a similar command if desired.
...And 9 more matches
sample2
- to enable ascii [optional]\n\n", "-a"); fprintf(stderr, "%-30s - to save certificate to header file as sig verification [optional]\n\n", "-v"); exit(-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,...
...dbdirpath> -s <subject> -r <csr> \n"); exit(-1); } } /* * validate the options used for add cert to db command */ static void validateaddcerttodbcommand(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...
...\nusage: %s %s \n\n", progname, "-a -d <dbdirpath> -n <nickname> -t <trust> -c <cert> -r <csr> -u <issuernickname> -m <serialnumber> [-x <\"\">] \n"); exit(-1); } } /* * validate the options used for save cert to header command */ static void validatesavecerttoheadercommand(const char *progname, const char *dbdir, const char *nicknamestr, const char *headerfilename) { prbool validationfailed = pr_false; if (!nicknamestr) { pr_fprintf(pr_stderr, "%s -s -d %s -n : nick name is missing\n", progname, dbdir); validationfailed = pr_true; } if (!headerfilename) { pr_fprintf(pr_stderr, "%s -s -d %s -n %s -b : header file name is not found\n", progname, dbdir, nicknamestr); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-s -d <dbdirpath> -n <nickn...
...And 9 more matches
Shell global objects
options is an optional object that may have these properties: isrunonce 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) catchtermin...
... unwrappedobjectshavesameshape(obj1, obj2) returns true iff obj1 and obj2 have the same shape, false otherwise.
...if present, options may have properties saying how the code should be compiled: 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 element if present with value v, convert v to an object o and mark the source as being attached to the dom element o.
...And 9 more matches
IAccessibleTable2
return value s_false if there is nothing to return, [out] value is null.
...s_false if there is nothing to return, [out] value is null.
...isselected returns true if the specified column is selected completely and false otherwise.
...And 9 more matches
nsIFile
by default, this value is false on all non-unix systems.
...otherwise it returns false.
...otherwise it returns false.
...And 9 more matches
Equality comparisons and sameness - JavaScript
briefly: double equals (==) will perform a type conversion when comparing two things, and will handle nan, -0, and +0 specially to conform to ieee 754 (so nan != nan, and -0 == +0); triple equals (===) will do the same comparison as double equals (including the special handling for nan, -0, and +0) but without type conversion; if the types differ, false is returned.
...for any non-primitive objects x and y which have the same structure but are distinct objects themselves, all of the above forms will evaluate to false.
... 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.
...And 9 more matches
Control flow and error handling - JavaScript
use the optional else clause to execute a statement if the condition is false.
... 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.
... (see boolean for an explanation of what evaluates to true and false.) if condition evaluates to true, statement_1 is executed.
...And 9 more matches
Expressions and operators - JavaScript
logical operators operator usage description logical and (&&) expr1 && expr2 returns expr1 if it can be converted to false; otherwise, returns expr2.
... thus, when used with boolean values, && returns true if both operands are true; otherwise, returns false.
...thus, when used with boolean values, || returns true if either operand is true; if both are false, returns false.
...And 9 more matches
Interacting with page scripts - Archive of obsolete content
in content scripts available to page scripts: // content-script.js unsafewindow.contentscriptobject = {"greeting" : "hello from add-on"}; // page-script.js var button = document.getelementbyid("show-content-script-var"); button.addeventlistener("click", function() { // access object defined by content script console.log(window.contentscriptobject.greeting); // "hello from add-on" }, false); after firefox 30, you can still do this for primitive values, but can no longer do it for objects.
...and the other listener displays a property of the assigned object: <html> <head> </head> <body> <input id="works" type="button" value="i will work"/> <input id="fails" type="button" value="i will not work"/> <script> var works = document.getelementbyid("works"); works.addeventlistener("click", function() { alert(clonedcontentscriptobject.greeting); }, false); var fails = document.getelementbyid("fails"); fails.addeventlistener("click", function() { alert(assignedcontentscriptobject.greeting); }, false); </script> </body> </html> if you run the example, clicking "i will work" displays the value of "greeting" in an alert.
...greetme"}); finally, the "page.html" file adds a button and a page script that calls the exported function when the user pushes the button: <html> <head> </head> <body> <input id="test" type="button" value="click me"/> <script> var test = document.getelementbyid("test"); test.addeventlistener("click", function() { alert(window.greetme("page script")); }, false); </script> </body> </html> exportfunction() works by structured cloning the arguments and return value of the function from one scope to the other.
...And 8 more matches
Tabbed browser - Archive of obsolete content
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.
... function openandreuseonetabperurl(url) { var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var browserenumerator = wm.getenumerator("navigator:browser"); // check each browser instance for our url var found = false; while (!found && browserenumerator.hasmoreelements()) { var browserwin = browserenumerator.getnext(); var tabbrowser = browserwin.gbrowser; // check each tab of this browser instance var numtabs = tabbrowser.browsers.length; for (var index = 0; index < numtabs; index++) { var currentbrowser = tabbrowser.getbrowseratindex(index); if (url == currentbrowser.curren...
...And 8 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.
...if canhandle is false, the exception is rethrown, the java handler catches it, and the doit method returns a java string: javascript error occurred see exception handling statements for complete information about javascript exceptions.
...for example: 237 becomes "237" boolean 0 and nan values are converted to false.
...And 8 more matches
OS.File for the main thread
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 "rename" operation, which is a "move".
...specify append: false to open the file in regular mode.
... when opening files for writing, they will be opened for appending unless you specify append: false in gecko 27 and later.
...And 8 more matches
nsIZipWriter
inqueue boolean true if operations are being performed in the background queue, or false if background operations are not in progress.
...if false, the operation is performed immediately.
...r_create_file: 0x08, pr_append: 0x10, pr_truncate: 0x20, pr_sync: 0x40, pr_excl: 0x80}; zw.open(xpi, pr.pr_wronly | pr.pr_create_file | pr.pr_truncate); //xpi file is created if not there, if it is there it is truncated/deleted var filetoaddtozip = fileutils.file('c:\\add this file.txt'); var saveinzipas = 'blah.txt'; zw.addentryfile(saveinzipas, ci.nsizipwriter.compression_none, filetoaddtozip, false); in the above example, the file ("add this file.txt") located at "c:\add this file.txt" will be added to the zip file "c:\myzipfile.zip", however in the zip file this file ("add this file.txt") will be named "blah.txt".
...And 8 more matches
WebIDL bindings
note: if your object can only be reflected into js by creating it, not by retrieving it from somewhere, you can skip steps 1 and 2 above and instead add 'wrappercache': false to your descriptor.
...otherinstance); [throws] myinterface dosomethingelse(optional long maybenumber); [throws] void dosomethingelse(myinterface otherinstance); void dotheother(any something); void doyetanotherthing(optional boolean actuallydoit = false); static void staticoperation(any arg); }; will require these method declarations: class myclass { void dosomething(int32_t anumber); double dosomething(myclass* aotherinstance); already_addrefed<myinterface> dosomethingelse(optional<int32_t> amaybenumber, errorresult& rv); void dosomethingelse(myclass& aotherinstance, errorresult& rv...
...if init() or tojsvalue() returns false, they will generally set a pending exception on the jscontext; reporting those is the responsibility of the caller.
...And 8 more matches
Loops and iteration - JavaScript
the statements for loops provided in javascript are: for statement do...while statement while statement labeled statement break statement continue statement for...in statement for...of statement for statement a for loop repeats until a specified condition evaluates to false.
...if the value of condition is false, the for loop terminates.
...ngth; i++) { if (selectobject.options[i].selected) { numberselected++; } } return numberselected; } let btn = document.getelementbyid('btn'); btn.addeventlistener('click', function() { alert('number of options selected: ' + howmany(document.selectform.musictypes)); }); </script> do...while statement the do...while statement repeats until a specified condition evaluates to false.
...And 8 more matches
Boolean - JavaScript
if the value is omitted or is 0, -0, null, false, nan, undefined, or the empty string (""), the object has an initial value of false.
... 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.
...And 8 more matches
Object.isFrozen() - JavaScript
object.isfrozen({}); // === false // an empty object which is not extensible // is vacuously frozen.
...var oneprop = { p: 42 }; object.isfrozen(oneprop); // === false // preventing extensions to the object still doesn't // make it frozen, because the property is still // configurable (and writable).
... object.preventextensions(oneprop); object.isfrozen(oneprop); // === false // ...but then deleting that property makes the object // vacuously frozen.
...And 8 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.
...: 'abc', designation: 'developer' } console.log(delete employee.name); // returns true console.log(delete employee.age); // returns true // when trying to delete a property that does // not exist, true is returned console.log(delete employee.salary); // returns true non-configurable properties when a property is marked as non-configurable, delete won't have any effect, and will return false.
...And 8 more matches
Miscellaneous - Archive of obsolete content
</div> <script type="text/javascript"> var elm = document.getelementbyid("scrollarea"); elm.addeventlistener("dommousescroll", function scroll(event){ //event.detail is positive for a downward scroll, negative for an upward scroll alert("scrolling " + event.detail + " lines"); }, false); </script> if you do not receive a dommousescroll event while holding any of the modifier keys (ctrl,shift,alt,meta) you should check the mousewheel.withcontrolkey.action and related preferences.
...note that it returns the empty string (""), not false, when nothing is selected.
... 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).
...And 7 more matches
Visual typescript game engine - Game development
client config if you want web app without any networking then setup: appusenetwork: boolean = false; you want to use communication for multiplayer but you don't want to use server database account sessions.
... the setup this on false in main client config class.
... appuseaccountssystem: boolean = false; networking is disabled by default.
...And 7 more matches
Making decisions in your code — conditionals - Learn web development
the condition makes use of the comparison operators we discussed in the last module and returns true or false.
... another set of curly braces, inside which we have some more code — this can be any code we like, and it only runs if the condition is not true — or in other words, the condition is false.
...te that you don't have to include the else and the second curly brace block — the following is also perfectly legal code: if (condition) { code to run if condition is true } run some other code however, you need to be careful here — in this case, the second block of code is not controlled by the conditional statement, so it always runs, regardless of whether the condition returns true or false.
...And 7 more matches
IAccessibleText
when a method doesn't implement this method it must return s_false.
...s_false if there is nothing to return, [out] values are 0s and null respectively.
... return value s_false if the caret is not currently active on this object, that is the caret is located on some other object.
...And 7 more matches
Web Console remoting - Firefox Developer Tools
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.
... actor preferences to allow the web console to configure logging options while it is running, we have added the setpreferences packet: { "to": "conn0.console9", "type": "setpreferences", "preferences": { "networkmonitor.saverequestandresponsebodies": false } } reply: { "updated": [ "networkmonitor.saverequestandresponsebodies" ], "from": "conn0.console10" } for convenience you can use webconsoleclient.setpreferences(prefs, onresponse).
... in firefox 25 we added the getpreferences request packet: { "to": "conn0.console34", "type": "getpreferences", "preferences": [ "networkmonitor.saverequestandresponsebodies" ] } reply packet: { "preferences": { "networkmonitor.saverequestandresponsebodies": false }, "from": "conn0.console34" } you can also use the webconsoleclient.getpreferences(prefs, onresponse).
...And 7 more matches
ARIA: switch role - Accessibility
the two possible values are true and false.
...the switch role does not support the value mixed for the aria-checked attribute; assigning a value of mixed to a switch instead sets the value to 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 7 more matches
Color picker tool - CSS: Cascading Style Sheets
' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { return (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue) === false) return; this.r = red | 0; this.g = green | 0; this.b = blue | 0; if (this.isvalidrgbvalue(alpha) === true) this.a = alpha | 0; }; color.
...prototype.setbyname = function setbyname(name, value) { if (name === 'r' || name === 'g' || name === 'b') { if(this.isvalidrgbvalue(value) === false) return; this[name] = value; this.updatehsx(); } }; color.prototype.sethsv = function sethsv(hue, saturation, value) { this.hue = hue; this.saturation = saturation; this.value = value; this.hsvtorgb(); }; color.prototype.sethsl = function sethsl(hue, saturation, lightness) { this.hue = hue; this.saturation = saturation; this.lightness = lightness; this.hsltorgb(); }; color.prototype.sethue = function sethue(value) { if (typeof(value) !== 'number' || isnan(value) === true || value < 0 || value > 359) return; this.hue = value; this.updatergb(); }; color.prototype.setsaturation = function setsa...
...this.color); }; colorpicker.prototype.inputchangeblue = function inputchangeblue(e) { var value = parseint(e.target.value); this.color.setbyname('b', value); e.target.value = this.color.b; this.setcolor(this.color); }; colorpicker.prototype.inputchangealpha = function inputchangealpha(e) { var value = parsefloat(e.target.value); if (typeof value === 'number' && isnan(value) === false && value >= 0 && value <= 1) this.color.a = value.tofixed(2); e.target.value = this.color.a; this.updatealphapicker(); }; colorpicker.prototype.inputchangehexa = function inputchangehexa(e) { var value = e.target.value; this.color.sethexa(value); this.setcolor(this.color); }; /*************************************************************************/ // internal pub/...
...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.
...r 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.
...e(components.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 6 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
conditionistrue : conditionisfalse; for example, to retrieve an element, you would use: function getelement(aid){ return (document.getelementbyid) ?
...if the boolean is set to false, it will only catch bubbling events.
...internet explorer's event model only has the bubbling phase; therefore, setting the third parameter to false results in internet explorer-like behavior: <div id="mydiv">click me!</div> <script> function handleevent(aevent) { // if aevent is null, it is the internet explorer event model, // so get window.event.
...And 6 more matches
Desktop gamepad controls - Game development
next, we'll consider the gamepadbuttonpressedhandler() function: function gamepadbuttonpressedhandler(button) { var press = false; for(var i=0; i<buttonspressed.length; i++) { if(buttonspressed[i] == button) { press = true; } } return press; } the function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the buttonspressed array.
... if it is, then the function returns true; false otherwise.
...here's the gamepadapi object, which contains useful variables and functions: var gamepadapi = { active: false, controller: {}, connect: function(event) {}, disconnect: function(event) {}, update: function() {}, buttons: { layout: [], cache: [], status: [], pressed: function(button, state) {} } axes: { status: [] } }; the controller variable stores the information about the connected gamepad, and there's an active boolean variable we...
...And 6 more matches
Creating our first Vue component - Learn web development
<template> <div> <input type="checkbox" id="todo-item" checked="false" /> <label for="todo-item">my todo item</label> </div> </template> using todoitem inside our app this is all fine, but we haven’t added the component to our app yet, so there’s no way to test it and see if everything is working.
... first add a default field, with a value of false.
... this means that when no done prop is passed to a todoitem component, the done prop will will have a value of false (bear in mind that this is not required — we only need default on non-required props).
...And 6 more matches
JS::CompileOptions
returns false if it failed to duplicate owning properties.
...returns false if it failed to duplicate.
...returns false if it failed to duplicate.
...And 6 more matches
nsITextInputProcessor
createinstance(components.interfaces.nsitextinputprocessor); next, you need to get the rights to create composition or dispatch keyboard events with begininputtransaction() or begininputtransactionfortests(): if (!tip.begininputtransaction(window, callback)) { return; } if begininputtransaction() or begininputtransactionfortests() returns false, it means that another instance of nsitextinputprocessor has composition on the window or is dispatching an event.
...however, if the event is consumed by web content, it returns false.
... repeat: false, // optional.
...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.
... 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 6 more matches
ValidityState - Web APIs
patternmismatch read only a boolean that is true if the value does not match the specified pattern, and false if it does match.
... rangeoverflow read only a boolean that is true if the value is greater than the maximum specified by the max attribute, or false if it is less than or equal to the maximum.
... rangeunderflow read only a boolean that is true if the value is less than the minimum specified by the min attribute, or false if it is greater than or equal to the minimum.
...And 6 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 +...
...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.p...
...arts.length; nchild++) { 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, thi...
...And 6 more matches
<mo> - MathML
WebMathMLElementmo
allowed values are true or false.
... allowed values are true or false.
...allowed values are either true or false.
...And 6 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 5 more matches
panel - Archive of obsolete content
ArchiveMozillaXULpanel
if set to false, the rollup event is not consumed.
... ignorekeys type: boolean if false, the default value, the escape key may be used to close the panel.
... noautofocus type: boolean if false, the default value, the currently focused element will be unfocused whenever the popup is opened or closed.
...And 5 more matches
XForms Input Element - Archive of obsolete content
the default value is 'false'.
...if "false", or the incremental attribute is omitted on this element then the bound instance node will be updated when the control loses the focus.
... checkbox most often used when the form author only needs a simple 'true', 'false', '1', or '0' response from the user (xhtml/xul).
...And 5 more matches
Working with Svelte stores - Learn web development
add the following import statement below the existing ones: import { alert } from '../stores.js' update your addtodo() function like so: function addtodo(name) { todos = [...todos, { id: newtodoid, name, completed: false }] $alert = `todo '${name}' has been added` } update removetodo() like so: function removetodo(todo) { todos = todos.filter(t => t.id !== todo.id) todosstatus.focus() // give focus to status heading $alert = `todo '${todo.name}' has been deleted` } update the updatetodo() function to this: function updatetodo(todo) { const i = todos.findindex(t => t.id ==...
... 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 tim...
...eout </script> and update the alert.svelte markup section like so: {#if visible} <div on:click={() => visible = false}> <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 20 20"><path d="m12.432 0c1.34 0 2.01.912 2.01 1.957 0 1.305-1.164 2.512-2.679 2.512-1.269 0-2.009-.75-1.974-1.99c9.789 1.436 10.67 0 12.432 0zm8.309 20c-1.058 0-1.833-.652-1.093-3.524l1.214-5.092c.211-.814.246-1.141 0-1.141-.317 0-1.689.562-2.502 1.117l-.528-.88c2.572-2.186 5.531-3.467 6.801-3.467 1.057 0 1.233 1.273.705 3.23l-1.391 5.352c-.246.945-.141 1.271.106 1.271.317 0 1.357-.392 2.379-1.207l.6.814c12.098 19.02 9.365 20 8.309 20z"/></svg> <p>{ $alert }</p> </div> {/if} here we first create the prop ms with a default value of 3000 (milliseconds).
...And 5 more matches
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
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 navigat...
...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
IAccessible2
[propget] hresult attributes( [out] bstr attributes ); parameters attributes return value s_false returned if there is nothing to return, [out] value is null.
...[propget] hresult extendedrole( [out] bstr extendedrole ); parameters extendedrole return value s_false if there is nothing to return, [out] value is null.
... return value s_false if there are no states, [out] values are null and 0 respectively.
...And 5 more matches
Background Tasks API - Web APIs
window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); return settimeout(function() { handler({ didtimeout: false, timeremaining: function() { return math.max(0, 50.0 - (date.now() - starttime)); } }); }, 1); } if window.requestidlecallback is undefined, we create it here.
...the callback is passed an object which conforms to idledeadline, with didtimeout set to false and a timeremaining() method which is implemented to give the callback 50 milliseconds of time to begin with.
... let logfragment = null; let statusrefreshscheduled = false; finally, we set up a couple of variables for other items: logfragment will be used to store a documentfragment that's generated by our logging functions to create content to append to the log when the next animation frame is rendered.
...And 5 more matches
DirectoryEntrySync - Web APIs
create: true exclusive: false path doesn't exist and no other error occurs a file is created.
... create: false (exclusive is ignored) path exists the file is returned.
... create: false (exclusive is ignored) path doesn't exist an error is thrown.
...And 5 more matches
FileSystemDirectoryEntry.getDirectory() - Web APIs
the fileerror.code specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the directory doesn't exist.
...the default is false.
...the default is false.
...And 5 more matches
FileSystemDirectoryEntry.getFile() - Web APIs
the {domxref("fileerror.code")}} specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the file doesn't exist.
...the default is false.
...the default is false.
...And 5 more matches
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>" .
... if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_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>" .
... include/header.php: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest = new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { return; } oreq.abort(); closereq(); } function ajaxerror () { alert("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status; switch (nstatus) { case 200: vmsg = json.parse(this.responsetext); document.title = opagei...
...And 5 more matches
Navigator.onLine - Web APIs
the property returns a boolean value, with true meaning online and false meaning offline.
...for example, the property should return false when users click links soon after they lose internet connection.
...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 5 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.
...if false, only xr device changes to the view are permitted.
...if false, the polyfill is only used if the browser doesn't implement navigator.xr.
...And 5 more matches
ARIA: grid role - Accessibility
the default value is false.
...the default value is false.
...ewcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": ...
...And 5 more matches
ARIA: button role - Accessibility
<div id="savechanges" tabindex="0" role="button" aria-pressed="false">save</div> the above example creates a simple button which is first in the focus order, though <button> or <input> with type="button" should be used for buttons: <button id="savechanges">save</button> note: if using role="button" instead of the semantic <button> or <input type="button"> elements, you will need to make the element focusable and have to define event handlers for click and keydown events, including the enter and space key...
...the aria-pressed attribute values of true or false identify a button as a toggle button.
...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 5 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 5 more matches
isNaN() - JavaScript
return value true if the given value is nan; otherwise, false.
... description the necessity of an isnan function unlike all other possible values in javascript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is nan or not, because both nan == nan and nan === nan evaluate to false.
...thus for non-numbers that when coerced to numeric type result in a valid non-nan numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." the confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as ieee-754 floating-point values.
...And 5 more matches
Communicating With Other Scripts - Archive of obsolete content
finally, "listen.html" uses window.addeventlistener() to listen for messages from the content script: <!doctype html> <html> <head></head> <body> <script> window.addeventlistener('message', function(event) { window.alert(event.data); // message from content script }, false); </script> </body> </html> messaging from page script to content script sending messages from the page script to the content script is just the same, but in reverse.
... "http://my-domain.org/"); } </script> <button onclick="sendmessage()">send message</button> </body> </html> finally, the content script "listen.js" uses window.addeventlistener() to listen for messages from the page script: // listen.js window.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using postmessage() before firefox 31 if your add-on is running in a version of firefox before firefox 31, then your content script can't access the postmessage() or addeventlistener() apis using window, but must access them using document.defaultview instead.
... so the content scripts in the above examples need to be rewritten like this: // content-script.js document.defaultview.postmessage("message from content script", "http://my-domain.org/"); // content-script.js document.defaultview.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using custom dom events as an alternative to using postmessage() you can use custom dom events to communicate between page scripts and content scripts.
...And 4 more matches
panel - Archive of obsolete content
n", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onchange: handlechange }); var mypanel = sdkpanels.panel({ contenturl: self.data.url("panel.html"), onhide: handlehide }); function handlechange(state) { if (state.checked) { mypanel.show({ position: button }); } } function handlehide() { button.state('window', {checked: false}); } updating panel content you can update the panel's content by: sending a message to a content script that updates the dom in the same document.
... var myscript = "window.addeventlistener('click', function(event) {" + " var t = event.target;" + " if (t.nodename == 'a')" + " self.port.emit('click-link', t.tostring());" + "}, false);" var mypanel = require("sdk/panel").panel({ contenturl: "http://www.bbc.co.uk/mobile/index.html", contentscript: myscript }); mypanel.port.on("click-link", function(url) { console.log(url); }); mypanel.show(); this example uses contentscript to supply the script as a string.
... text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; } }, false); // listen for the "show" event being sent from the // main add-on code.
...And 4 more matches
platform/xpcom - Archive of obsolete content
getservice(ci.nsiobserverservice); var starobserver = class({ extends: unknown, interfaces: [ 'nsiobserver' ], topic: '*', register: function register() { observerservice.addobserver(this, this.topic, false); }, unregister: function() { observerservice.removeobserver(this, this.topic); }, observe: function observe(subject, topic, data) { console.log('star observer:', subject, topic, data); } }); var starobserver = starobserver(); starobserver.register(); implementing xpcom factories the xpcom module exports a class called factory which implements the nsifactory interface.
... you can override this behavior using the register and unregister options to the factory or service constructor: var xpcom = require('sdk/platform/xpcom'); var factory = xpcom.factory({ contract: contractid, component: helloworld, register: false, unregister: false, }); if you disable automatic registration in this way, you can use the register() function to register factories and services: xpcom.register(factory); you can use the corresponding unregister() function to unregister them, whether or not you have disabled automatic unregistration: xpcom.unregister(factory); you can find out whether a factory or service has been registe...
...by including this option, set to false, the factory is not automatically registered and you must register it manually using the register() function.
...And 4 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
[root@calaz firefox]# cat firefox.cfg //put everything in a try/catch try { //privacy & security defaultpref("signon.remembersignons", false); //proxy and cache, as it is on nfs volume, we don't want cache lockpref("browser.cache.disk.capacity", 0); lockpref("network.cookie.cookiebehavior", 0); defaultpref("network.proxy.autoconfig_url", "http://wpad.int-evry.fr/wpad.dat"); defaultpref("network.proxy.type", 2); lockpref("network.protocol-handler.app.mailto", "/usr/bin/thunderbird"); //firefox3 urlclassifier3.sqlite iowait/cpu pb //h...
...ttp://forums.mozillazine.org/viewtopic.php?p=3381133#3381133 defaultpref("browser.safebrowsing.enabled", false); defaultpref("browser.safebrowsing.malware.enabled", false); // 1) env variables if(getenv("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"); // 2) define here (because if set after "3)" below it doesn't work !) processldapvalues which is eventually called by getldapattributes() just below, // check getldapattributes() code from $mozilla_home/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processldapvalues /* commented all this secti...
... [root@b008-02 /usr/lib/firefox-1.5.0.2] $cat firefox.cfg //put everything in a try/catch try { //privacy & security defaultpref("signon.remembersignons", false); // 1) env variables if(getenv("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"); /* 2) define here (because if set after "3)" below it doesn't work!) processldapvalues which is eventually calle...
...And 4 more matches
Download Manager preferences - Archive of obsolete content
default value is false.
... in other applications the default value is false.
... in firefox,thunderbird and seamonkey the default value is false.
...And 4 more matches
Using microformats - Archive of obsolete content
the default is false.
... debug specify true if debug mode is in use; otherwise, specify false.
... the default is false.
...And 4 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.
...the default value is false.
...if false, the textbox only allows entry of one line.
...And 4 more matches
tree - Archive of obsolete content
ArchiveMozillaXULtree
<treecell label="joe@somewhere.com"/> <treecell label="top secret plans"/> </treerow> </treeitem> <treeitem> <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...
...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.
... hidecolumnpicker type: boolean when set to false, a drop-down will appear in the upper right corner of the tree, which the user may use to show and hide columns.
...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
Drawing graphics - Learn web development
let's add an arc to our canvas — add the following to the bottom of your code: ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(150, 106, 50, degtorad(0), degtorad(360), false); ctx.fill(); arc() takes six parameters.
...the third is the circle's radius, the fourth and fifth are the start and end angles at which to draw the circle (so specifying 0 and 360 degrees gives us a full circle), and the sixth parameter defines whether the circle should be drawn counterclockwise (anticlockwise) or clockwise (false is clockwise).
...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.
...And 4 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
first, import usestate into the todo component like we did before with the app component, by updating the first import statement to this: import react, { usestate } from "react"; we'll now use this to set an isediting state, the default state of which should be false.
... add the following line just inside the top of your todo(props) { … } component definition: const [isediting, setediting] = usestate(false); next, we're going to rethink the <todo /> component — from now on, we want it to display one of two possible “templates", rather than the single template it's used so far: the "view" template, when we are just viewing a todo; this is what we’ve used in rest of the tutorial so far.
...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!
...And 4 more matches
Vue conditional rendering: editing existing todos - Learn web development
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).
...this method should take the new item label as an argument, emit an itemedited event to the parent component, and set isediting to false.
... add it now, below your existing methods: itemedited(newlabel) { this.$emit('item-edited', newlabel); this.isediting = false; } next, we'll need an editcancelled() method.
...And 4 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.
...this property becomes false when a download is started for the first time, or when a failed or canceled download is restarted.
...And 4 more matches
AsyncTestUtils extended framework
your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or return false when something asynchronous is going on.
...returning false tells the asynchronous driver that it should yield control up to the top-level.
... 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
Places Developer Guide
}, onendupdatebatch: function() { this._inbatch = false; }, onitemadded: function(id, folder, index) { }, onitemremoved: function(id, folder, index) { }, onitemchanged: function(id, property, isannotationproperty, value) { // isannotationproperty is a boolean value that is true of the changed property is an annotation.
... }, queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_error_no_interface; }, }; // register the observer with the bookmarks service var bmsvc = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); bmsvc.addobserver(observer, false); // un-register the observer when done.
... getservice(ci.nsinavhistoryservice); var oururi = uri("http://www.mozilla.com"); var visitdate = date.now() * 1000; // in microseconds var referreruri = null; // or a uri var isredirect = false; var visittype = history.transition_link; // the visit is from a link that was clicked var sessionid = 0; // can link the visit with a specific browsing session history.addvisit(oururi, visitdate, referreruri, visittype, isredirect, sessionid); // add a visit to a url, with a page title and visited time // via nsibrowserhistory.
...And 4 more matches
nsIDOMWindowUtils
true if it's open, otherwise false.
... paintingsuppressed boolean true if painting is currently suppressed for this window; otherwise false.
...if false, this method returns null for coordinates outside of the viewport.
...And 4 more matches
nsIMsgMessageService
false leaves it as just a copy.
...false leaves it as just a copy.
... ageneratedummyenvelope usually false.
...And 4 more matches
nsINavHistoryContainerResultNode
etails(in autf8string auristring, in prtime atime, in long long aitemid, in boolean arecursive); nsinavhistoryresultnode getchild(in unsigned long aindex); unsigned long getchildindex(in nsinavhistoryresultnode anode); attributes attribute type description childcount unsigned long the number of child nodes; accessing this throws an ns_error_not_available exception of containeropen is false.
... 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.
...this is false for bookmark folder nodes unless the setfolderreadonly() method has been called to specifically make the folder read-only.
...And 4 more matches
Setting HTTP request headers
// adds "x-hello: world" header to the request httpchannel.setrequestheader("x-hello", "world", false); in the example code above we have a variable named httpchannel which points to an object implementing nsihttpchannel.
...and for now, just ignore the third parameter, and just always make it false.
...is an example observer that adds a custom header "x-hello" to the channel passed in for http-on-modify-request notification: var {cc, ci} = require("chrome"); var httprequestobserver = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); httpchannel.setrequestheader("x-hello", "world", false); } } }; note: the above code was changed to reflect that in a firefox add-on one can not directly access components.interfaces und components.classes anymore but must use the require line introduced to the sample code above.
...And 4 more matches
Address Book examples
let card = collection.getcardfromproperty("jobtitle", "software engineer", false); if you are searching for a card with a particular email address, you can use the cardforemailaddress function that will match against multiple email addresses stored in one card.
... .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 of the mailing list.
...get the equivalent mailing list object that implements nsiabdirectory: let abmanager = components.classes["@mozilla.org/abmanager;1"] .getservice(components.interfaces.nsiabmanager); let maillistdirectory = abmanager.getdirectory(maillistcard.maillisturi); you can then adjust the items in the actual mailing list: maillistdirectory.addresslists.appendelement(newcard, false); then save the updated list to the database: maillistdirectory.editmaillisttodatabase(maillistcard); deleting a mailing list there are two ways to delete a mailing list.
...And 4 more matches
Using files from web applications - Web APIs
you need to use eventtarget.addeventlistener() to add the change event listener, like this: const inputelement = document.getelementbyid("input"); inputelement.addeventlistener("change", handlefiles, false); function handlefiles() { const filelist = this.files; /* now you can work with the file list */ } getting information about selected file(s) the filelist object provided by the dom lists all of the files selected by the user, each specified as a file object.
...prox = nbytes / 1024; napprox > 1; napprox /= 1024, nmultiple++) { soutput = napprox.tofixed(3) + " " + amultiples[nmultiple] + " (" + nbytes + " bytes)"; } // end of optional code document.getelementbyid("filenum").innerhtml = nfiles; document.getelementbyid("filesize").innerhtml = soutput; } document.getelementbyid("uploadinput").addeventlistener("change", updatesize, false); </script> </body> </html> using hidden file input elements using the click() method you can hide the admittedly ugly file <input> element and present your own interface for opening the file picker and displaying which file or files the user has selected.
...<input type="file" id="fileelem" multiple accept="image/*" style="display:none"> <button id="fileselect">select some files</button> the code that handles the click event can look like this: const fileselect = document.getelementbyid("fileselect"), fileelem = document.getelementbyid("fileelem"); fileselect.addeventlistener("click", function (e) { if (fileelem) { fileelem.click(); } }, false); you can style the new button for opening the file picker as you wish.
...And 4 more matches
FileSystemFlags - Web APIs
the default is false.
...the default is false.
... option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called.
...And 4 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
r="release">release</label> <input name="release" id="release" type="range" min="0" max="1" value="0.5" step="0.1" /> now we can create some variables over in javascript and have them change when the input values are updated: let attacktime = 0.2; const attackcontrol = document.queryselector('#attack'); attackcontrol.addeventlistener('input', function() { attacktime = number(this.value); }, false); let releasetime = 0.5; const releasecontrol = document.queryselector('#release'); releasecontrol.addeventlistener('input', function() { releasetime = number(this.value); }, false); the final playsweep() function now we can expand our playsweep() function.
... let pulsehz = 880; const hzcontrol = document.queryselector('#hz'); hzcontrol.addeventlistener('input', function() { pulsehz = number(this.value); }, false); let lfohz = 30; const lfocontrol = document.queryselector('#lfo'); lfocontrol.addeventlistener('input', function() { lfohz = number(this.value); }, false); the final playpulse() function here's the entire playpulse() function: let pulsetime = 1; function playpulse() { let osc = audioctx.createoscillator(); osc.type = 'sine'; osc.frequency.setvalueattime(pulsehz, audioctx.cur...
...uration</label> <input name="duration" id="duration" type="range" min="0" max="2" value="1" step="0.1" /> <label for="band">band</label> <input name="band" id="band" type="range" min="400" max="1200" value="1000" step="5" /> let noiseduration = 1; const durcontrol = document.queryselector('#duration'); durcontrol.addeventlistener('input', function() { noiseduration = number(this.value); }, false); let bandhz = 1000; const bandcontrol = document.queryselector('#band'); bandcontrol.addeventlistener('input', function() { bandhz = number(this.value); }, false); the final playnoise() function here's the entire playnoise() function: function playnoise() { const buffersize = audioctx.samplerate * noiseduration; // set the time of the note const buffer = audioctx.createbuffer(1, ...
...And 4 more matches
JavaScript data types and data structures - JavaScript
boolean type boolean represents a logical entity and can have two values: true and false.
... undefined [[writable]] boolean if false, the property's [[value]] cannot be changed.
... false [[enumerable]] boolean if true, the property will be enumerated in for...in loops.
...And 4 more matches
Array.prototype.every() - JavaScript
otherwise, false.
...if such an element is found, the every method immediately returns false.
...if iscallable(callbackfn) is false, throw a typeerror exception.
...And 4 more matches
Array.prototype.some() - JavaScript
otherwise, false.
...otherwise, some() returns false.
... caution: calling this method on an empty array returns false for any condition!
...And 4 more matches
Iteration protocols - JavaScript
an object is an iterator when it implements a next() method with the following semantics: property value next() a zero-argument function that returns an object with at least the following two properties: done (boolean) has the value false if the iterator was able to produce the next value in the sequence.
...if a non-object value gets returned (such as false or undefined), a typeerror ("iterator.next() returned a non-object value") will be thrown.
...g the iteration protocols a string is an example of a built-in iterable object: let somestring = 'hi'; console.log(typeof somestring[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 explicitl...
...And 4 more matches
Logical NOT (!) - JavaScript
when used with non-boolean values, it returns false if its single operand can be converted to true; otherwise, returns true.
... syntax !expr description returns false if its single operand can be converted to true; otherwise, returns true.
...if a value can be converted to false, the value is so-called falsy.
...And 4 more matches
Index - XPath
WebXPathIndex
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
Search Extension Tutorial (Draft) - Archive of obsolete content
var firstrun = false; // get the root user preference branch.
...var firstrun = false; // decide whether to select the search engine.
... var selectsearch = false; function startup(data, reason) { firstrun = reason == addon_install; // re-select the search engine if this is the first run // or we're being re-enabled.
...And 3 more matches
MMgc - Archive of obsolete content
// before sweeping we check for missing write barriers bool gc::incrementalvalidation = false; // check for missing write barriers at every alloc bool gc::incrementalvalidationpedantic = false; if you suspect you have missing write barriers, turn these switches on in a debug build.
...sometimes, this missing write barrier detection will turn up a false positive.
... if you can't find anything wrong with the code, it might just be a false positive.
...And 3 more matches
MenuItems - Archive of obsolete content
when the autocheck attribute is set to false, the checkbox state is not updated automatically, and you must write code to adjust the state yourself.
...<menuitem label="show toolbar" accesskey="t" type="checkbox" autocheck="false" oncommand="changetoolbarstate();"/> this version of the changetoolbarstate function changes the checked attribute itself.
... the autocheck attribute has been set to false on the menuitem so the checked attribute will not be updated automatically.
...And 3 more matches
Commands - Archive of obsolete content
if you return false, the command is not handled and command dispatcher will look for another controller.
... iscommandenabled (command) this method should return true if the command is enabled, or false if it is disabled.
...ler example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getelementbyid("thelist"); var listcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_delete"); }, iscommandenabled : function(cmd){ if (cmd == "cmd_delete") return (list.selecteditem != null); return false; }, docommand : function(cmd){ list.removeitemat(list.selectedindex); }, onevent : function(evt){ } }; list.controllers.appendcontroller(listcontroller); } </script> <listbox id="thelist"> <listitem label="ocean"/> <listitem label="desert"/> <listitem label="jungle"/> <listitem label="swamp"/> </listbox> </window> the controller (listcontroller) implements t...
...And 3 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.
... 141 falsy codingscripting, glossary, javascript a falsy (sometimes written falsey) value is a value that is considered false when encountered in a boolean context.
...And 3 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.
...it returns a true/false (boolean) result.
...And 3 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
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.
... add the following import statement below the others inside todos.svelte: import newtodo from './newtodo.svelte' and update the addtodo() function like so: function addtodo(name) { todos = [...todos, { id: newtodoid, name, completed: false }] } addtodo() now receives the name of the new todo directly, so we no longer need the newtodoname variable to give it its value.
...update the first part of the newtodo.svelte <script> section (the first four lines) to look like this: <script> import { createeventdispatcher } from 'svelte' const dispatch = createeventdispatcher() export let autofocus = false let name = '' let nameel // reference to the name input dom node if (autofocus) nameel.focus() now go back to the todos component, and pass the autofocus prop into the <newtodo> component call, like so: <!-- newtodo --> <newtodo autofocus on:addtodo={e => addtodo(e.detail)} /> if you try your app out now, you'll see that the page is now blank, and in your ...
...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
IPDL Tutorial
to initialize a union, simply assign a valid value to it, as follows: avariant = false; structs ipdl has built-in support for arbitrary collections of serializable data types.
... 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.
... message implementations should return false from a message implementation if the data is corrupted or otherwise malformed.
...And 3 more matches
CustomizableUI.jsm
parameters awidgetid the widget id or dom node to check return value true if the widget can be removed from its area, false otherwise.
... return value true if this is possible, false if it is not.
... return value true if the widget is 'special', false otherwise.
...And 3 more matches
PKCS11 Implement
nss's interpretation of the ckf_login_required and ckf_user_pin_initialized flags cfk_login_required cfk_user_pin_initialized nss assumes that: false false this is a general access device.
... 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.
...And 3 more matches
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
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
nsIDOMXULElement
allowevents boolean true if the element's allowevents attribute is the string "true", otherwise false.
... removes the attribute if you set it to false.
... collapsed boolean true if the element's collapsed attribute is the string "true", otherwise false.
...And 3 more matches
nsIHttpChannel
this should be set to false, for example, if the application knows that the corresponding document is likely to be very large.
... return value returns true if the server sent the equivalent of a "cache-control: no-cache" response header, otherwise false.
...if avalue is empty and amerge is false, the header will be cleared.
...And 3 more matches
nsINavHistoryQueryOptions
by default, this is false.
...defaults to false.
...defaults to false.
...And 3 more matches
nsISHistoryListener
the listener can prevent any action (except adding a new session history entry) from happening by returning false from the corresponding callback method.
... return value true to allow the go back operation to proceed or false to cancel it.
... return value true to allow the go forward operation to proceed or false to cancel it.
...And 3 more matches
DevTools API - Firefox Developer Tools
default: false inverticonforlighttheme boolean, optional.
...default: false key string, optional.
...default: false inmenu boolean, optional.
...And 3 more matches
EventTarget.removeEventListener() - Web APIs
if this parameter is absent, a default value of false is assumed.
... 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.
...And 3 more matches
KeyboardEvent() - Web APIs
"ctrlkey", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.ctrlkey.
... "shiftkey", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.shiftkey.
... "altkey", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.altkey.
...And 3 more matches
MutationObserverInit - Web APIs
the default value is false.
...the default value is false.
...the default value is true if either of attributefilter or attributeoldvalue is specified, otherwise the default value is false.
...And 3 more matches
RTCPeerConnection.createOffer() - Web APIs
specify false to keep the same credentials and therefore not restart ice.
... the default is false.
...if this value is false, the remote peer will not be offered to send audio data, even if the local side will be sending audio data.
...And 3 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
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...
... once the offer has been created, set and sent (or an error occurs), makingoffer gets set back to false.
... let ignoreoffer = false; signaler.onmessage = async ({ data: { description, candidate }}) => { try { if (description) { const offercollision = (description.type == "offer") && (makingoffer || pc.signalingstate != "stable"); ignoreoffer = !polite && offercollision; if (ignoreoffer) { return; } await pc.setremotedescription(description); if ...
...And 3 more matches
Using XMLHttpRequest - Web APIs
however, if the lengthcomputable field is false, the total length is not known and will be zero.
...er(ofield.name) + "=" + ffilter(ofield.value) ); } } processstatus(this); } return function (oformelement) { if (!oformelement.action) { return; } new submitrequest(oformelement); }; })(); </script> </head> <body> <h1>sending forms with pure ajax</h1> <h2>using the get method</h2> <form action="register.php" method="get" onsubmit="ajaxsubmit(this); return false;"> <fieldset> <legend>registration example</legend> <p> first name: <input type="text" name="firstname" /><br /> last name: <input type="text" name="lastname" /> </p> <p> <input type="submit" value="submit" /> </p> </fieldset> </form> <h2>using the post method</h2> <h3>enctype: application/x-www-form-urlencoded (default)</h3> <form action="register.php"...
... method="post" 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> <p> <input type="submit" value="submit" /> </p> </fieldset> </form> <h3>enctype: text/plain</h3> <form action="register.php" method="post" enctype="text/plain" onsubmit="ajaxsubmit(this); return false;"> <fieldset> <legend>registration example</legend> <p> your name: <input type="text" name="user" /> </p> <p> your message:<br /> <textarea name="message" cols="40" rows="8"></textarea> </p> <p> <input type="submit" value="submit" /> </p> </fieldset> </form> <h3>enctype: mult...
...And 3 more matches
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 ) { p...
...we assume that animation is not supported by setting animation to false.
... if the browser does not support non-prefixed animation and animation is still false, we iterate over all the possible prefixes, since all the major browsers are currently prefixing this property and changing its name to animationname instead.
...And 3 more matches
Border-radius generator - CSS: Cascading Style Sheets
rs[topic] = this; setvalue(topic, value); } var setvalue = function setvalue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setattribute('data-value', value); if (send_notify !== undefined && send_notify === false) { slider.input.value = value + slider.unit; return; } notify.call(slider); } var setmax = function setmax(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.max = value; setvalue(topic, slider.value); } var setmin = function setmin(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.min = ...
...; } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addeventlistener("load", function() { borderradius.init(); }); var borderradius = (function borderradius() { function getelembyid(id) { return document.getelementbyid(id); } /** * shadow dragging */ 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.adde...
...ventlistener('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); lastx = e.clientx; lasty = e.clienty; } var subscribe = function subscribe(callback) { subscribers.push(callback); } var unsubscribe = function unsubscribe(callback) { var index = subscribers.indexof(callback); subscribers.splice(index, 1); } var notify = function notify(deltax, deltay) { for (var i in subscribers) subscribers[i](deltax, deltay); } return { init : init, subscribe : subscribe, unsubscribe : unsubscr...
...And 3 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.
...(that is, -0 is considered to be equal to both 0 and +0), but false is not considered to be the same as 0.
... 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 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
Object.isSealed() - JavaScript
description returns true if the object is sealed, otherwise false.
...var empty = {}; object.issealed(empty); // === false // if you make an empty object non-extensible, // it is vacuously sealed.
...var hasprop = { fee: 'fie foe fum' }; object.preventextensions(hasprop); object.issealed(hasprop); // === false // but make them all non-configurable // and the object becomes sealed.
...And 3 more matches
Equality (==) - JavaScript
if one of the operands is boolean, convert the boolean operand to 1 if it is true and +0 if it is false.
...if either operand is nan, return false.
... boolean: return true only if operands are both true or both false.
...And 3 more matches
HTML to DOM - Archive of obsolete content
lstring){ var html = document.implementation.createdocument("http://www.w3.org/1999/xhtml", "html", null), body = document.createelementns("http://www.w3.org/1999/xhtml", "body"); html.documentelement.appendchild(body); body.appendchild(components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(ahtmlstring, false, null, body)); return body; } it works by creating a content-level (this is safer than chrome-level) <div> in the current page, then parsing the html fragment and attaching that fragment to the <div>.
...for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this...
...// 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.webnavigation.allowsubframes = false; // listen for load frame.addeventlistener("load", function (event) { // the document of the html in the dom var doc = event.originaltarget; // skip blank ...
...And 2 more matches
Preferences - Archive of obsolete content
to add a default value for a preference, you should add a line like this to your default preferences file: pref("extensions.extensionname.preferencename", false); how to install an extension's defaults files for mozilla suite (not firefox and thunderbird), copy them to (appdir)/defaults/pref in your install script.
... this.branch.addobserver("", this, false); }, unregister: function() { this.branch.removeobserver("", this); }, observe: function(asubject, atopic, adata) { // asubject is the nsiprefbranch we're observing (after appropriate qi) // adata is the name of the pref that's been changed (relative to asubject) switch (adata) { case "pref1": // extensions.myextension.pref1 was changed break; ...
... */ preflistener.prototype.register = function(trigger) { this._branch.addobserver('', this, false); if (trigger) { let that = this; this._branch.getchildlist('', {}).
...And 2 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
listing 7: check that file exists, delete it, and create it file.initwithpath('c:\\temp\\temp.txt'); if (file.exists()) file.remove(false); file.create(file.normal_file_type, 0666); the first parameter of the nsilocalfile.create() method gives the type of file to create.
... listing 13: reading the contents of a binary file file.initwithpath('c:\\temp\\temp.txt'); var filestream = components.classes['@mozilla.org/network/file-input-stream;1'] .createinstance(components.interfaces.nsifileinputstream); filestream.init(file, 1, 0, false); var binarystream = components.classes['@mozilla.org/binaryinputstream;1'] .createinstance(components.interfaces.nsibinaryinputstream); binarystream.setinputstream(filestream); var array = binarystream.readbytearray(filestream.available()); binarystream.close(); filestream.close(); alert(array.map( function(aitem) {return aitem.tostring(16); } ).join(' ').toupper...
... 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); binarystream.setoutputstream(filestream); binarystream.writebytearray(array , array.length); binarystream.close(); filestream.close(); text file i/o text files are read the same way streams are.
...And 2 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.
...we could also have left the rules in the original order and set the iscontainer on the first rule to false.
...note that leaving out the iscontainer attribute is not the same as setting it to either true or false.
...And 2 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
if set to false or omitted, the value must be selected from the list.
...if false, the default, autocomplete is enabled.
...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
menuitem - Archive of obsolete content
if this attribute is false, the checked state must be adjusted manually.
...a workaround is to set the autocheck attribute to false, then programmatically set the checked attribute when the user selects the item, and set it to false instead of removing the attribute (i.e.
... do menuitem.setattribute("checked", "false") instead of menuitem.removeattribute("checked")) when the user unchecks the menuitem, as a value of false will both correctly hide the checkmark and persist its hidden state.
...And 2 more matches
prefwindow - Archive of obsolete content
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.
... 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).
...returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527).
...And 2 more matches
Common causes of memory leaks in extensions - Extensions
consider the following example code that could be part of your browser.xul overlay: gbrowser.addeventlistener("domcontentloaded", function(evt) { var contentdoc = evt.originaltarget; var i = 0; // refresh the title once each second setinterval(function() { contentdoc.title = ++i; }, 1000); }, false); one would normally expect that the interval (or timer) would be destroyed as soon as the document unloads, in the same way that event listeners are automatically destroyed.
... // unload(function() window.removeeventlistener("leaky", leakref, false), window); // this is the right way to do it remove the listener.
..."private" : "normal"); } }; services.obs.addobserver(myobserver, "private-browsing", /* ownsweak */ false); the ownsweak = false parameter causes the observer service to use a strong reference to the observer object, which will cause it to hold onto the whole window.
...And 2 more matches
Paddle and keyboard controls - Game development
add these lines somewhere near the rest of your variables: var rightpressed = false; var leftpressed = false; the default value for both is false because at the beginning the control buttons are not pressed.
...add the following lines just above the setinterval() line at the bottom of your javascript: document.addeventlistener("keydown", keydownhandler, false); document.addeventlistener("keyup", keyuphandler, false); when the keydown event is fired on any of the keys on your keyboard (when they are pressed), the keydownhandler() function will be executed.
...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.
...And 2 more matches
TypeScript support in Svelte - Learn web development
now from todos.svelte, we will instantiate a todo component with a literal object as its parameter before the call to the moreactions component, like this: <hr /> <todo todo={ { name: 'a new task with no id!', completed: false } } /> <!-- moreactions --> <moreactions {todos} add the lang='ts' to the <script> tag of the todos.svelte component, so that it knows to use the type checking we have specified.
...math.max(...todos.map(t => t.id)) + 1 : 1 function addtodo(name: string) { todos = [...todos, { id: newtodoid, name, completed: false }] $alert = `todo '${name}' has been added` } function removetodo(todo: todotype) { todos = todos.filter(t => t.id !== todo.id) todosstatus.focus() // give focus to status heading $alert = `todo '${todo.name}' has been deleted` } function updatetodo(todo: todotype) { const i = todos.findindex(t => t.id === todo.id) if (todos[i].name !== todo.name) ...
...set its type to htmlelement like this: let nameel: htmlelement // reference to the name input dom node last for this file, we need to specify the correct type for our autofocus variable; update its definition like this: export let autofocus: boolean = false todo.svelte now the only warnings that npm run validate emits are triggered by calling the todo.svelte component; let's fix them.
...And 2 more matches
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.
...add this to the bottom of your <script> block inside src/components/todo.svelte: function addtodo() { todos.push({ id: 999, name: newtodoname, completed: false }) newtodoname = '' } note: for the moment we are just assigning the same id to every todo, but don't worry, we will fix that soon.
...And 2 more matches
Rendering a list of Vue components - Learn web development
export default { name: 'app', components: { todoitem }, data() { return { todoitems: [ { label: 'learn vue', done: false }, { label: 'create a vue project with the cli', done: true }, { label: 'have fun', done: true }, { label: 'create a to-do list', done: false } ] }; } }; now that we have a list of items, we can use the v-for directive to display them.
... your app.vue <script> element contents should now look like this: import todoitem from './components/todoitem.vue'; import uniqueid from 'lodash.uniqueid' export default { name: 'app', components: { todoitem }, data() { return { todoitems: [ { id: uniqueid('todo-'), label: 'learn vue', done: false }, { id: uniqueid('todo-'), label: 'create a vue project with the cli', done: true }, { id: uniqueid('todo-'), label: 'have fun', done: true }, { id: uniqueid('todo-'), label: 'create a to-do list', done: false } ] }; } }; now, add the v-for directive and key attribute to the <li> element in your app.vue template, like so: <ul> <li v-for="item in tod...
...in addition, we want their checked status to reflect their done properties, not always be set to done="false".
...And 2 more matches
Communicating with frame scripts
le below sends a message named "my-e10s-extension-message", with a data payload containing details and tag properties, and exposes the event.target object as a cpow: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }, { target : event.target }); }, false); to receive messages from content, a chrome script needs to add a message listener using the message manager's addmessagelistener() api.
...y-e10s-extension-message", listener); function listener(message) { console.log(message.name); console.log(message.sync); console.log(message.data); console.log(message.target); console.log(message.objects); } so combining this message listener with the message above will give console output somewhat like this, when the user clicks a <div>: "my-addon@me.org:my-e10s-extension-message" false object { details: "they clicked", tag: "div" } <xul:browser anonid="initialbrowser" ...
...value of sendsyncmessage() is an array of all the values returned from every listener, even if it only contains a single value: // frame script addeventlistener("click", function (event) { var results = sendsyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }); content.console.log(results[0]); // "value from chrome" }, false); like arguments, return values from sendsyncmessage() must be json-serializable, so chrome can't return functions.
...And 2 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.
...an example of the differences is that the "bold" command will generate <b> if the stylewithcss command is false and generate css style attribute if the stylewithcss command is true.
...And 2 more matches
Enc Dec MAC Output Public Key as CSR
citem_freeitem(data, pr_true); } return rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_false, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } return key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } return rv; } /* * macupdate */ secstatus macupdate(pk11context...
...asn1_get(cert_certificaterequesttemplate), &signeddata.data); if (rv) { rv = secfailure; goto cleanup; } rv = cert_verifysigneddatawithpublickeyinfo(&signeddata, &certreq->subjectpublickeyinfo, null /* wincx */); publickey = seckey_extractpublickey(&certreq->subjectpublickeyinfo); cleanup: if (reqder.data) { secitem_freeitem(&reqder, pr_false); } if (arena) { port_freearena(arena, pr_false); } return publickey; } /* * get the private key corresponding to public key */ seckeyprivatekey * getrsaprivatekey(pk11slotinfo *slot, secupwdata *pwdata, seckeypublickey *pubkey) { seckeyprivatekey *privkey = null; secitem *cka_id; if (slot...
...printf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ encoding = sec_asn1encodeitem(arena, null, cr, sec_asn1_get(cert_certificaterequesttemplate)); if (encoding == null) { pr_fprintf(pr_stderr, "der encoding of request failed...
...And 2 more matches
JSDeletePropertyOp
this callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false.
... if an error occurred, return false as per normal jsapi error practice.
... if no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return true.
...And 2 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.
... if obj has the specified property but it is permanent, then *succeeded receives false.
...And 2 more matches
Starting WebLock
* pr_false if there are no more elements in the enumerator.
...* false - the provider will be asked for this prop * each time it is requested.
...this boolean value will be used later to determine if we should be denying url requests: /* void lock (); */ ns_imethodimp weblock::lock() { mlocked = pr_true; return ns_ok; } /* void unlock (); */ ns_imethodimp weblock::unlock() { mlocked = pr_false; return ns_ok; } addsite for addsite, we add a new node to our linked list.
...And 2 more matches
Using XPCOM Components
ns_get_iid(nsicookiemanager), getter_addrefs(cookiemanager)); if (ns_failed(rv)) return -1; pruint32 len; deletedcookies->getlength(&len); for (int c=0; c<len; c++) cookiemanager->remove(deletedcookies[c].host, deletedcookies[c].name, deletedcookies[c].path, pr_false); xxx: in the original document, there were only the first three parameters to the |remove| call.
... i added |pr_false| as a fourth parameter because the interface seems to require it: http://lxr.mozilla.org/mozilla/source/netwerk/cookie/public/nsicookiemanager.idl#64 this problem also appears in the javascript version below, and i've added |false| as a fourth parameter there as well.
... managing cookies from javascript var cmgr = components.classes["@mozilla.org/cookiemanager;1"] .getservice(); cmgr = cmgr.queryinterface(components.interfaces.nsicookiemanager); function loadcookies() { // load cookies into a table var enumerator = cmgr.enumerator; var count = 0; var showpolicyfield = false; while (enumerator.hasmoreelements()) { var nextcookie = enumerator.getnext(); nextcookie = nextcookie.queryinterface(components.interfaces.nsicookie); /* ....
...And 2 more matches
Index
MozillaTechXPCOMIndex
24 components.issuccesscode xpcom, xpcom:language bindings, xpconnect determines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.
... 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) with the text "error: (error text)", so writes this text to console (s...
...when a method doesn't implement this method it must return s_false.
...And 2 more matches
Components.utils.cloneInto
if omitted the default value is false.
...if omitted the default value is false.
...s it a property of the content window global: // add-on script var addonscriptobject = {"greeting" : "hello from add-on"}; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow); scripts running in the page can now access the object: // page script button.addeventlistener("click", function() { console.log(window.addonscriptobject.greeting); // "hello from add-on" }, false); of course, you don't have to assign the clone to the window itself: you can assign it to some other object in the target scope: contentwindow.foo.addonscriptobject = cloneinto(addonscriptobject, contentwindow); you can also pass it into a function defined in the page script.
...And 2 more matches
Components.utils.exportFunction
boolean, defaulting to false.
...boolean, defaulting to false.
...{ user.name = "bill"; } exportfunction(changemyname, contentwindow, { defineas: "changemyname" }); // less-privileged scope: for example, a page script var user = {name: "jim"}; var test = document.getelementbyid("test"); test.addeventlistener("click", function() { console.log(user.name); // "jim" window.changemyname(user); console.log(user.name); // "bill" }, false); note that this is subject to the normal rules of xrays: for example, an expando property added to a dom node will not be visible in the original object.
...And 2 more matches
mozIStorageConnection
this will be false if the connection failed to open, or it has been closed.
...otherwise returns false.
...this is false by default.
...And 2 more matches
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.
... starvationdelay is only used when favorperfoverstarvation is pr_false.
...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
nsINavBookmarksService
if ownsweak is false, the bookmark service will keep an owning reference to the observer.
...the default for all folders is false.
... return value returns true if the folder is marked as read-only, otherwise returns false.
...And 2 more matches
nsIWebBrowserFind
default is false.
...default is false (search forward).
...default is false.
...And 2 more matches
Styling the Folder Pane
hasunreadmessages-true afolder.getnumunread(false) > 0 indicates that the folder (but not subfolders) has unread messages.
... issecure-{true, false} afolder.server.issecure indicates whether or not the connection to the server will be secure.
... newmessages-true afolder.hasnewmessages subfoldershaveunreadmessages-true afolder.getnumunread(true) > afolder.getnumunread(false) indicates whether or not subfolders have unread messages.
...And 2 more matches
Drawing and Event Handling - Plugins
an embedded plug-in can set the pluginprinted field in its printinfo parameter to false (the default).
... to specify that a plug-in is windowless, use npn_setvalue with nppvpluginwindowbool as the value of variable and false as the value of value.
... nperror result = npn_setvalue(instance, nppvpluginwindowbool, (void*)false); } invalidating the drawing area before it can repaint or refresh part of its drawing area, a windowless plug-in must first invalidate the area with either of these browser methods: npn_invalidaterect or npn_invalidateregion.
...And 2 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.
...setting this to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal javascript.
...it is initially false in a freshly created debugger instance.
...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.
...the method should return false as soon as it's known that it will no longer produce 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
Cache.delete() - Web APIs
WebAPICachedelete
if no cache entry is found, it resolves to false.
...it defaults to false.
... 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
Document.execCommand() - Web APIs
syntax document.execcommand(acommandname, ashowdefaultui, avalueargument) return value a boolean that is false if the command is unsupported or disabled.
...this requires a boolean true/false as the value argument.
...requires a boolean true/false as a value argument.
...And 2 more matches
Element.classList - Web APIs
WebAPIElementclassList
null : n} return nullcheck(this[i]); }; if (!domtokenlistproto.toggle || testclass.toggle("a",0)!==false) domtokenlistproto.toggle=function(val){ if (arguments.length > 1) return (this[arguments[1] ?
... "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 && (this.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; }; ...
...{value: [nextindex, that[nextindex++]], done: false} : {done: true}; }}; }; if (!domtokenlistproto.values) domtokenlistproto.values = function(){ var nextindex = 0, that = this; return {next: function() { return nextindex<that.length ?
...And 2 more matches
FileSystemFlags.create - Web APIs
option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called.
... false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided).
... 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.
...And 2 more matches
FileSystemFlags.exclusive - Web APIs
option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called.
... false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided).
... 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.
...And 2 more matches
HTMLInputElement - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
...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.
...does not affect the value of the checked attribute, and clicking the checkbox will set the value to false.
...And 2 more matches
HTMLTextAreaElement - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
...false if any conditions bar it from constraint validation, including its readonly or disabled property is true.
... checkvalidity() returns false if the element is a candidate for constraint validation, and it does not satisfy its constraints.
...And 2 more matches
Drag Operations - Web APIs
if this attribute were omitted or set to "false", the element would not be dragged, and instead the text would be selected.
...however, for these last two, the default value is true, so you would only use the draggable attribute with a value of false to disable dragging of these elements.
...you can do this either by returning false from attribute-defined event listeners, or by calling the event's preventdefault() method.
...And 2 more matches
Using IndexedDB - Web APIs
objectstore.createindex("name", "name", { unique: false }); // create an index to search customers by email.
...yrange.lowerbound("bill"); // match anything past "bill", but don't include "bill" var lowerboundopenkeyrange = idbkeyrange.lowerbound("bill", true); // match anything up to, but not including, "donna" var upperboundopenkeyrange = idbkeyrange.upperbound("donna", true); // match anything between "bill" and "donna", but not including "donna" var boundkeyrange = idbkeyrange.bound("bill", "donna", false, true); // to use one of the key ranges, pass it in as the first argument of opencursor()/openkeycursor() index.opencursor(boundkeyrange).onsuccess = function(event) { var cursor = event.target.result; if (cursor) { // do something with the matches.
... idbindex has also had new properties added to it to specify if it has a locale specified, and what it is: locale (returns the locale if any, or null if none is specified) and isautolocale (returns true if the index was created with an auto locale, meaning that the platform's default locale is used, false otherwise.) note: this feature is currently hidden behind a flag — to enable it and experiment, go to about:config and enable dom.indexeddb.experimental.
...And 2 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.
... note: you can implement standard "mute" functionality by setting enabled to false.
... note: you can implement standard "mute" functionality by setting enabled to false, and unmute the media by setting it back to true again.
...And 2 more matches
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.
... the speechrecognitionresult.isfinal property is false.) the default value for interimresults is false.
... syntax var myinterimresult = myspeechrecognition.interimresults; myspeechrecognition.interimresults = false; value a boolean representing the state of the current speechrecognition's interim results.
...And 2 more matches
WebGL constants - Web APIs
returns false if the shader was not compiled.
...returns true if it was, false otherwise.
...returns false if there were errors.
...And 2 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
let context = null; let playbutton = null; let volumecontrol = null; let oscnode1 = null; let oscnode2 = null; let oscnode3 = null; let constantnode = null; let gainnode1 = null; let gainnode2 = null; let gainnode3 = null; let playing = false; these variables are: context the audiocontext in which all the audio nodes live.
... function setup() { context = new (window.audiocontext || window.webkitaudiocontext)(); playbutton = document.queryselector("#playbutton"); volumecontrol = document.queryselector("#volumecontrol"); playbutton.addeventlistener("click", toggleplay, false); volumecontrol.addeventlistener("input", changevolume, false); gainnode1 = context.creategain(); gainnode1.gain.value = 0.5; gainnode2 = context.creategain(); gainnode3 = context.creategain(); gainnode2.gain.value = gainnode1.gain.value; gainnode3.gain.value = gainnode1.gain.value; volumecontrol.value = gainnode1.gain.value; constantnode = context.createconstantsource(); c...
...onstantnode.connect(gainnode2.gain); constantnode.connect(gainnode3.gain); constantnode.start(); gainnode1.connect(context.destination); gainnode2.connect(context.destination); gainnode3.connect(context.destination); } window.addeventlistener("load", setup, false); first, we get access to the window's audiocontext, stashing the reference in context.
...And 2 more matches
Using the Web Audio API - Web APIs
we have a play button that changes to a pause button when the track is playing: <button data-playing="false" role="switch" aria-checked="false"> <span>play/pause</span> </button> before we can play our track we need to connect our audio graph from the audio source/input node to the destination.
... // select our play button const 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.
... our htmlmediaelement fires an ended event once it's finished playing, so we can listen for that and run code accordingly: audioelement.addeventlistener('ended', () => { playbutton.dataset.playing = 'false'; }, false); modifying sound let's delve into some basic modification nodes, to change the sound that we have.
...And 2 more matches
Window.open() - Web APIs
WebAPIWindowopen
*/ }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="promotefirefoxwindowname" onclick="openffpromotionpopup(); return false;" title="this link will create a new window or will re-use an already opened one" >promote firefox adoption</a></p> the above code solves a few usability problems related to links opening secondary window.
... the purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link.
...pup(url, windowname) { if(windowobjectreference == null || windowobjectreference.closed) { windowobjectreference = window.open(url, windowname, "resizable,scrollbars,status"); } else { windowobjectreference.focus(); }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="promotefirefoxwindow" onclick="openrequestedpopup(this.href, this.target); return false;" title="this link will create a new window or will re-use an already opened one" >promote firefox adoption</a></p> you can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner: <script type="text/javascript"> var windowobjectreference = null; // global variable var previousurl; /* global variable that will store...
...And 2 more matches
ARIA: tab role - Accessibility
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.
... <div class="tabs"> <div role="tablist" aria-label="sample tabs"> <button role="tab" aria-selected="true" aria-controls="panel-1" id="tab-1" tabindex="0"> first tab </button> <button role="tab" aria-selected="false" aria-controls="panel-2" id="tab-2" tabindex="-1"> second tab </button> <button role="tab" aria-selected="false" aria-controls="panel-3" id="tab-3" tabindex="-1"> third tab </button> </div> <div id="panel-1" role="tabpanel" tabindex="0" aria-labelledby="tab-1"> <p>content for the first panel</p> </div> <div id="panel-2" role="tabpanel" tabindex=...
...And 2 more matches
ARIA: checkbox role - Accessibility
<span role="checkbox" aria-checked="false" tabindex="0" aria-labelledby="chk1-label"> </span> <label id="chk1-label">remember my preferences</label> the first rule of aria is if a native html element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding aria.
...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.
...And 2 more matches
ARIA: listbox role - Accessibility
all options that are not selected have aria-selected set to false.
...if set to true, every selectable option should have an aria-selected attribute included and set to true or false.
... if false or omitted, only the currently selected option, if any option is selected, needs the aria-selected attribute, and it must be set to true.
...And 2 more matches
Making content editable - Developer guides
for example, to use <p> elements: document.execcommand("defaultparagraphseparator", false, "p"); additionally, firefox supports the non-standard argument, br, for defaultparagraphseparator since firefox 55.
...you can use the older firefox behavior with this line: document.execcommand("defaultparagraphseparator", false, "br"); security for security reasons, firefox doesn't let javascript code use clipboard related features (copy, paste, etc.) by default.
...imple 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.innerhtml); odoc.innerhtml = ""; var opre = document.createelement("pre"); odoc.content...
...And 2 more matches
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
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.
... 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.
... <input type="button" value="button 1"> <input type="button" value="button 2"> <input type="button" value="button 3"> </fieldset> const button = document.queryselector('input'); const fieldset = document.queryselector('fieldset'); button.addeventlistener('click', disablebutton); function disablebutton() { fieldset.disabled = true; window.settimeout(function() { fieldset.disabled = false; }, 2000); } note: firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads.
...And 2 more matches
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.
... var hastouchscreen = false; if ("maxtouchpoints" 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) { ...
...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 ...
...And 2 more matches
Proxy Auto-Configuration (PAC) file - HTTP
in chrome (versions 52 to 73), you can disable this by setting pachttpsurlstrippingenabled to false in policy or by launching with the --unsafe-pac-url command-line flag (in chrome 74, only the flag works, and from 75 onward, there is no way to disable path-stripping; as of chrome 81, path-stripping does not apply to http urls, but there is interest in changing this behavior to match https); in firefox, the preference is network.proxy.autoconfig_url.include_path.
... examples isplainhostname("www.mozilla.org") // false isplainhostname("www") // true dnsdomainis() syntax dnsdomainis(host, domain) parameters host is the hostname from the url.
... examples dnsdomainis("www.mozilla.org", ".mozilla.org") // true dnsdomainis("www", ".mozilla.org") // false localhostordomainis() syntax localhostordomainis(host, hostdom) parameters host the hostname from the url.
...And 2 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
e 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 specified number format, then return the number parsed up to that point.
... 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.
... you can perform this conversion explicitly using the boolean() function: boolean(''); // false boolean(234); // true however, this is rarely necessary, as javascript will silently perform this conversion when it expects a boolean, such as in an if statement (see below).
...And 2 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._enumerableandnotenumerable...
...); // or just use: return object.getownpropertynames(obj); }, getprototypeenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._enumerable); }, getprototypenonenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._notenumerable); }, getprototypeenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, false, true, this._enumerableandnotenumerable); }, getownandprototypeenumerables: function(obj) { return this._getpropertynames(obj, true, true, this._enumerable); // or could use unfiltered for..in }, getownandprototypenonenumerables: function(obj) { return this._getpropertynames(obj, true, true, this._notenumerable); }...
...And 2 more matches
Grammar and types - JavaScript
var input; if (input === undefined) { dothis(); } else { dothat(); } the undefined value behaves as false when used in a boolean context.
... var a; a + 2; // evaluates to nan when you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts.
...true and false.
...And 2 more matches
Intl.Collator() constructor - JavaScript
possible values are "true" and "false".
...possible values are "upper", "lower", or "false" (use the locale's default).
...possible values are true and false; the default is false.
...And 2 more matches
Map - JavaScript
other operations on the data fail: wrongmap.has('bla') // false wrongmap.delete('bla') // false console.log(wrongmap) // map { bla: 'blaa', bla2: 'blaaa2' } the correct usage for storing data in the map is through the set(key, value) method.
... 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.
...And 2 more matches
Object.isExtensible() - JavaScript
object.preventextensions(empty); object.isextensible(empty); // === false // sealed objects are by definition non-extensible.
... var sealed = object.seal({}); object.isextensible(sealed); // === false // frozen objects are also by definition non-extensible.
... var frozen = object.freeze({}); object.isextensible(frozen); // === false non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
...And 2 more matches
Proxy - JavaScript
obj[prop] : 37; } }; const p = new proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it.
... 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
TypedArray.prototype.every() - JavaScript
return value true if the callback function returns a truthy value for every array element; otherwise, false.
... description the every method executes the provided callback function once for each element present in the typed array until it finds one where callback returns a falsy value (a value that becomes false when converted to a boolean).
... if such an element is found, the every method immediately returns false.
...And 2 more matches
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.
... if either value is nan, the operator returns false.
...And 2 more matches
Logical AND (&&) - JavaScript
if a value can be converted to false, the value is so-called falsy.
... examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
...see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( a() && b() ); // logs "called a" due to the function call, // then logs false (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).
...And 2 more matches
Logical OR (||) - JavaScript
if a value can be converted to false, the value is so-called falsy.
... examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
...see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( b() || a() ); // logs "called b" due to the function call, // then logs true (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).
...And 2 more matches
Strict equality (===) - JavaScript
if the operands are of different types, return false.
... if either operand is nan, return false.
... booleans must be both true or both false.
...And 2 more matches
in operator - JavaScript
// 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 my...
... let color1 = new string('green') 'length' in color1 // returns true let color2 = 'coral' // generates an error (color2 is not a string object) 'length' in color2 using in with deleted or undefined properties if you delete a property with the delete operator, the in operator returns false for that property.
... let mycar = {make: 'honda', model: 'accord', year: 1998} delete mycar.make 'make' in mycar // returns false let trees = new array('redwood', 'bay', 'cedar', 'oak', 'maple') delete trees[3] 3 in trees // returns false if you set a property to undefined but do not delete it, the in operator returns true for that property.
...And 2 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 instanc...
...for instance, [] instanceof window.frames[0].array will return false, because array.prototype !== window.frames[0].array and arrays inherit from the former.
... let simplestr = 'this is a simple string' let mystring = new string() let newstr = new string('string created with constructor') let mydate = new date() let myobj = {} let mynonobj = object.create(null) simplestr instanceof string // returns false, string literal is not an object mystring instanceof string // returns true newstr instanceof string // returns true mystring instanceof object // returns true myobj instanceof object // returns true, every object literal has object.prototype as prototype ({}) instanceof object // returns true, same case as above mynonobj instanceof object // returns false, prototype is end ...
...And 2 more matches
Classes and Inheritance - Archive of obsolete content
consider the following: let circle = circle(2, 3, 5); circle instanceof shape; // => false since instances of circle inherit from shape, we definitely want the result of this expression to be true.
...otherwise, it repeats the comparison for the prototype of the right hand side, and so on, until either it returns true, or the prototype becomes null, in which case it returns false.
...consequently, overriding a method is as simple as providing a new definition on the prototype of the subclass: circle.prototype.draw = function (ctx) { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, 2 * math.pi, false); ctx.fill(); }; with this definition in place, we get: let shape = shape(2, 3); shape.draw(); // error: not yet implemented let circle = circle(2, 3, 5); circle.draw(); // typeerror: ctx is not defined which is the behavior we were aiming for.
... property, let's redefine the constructor for the class circle in terms of class: var circle = class({ extends: shape, initialize: function(x, y, radius) { shape.prototype.initialize.call(this, x, y); this.radius = radius; }, draw: function (context) { context.beginpath(); context.arc(this.x, this.y, this.radius, 0, 2 * math.pi, false); context.fill(); } }); unlike the definition of circle in the previous section, we no longer have to override its prototype, or set its constructor property.
tabs/utils - Archive of obsolete content
if false, make the new tab the selected tab.
... optional, defaults to false.
...optional, defaults to false.
... returns boolean : true if the tab is open, otherwise false.
ui/frame - Archive of obsolete content
ation, you need to specify "*" as the origin: window.parent.postmessage("ping", "*"); if the frame script has received a message from the add-on already, it can use the origin property of the event object passed to the message hander: // listen for messages from the add-on, and send a reply window.addeventlistener("message", function(event) { event.source.postmessage("pong", event.origin) }, false); this frame script listens to change events on the "city-selector" <select> element, and sends a message to the add-on containing the value for the newly selected element.
.../city-info.html", onmessage: (e) => { updateweather(e.data); } }); var toolbar = toolbar({ name: "city-info", title: "city info", items: [frame] }); function updateweather(location) { frame.postmessage(weather[location], frame.url); } to listen to these messages in the frame script, add a listener to the window's message event: window.addeventlistener("message", updateweather, false); function updateweather(message) { var label = window.document.getelementbyid("weather"); label.textcontent = message.data; } from add-on to a specific frame you can send a message from the main add-on code to the frame hosted by a particular browser window.
... to receive such messages in the frame script, listen for the window's message event: window.addeventlistener("message", handlepong, false); sending json in all cases, you can send a string as a message or a json object.
...ar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ name: "my-toolbar", title: "my toolbar", items: [frame] }); frame.postmessage("ping", frame.url); frame scripts can receive these messages using window.addeventlistener(): function ponged(message) { label.textcontent = message.data; } window.addeventlistener("message", ponged, false); to send a message only to the frame instance hosted by a specific browser window call postmessage() on the source property of the object passed into any of the frame's event listeners.
Forms related code snippets - Archive of obsolete content
+ " " + 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 bismonth = rmonth.test(this.id), ndelta = rdecrease.test(this.id) ?
..."getmonth" : "getfullyear"]() + ndelta); othiscal.writedays(); return false; } function ondayclick () { const othiscal = ainstances[this.id.replace(rbgnandend, "")]; othiscal.target.value = (this.innerhtml / 100).tofixed(2).substr(-2) + "\/" + (othiscal.current.getmonth() + 1) + "\/" + othiscal.current.getfullyear(); othiscal.container.parentnode.removechild(othiscal.container); return false; } function buildcalendars () { const afields = document.getelementsbyclassname(sdpclass), nlen = afields.length; for (var nitem = 0; nitem < nlen; new datepicker(afields[nitem++])); } const /* customizable by us...
...addeventlistener("load", buildcalendars, false) : window.attachevent ?
...document.addeventlistener("mousedown", ondocclick, false) : document.attachevent ?
On page load - Archive of obsolete content
//messenger/content/messenger.xul navigator from seamonkey chrome://navigator/content/navigator.xul attaching a script attach a script to your overlay (see "attaching a script to an overlay") that adds a load event listener to appcontent element (browsers) or messagepane (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){ mess...
...to attach to the unload event in above example you can use the "pagehide" event like this: appcontent.addeventlistener("pagehide", myextension.onpageunload, false); for appcontent and similarly for messagepane messagepane.addeventlistener("pagehide", myextension.onpageunload, false); and add your code to onpageunload method.
... if(gbrowser) gbrowser.addeventlistener("domcontentloaded", this.onpageload, false); }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered the event var win = doc.defaultview; // win is the window for the doc // test desired conditions and do something // if (doc.nodename != "#document") return; // only documents // if (win != win.top) return; //only top window.
... // if (win.frameelement) return; // skip iframes/frames alert("page is loaded \n" +doc.location.href); } } window.addeventlistener("load", function load(event){ window.removeeventlistener("load", load, false); //remove listener, no longer needed myextension.init(); },false); references if you need to have a more complicated listener (not just onload), use progress listeners.
Install Manifests - Archive of obsolete content
the default value is false.
... 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.
... by default, the value of this property is false meaning that the compatibility checking will not be performed against the max version.
... examples <em:translator>janez novak</em:translator> <em:translator>kari nordmann</em:translator> unpack a true or false value that tells the application whether the extension requires its files be unpacked into a directory in order to work or whether the extension can be loaded direct from the xpi.
Listening to events in Firefox extensions - Archive of obsolete content
} b.addeventlistener("event", callback, false) where b is the browser or tabbrowser you wish to watch for events from.
...the pageshow event uses a boolean property called persisted that is set to false on the initial load.
...this property is set to false if the page is not cached by the browser and set to true if the page is cached by the browser.
... when this property is set to false, the unload handler, if present, fires immediately after the pagehide event.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
note: with attributes like hidden, collapsed, and disabled, which take boolean values, setting disabled="false" in xul can have unintended consequences.
...so when changing the attribute’s value using a dom function for example, do not use setattribute('disabled', false) — instead, use removeattribute('disabled').
... var item = document.getelementbyid('menu-item-custom'); function handlecommandevent(aevent) { alert('ok'); item.removeeventlistener('command', handlecommandevent, false); item.parentnode.removechild(item); } item.addeventlistener('command', handlecommandevent, false); listing 11: additions and deletions using a dynamic event listener special menu items much like input elements in html, menuitem elements can operate like checkboxes and radio buttons by setting their type attributes.
... <checkbox label="checkbox checked" checked="true"/> <checkbox label="checkbox unchecked" checked="false"/> listing 11: checkboxes in different state figure 11: output from listing 11 radio buttons radio buttons in html are multiple input elements grouped by assigning them all the same name attribute.
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
// restore session (event handler) restore: function(event) { }, // delete session (event handler) clear: function(event) { }, // dynamically generate menu items (event handler) createmenu: function(event) { }, // read file _readfile: function(afile) { }, // write file _writefile: function(afile, adata) { }, }; window.addeventlistener("load", function(){ gsessionstore.init(); }, false); window.addeventlistener("unload", function(){ gsessionstore.uninit(); }, false); wrap methods and variables as properties of objects you’ll note that in listing 15, i’ve defined a lot of different methods and variables as properties of a single object, gsessionstore.
... listing 20: content for restore method restore: function(event) { var filename = event.target.getattribute("filename"); var file = this._dir.clone(); file.append(filename); var state = this._readfile(file); var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); ss.setwindowstate(window, state, false); }, clear method this uses the directoryentries property of the nslfile interface to delete all files within the directory you got earlier.
... listing 21: content for clear method clear: function(event) { event.preventbubble(); var fileenum = this._dir.directoryentries; while (fileenum.hasmoreelements()) { var file = fileenum.getnext().queryinterface(components.interfaces.nsifile); file.remove(false); // debug dump("sessionstore> clear: " + file.leafname + "\n"); } }, _readfile method reads the nslfile object passed as a parameter, and returns its contents as a text string.
...if true, causes a confirmation dialog to appear; if false, deletes immediately.
Adding windows and dialogs - Archive of obsolete content
let somevalue = 2; let returnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, returnvalue); // you can send as many extra parameters as you need.
...the only constant rule is that clicking on ok and cancel will close the dialog unless your associated function returns false.
... you should avoid returning false, though, specially with the cancel button.
... <checkbox id="xulschoolhello-some-checkbox" label="&xulschoolhello.sometext.label;" checked="false" persist="checked" /> setting the id attribute of the element is mandatory if you want the persist attribute to work.
Observer Notifications - Archive of obsolete content
you should normally set the third parameter to false.
... getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(testobserver, "xulschoolhello-test-topic", false); you should come up with a notification topic that is unique so you know it will not conflict with firefox or other extensions topics.
... getservice(components.interfaces.nsiobserverservice); this._observerservice.addobserver(this, "xulschoolhello-test-topic", false); }, /** * unitializes this object.
... */ observe : function(asubject, atopic, adata) { if (atopic == "xulschoolhello-test-topic") { asubject.queryinterface(ci.nsisupportsstring); window.alert("subject: " + asubject.data); // => "this is a test" window.alert("data: " + adata); // => "hello" } } } window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); window.addeventlistener( "unload", function() { xulschoolchrome.browseroverlay.uninit(); }, false); in the observe method the notification topic is verified because you can have one observer listening to several topics.
Introducing the Audio API extension - Archive of obsolete content
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); </script> </body> </html> the mozaudioavailable event as the audio is played, sample data is made available to the audio layer and the audio buffer (size defined in mozframebufferlength) gets filled with those samples.
...event) { var framebuffer = event.framebuffer; var t = event.time; var text = "samples at: " + t + "\n"; text += framebuffer[0] + " " + framebuffer[1]; raw.innerhtml = text; } var raw = document.getelementbyid('raw'); var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> creating an audio stream it is also possible to create and setup an <audio> element for raw writing from script (i.e., without a src attribute).
... autolatency = false; } processing an audio stream since the mozaudioavailable event and the mozwriteaudio() method both use float32array values, it is possible to take the output of one audio stream and pass it directly (or process first and then pass) to a second.
... a2.mozsetup(a1.mozchannels, a1.mozsamplerate); } function audioavailable(event) { // write the current framebuffer var framebuffer = event.framebuffer; writeaudio(framebuffer); } a1.addeventlistener('mozaudioavailable', audioavailable, false); a1.addeventlistener('loadedmetadata', loadedmetadata, false); function writeaudio(audio) { buffers.push(audio); // if there's buffered data, write that while(buffers.length > 0) { var buffer = buffers.shift(); var written = a2.mozwriteaudio(buffer); // // if all data wasn't written, keep it in the buffers: if(written < buffer.length) { buffers.unshift(buffer.slice(...
command - Archive of obsolete content
ArchiveMozillaXULEventscommand
false otherwise.
...false otherwise.
...false otherwise.
...false otherwise.
tooltip - Archive of obsolete content
noautohide type: boolean if this attribute is set to false or omitted, the tooltip will automatically disappear after a few seconds.
...returning false from this event handler prevents the popup from appearing.
... iscontextmenu the iscontextmenu argument should be true for context menus and false for all other types of popups.
...if attributesoverride is false, the attribute is only used if the position argument is empty.
wizard - Archive of obsolete content
if this property is false, the user cannot navigate to the next page.
...set to false to disallow moving to the next page.
...if this property is false, the user cannot navigate to the previous page.
...set to false to disallow moving to the previous page.
Monitoring plugins - Archive of obsolete content
service you must create a class with an observe method which receives 3 parameters (subject, topic and data) as well as a register method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice (components.interfaces.nsiobserverservice); observerservice.addobserver(this, "experimental-notify-plugin-call", false); observing as discussed above, to specify what you want done when a notification arrives your class must have an observe method, receiving 3 parameters (subject, topic and data).
... code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "experimental-notify-plugin-call"); skeleton observer class below is a skeleton class that you may use to listen to runtime notifications: function pluginobserver() { this.registered = false; this.register(); //takes care of registering this class with observer services as an observer for plugin runtime notifications } pluginwatcherobserver.prototype = { observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-call") //in case your class is registered to listen to other topics //this gets executed each time a runtime notification arriv...
...es // --your code goes here-- } }, //takes care of registering the observer services for the "experimental-notify-plugin-call" topic register: function() { if (this.registered == false) { //this check prevents double registration -- something you want to avoid!!
... var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(this, "experimental-notify-plugin-call", false); this.registered = true; } }, //unregisters from the observer services unregister: function() { if (this.registered == true) { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "experimental-notify-plugin-call"); this.registered = false; } } } additional resources more information on the observer service: nsiobserverservi...
NPFullPrint - Archive of obsolete content
false: (default) plug-in renders its area of the page only (for embedded plug-in).
...should always be false.
... false: display print dialogs so user can choose printer, other options.
...if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and return immediately; the browser calls npp_print again with the npembedprint substructure of npprint.
NPN_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 browser that th...
...to set windowless operation, call npn_setvalue with nppvpluginwindowbool as the variable parameter and false as the value parameter.
...to specify an opaque mode, the plugin calls npn_setvalue with nppvplugintransparentbool for the variable parameter and false for the value parameter.
...} so the proper way to call this function from a plug-in would be: bool bwindowed = false; npn_setvalue(npp, nppvpluginwindowbool, ( void *)bwindowed); see also npp_new, npn_getvalue, npp_setvalue, npp_getvalue ...
XForms Select1 Element - Archive of obsolete content
xhtml widget characteristics analogous widgets is <html:select/> visual grouping by choices element is supported selection="open" is supported if incremental attribute value is false, the bound node is updated when the select1 control is blurred (i.e.
... loses focus), otherwise it is updated upon item selection xul widget characteristics analogous widgets are <html:select/> and <xul:menulist/> visual grouping by choices element isn't implemented selection="open" attribute isn't supported if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e.
...characteristics analogous widgets are <html:select size="5"/> and <xul:listbox/> visual grouping by choices element isn't implemented selection="open" attribute isn't supported if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e.
...characteristics appearance attribute contains the value full there are no analogue widgets in xhtml or in xul visual grouping by choices element is supported selection="open" attribute isn't supported if incremental attribute value is false then bound node is updated when item is blurred examples <xf:model> <xf:instance> <data xmlns=""> <values>g</values> </data> </xf:instance> </xf:model> <xf:select1 ref="/data/values"> <xf:choices> <xf:label>green colors</xf:label> <xf:item> <xf:label>pale green</xf:label> <xf:value>pg</xf:value> </xf:item> <xf:item> <xf:label>green</xf:label> <xf:value>g</xf:v...
Audio for Web games - Game development
let's add some javascript to make this work: var myaudio = document.getelementbyid('myaudio'); var buttons = document.getelementsbytagname('button'); var stoptime = 0; for (var i = 0; i < buttons.length; i++) { buttons[i].addeventlistener('click', function() { myaudio.currenttime = this.getattribute("data-start"); stoptime = this.getattribute("data-stop"); myaudio.play(); }, false); } myaudio.addeventlistener('timeupdate', function() { if (this.currenttime > stoptime) { this.pause(); } }, false); note: you can try out our audio sprite player live on jsfiddle.
... 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> <button 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> <button data-playing="false" aria-describedby="clavi-play-label"> <span id="clavi-play-label">play</span> </button> </li> <...
...ur <li> elements, grab the correct file for each one and then allow playback by hiding the "loading" text and displaying the play button: trackels.foreach((el, i) => { // get children const anchor = el.queryselector('a'); const loadtext = el.queryselector('p'); const playbutton = el.queryselector('button'); // load file loadfile(anchor.href).then((track) => { // set loading to false el.dataset.loading = 'false'; // hide loading 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(); } ...
Implementing controls using the Gamepad API - Game development
the first one is fired when the browser detects the connection of a new gamepad while the second one is fired when a gamepad is disconnected (either physically by the user or due to inactivity.) in the demo, the gamepadapi object is used to store everything related to the api: var gamepadapi = { controller: {}, turbo: false, connect: function() {}, disconnect: function() {}, update: function() {}, buttonpressed: function() {}, buttons: [], buttonscache: [], buttonsstatus: [], axesstatus: [] }; the buttons array contains the xbox 360 button layout: buttons: [ 'dpad-up','dpad-down','dpad-left','dpad-right', 'start','back','axis-left','axis-right', 'lb','rb','power','a','b','x','y', ], this can...
...(we could use the gamepad.connected boolean for this purpose, but we wanted to have a separate variable for turning on turbo mode without needing to have a gamepad connected, for reasons explained above.) disconnect: function(evt) { gamepadapi.turbo = false; delete gamepadapi.controller; console.log('gamepad disconnected.'); }, the disconnect function sets the gamepad.turbo property to false and removes the variable containing the gamepad object.
... buttonpressed: function(button, hold) { var newpress = false; // loop through pressed buttons for(var i=0,s=gamepadapi.buttonsstatus.length; i<s; i++) { // if we found the button we're looking for...
... // set the boolean variable to true newpress = true; // if we want to check the single press if(!hold) { // loop through the cached states from the previous frame for(var j=0,p=gamepadapi.buttonscache.length; j<p; j++) { // if the button was already pressed, ignore new press if(gamepadapi.buttonscache[j] == button) { newpress = false; } } } } } return newpress; }, there are two types of action to consider for a button: a single press and a hold.
Extra lives - Game development
e existing scoretext definition inside your create() function: livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, { font: '18px arial', fill: '#0095dd' }); livestext.anchor.set(1,0); lifelosttext = game.add.text(game.world.width*0.5, game.world.height*0.5, 'life lost, click to continue', { font: '18px arial', fill: '#0095dd' }); lifelosttext.anchor.set(0.5); lifelosttext.visible = false; the livestext and lifelosttext objects look very similar to the scoretext one — they define a position on the screen, the actual text to display, and the font styling.
... the lifelosttext will be shown only when the life is lost, so its visibility is initially set to false.
...ple instances of the text styling are replaced with the variable: scoretext = game.add.text(5, 5, 'points: 0', textstyle); livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, textstyle); livestext.anchor.set(1,0); lifelosttext = game.add.text(game.world.width*0.5, game.world.height*0.5, 'life lost, click to continue', textstyle); lifelosttext.anchor.set(0.5); lifelosttext.visible = false; this way changing the font in one variable will apply the changes to every place it is used.
...een() 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 printing out the alert when you lose a life, we first subtract one life from the current number and check if it's a non-zero value.
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
d is allowed if (href === '' || href === null) { // points to same document if empty (null is equivalent to empty string) href = null; // set for uniformity in testing below if (parse === 'xml' && xpointer === null) { alert('there must be an xpointer attribute present if "href" is empty an parse is "xml"'); return false; } } else if (href.match(/#$/, '') || href.match(/^#/, '')) { alert('fragment identifiers are disallowed in an xinclude "href" attribute'); return false; } var j; var xincludeparent = xinclude.parentnode; try { netscape.security.privilegemanager.enableprivilege('...
...universalxpconnect universalbrowserread'); // necessary with file:///-located files trying to reach external sites if (href !== null) { var response, responsetype; var request = new xmlhttprequest(); request.open('get', href, false); request.setrequestheader('if-modified-since', 'thu, 1 jan 1970 00:00:00 gmt'); request.setrequestheader('cache-control', 'no-cache'); if (accept) { request.setrequestheader('accept', accept); } if (acceptlanguage) { request.setrequestheader('accept-language', acceptlanguage); } switch (parse) { ...
... responsetype = 'responsetext'; break; case null: case 'xml': responsetype = 'responsexml'; break; default: alert('xinclude element contains an invalid "parse" attribute value'); return false; break; } request.send(null); if((request.status === 200 || request.status === 0) && request[responsetype] !== null) { response = request[responsetype]; if (responsetype === 'responsexml') { // apply xpointer (only xpath1() subset is ...
... } // need to make a whole new request apparently since cannot convert the encoding after receiving it (to know what the encoding was) var request2 = new xmlhttprequest(); request2.overridemimetype('text/plain; charset='+encodingtype); request2.open('get', href, false); request2.setrequestheader('if-modified-since', 'thu, 1 jan 1970 00:00:00 gmt'); request2.setrequestheader('cache-control', 'no-cache'); request2.send(null); response = request2[responsetype]; // update the response for processing } ...
A first splash into JavaScript - Learn web development
cument.body.append(resetbutton); resetbutton.addeventlistener('click', resetgame); } function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for(let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } resetbutton.parentnode.removechild(resetbutton); guessfield.disabled = false; guesssubmit.disabled = false; guessfield.value = ''; guessfield.focus(); lastresult.style.backgroundcolor = 'white'; randomnumber = math.floor(math.random() * 100) + 1; } </script> </body> </html> have a go at playing it — familiarize yourself with the game before you move on.
...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.
...add the following code, again to the bottom of your javascript: function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for (let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } resetbutton.parentnode.removechild(resetbutton); guessfield.disabled = false; guesssubmit.disabled = false; guessfield.value = ''; guessfield.focus(); lastresult.style.backgroundcolor = 'white'; randomnumber = math.floor(math.random() * 100) + 1; } this rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go.
Componentizing our Svelte app - Learn web development
add the following variable definitions at the bottom of the <script> section of the todo component: let editing = false // track editing mode let name = todo.name // hold the name of the todo being edited we have to decide what events our todo component will emit: we could emit different events for the status toggle and editing of the name.
... add the following set of functions below your previous function to handle these actions: function oncancel() { name = todo.name // 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() { updat...
... 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.
... the <input>'s value property will be bound to the name variable, and the buttons to cancel and save the changes call oncancel() and onsave() respectively (we added those functions earlier): when oncancel() is invoked, name is restored to its original value (when passed in as a prop) and we exit editing mode (by setting editing to false).
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 t...
...e is from 0-65535, rfc 2109 and 2965 require 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.
... network.cookie.prefsmigrated default value: false migration pref for users with older profiles (before mozilla 1.7).
...(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.
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.
... to verify that status of fips mode, run the -chkfips command with either a true or false flag (it doesn't matter which).
... modutil -chkfips false -dbdir sql:/home/my/sharednssdb/ fips mode enabled.
NSS 3.15.4 release notes
bug 919877 - (cve-2013-1740) when false start is enabled, libssl will sometimes return unencrypted, unauthenticated data from pr_recv new in nss 3.15.4 new functionality implemented ocsp querying using the http get method, which is the new default, and will fall back to the http post method.
... new functions cert_forcepostmethodforocsp cert_getsubjectnamedigest cert_getsubjectpublickeydigest ssl_peercertificatechain ssl_recommendedcanfalsestart ssl_setcanfalsestartcallback new types cert_rev_m_force_post_method_for_ocsp: when this flag is used, libpkix will never attempt to use the http get method for ocsp requests; it will always use post.
... improved ssl/tls false start.
... in addition to enabling the ssl_enable_false_start option, an application must now register a callback using the ssl_setcanfalsestartcallback function.
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.
... to verify that status of fips mode, run the -chkfips command with either a true or false flag (it doesn't matter which).
... modutil -chkfips false -dbdir sql:/home/my/sharednssdb/ fips mode enabled.
ssltyp.html
freeitem when pr_false, free only the structure pointed to.
...when freeitem is not pr_false, also frees the item structure itself.
... freeitem when pr_false, free only the structure pointed to.
...when freeitem is not pr_false, also zeroes and frees the item structure itself.
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
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.
... to verify that status of fips mode, run the -chkfips command with either a true or false flag (it doesn't matter which).
... modutil -chkfips false -dbdir sql:/home/my/sharednssdb/ fips mode enabled.
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.
JS_AddArgumentFormatter
otherwise it returns js_false.
... 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.
...when called from js_pushargumentsva, the formatter is invoked thus: formatter(cx, "aa...", js_false, &sp, &ap); where js_false for fromjs means to wrap the c values at ap according to the format specifier and store them at sp, updating ap and sp appropriately.
JS_PreventExtensions
before then, js_preventextensions did not accept a succeeded argument; in those cases where *succeeded would be set to false, js_preventextensions would throw a typeerror and return false.
... for example, if making the object requires an allocation, and that allocation fails, out-of-memory might be reported, and js_preventextensions would return false.
... var target = {}; var handler = {}; var pair = proxy.revocable(target, handler); var proxy = pair.proxy; var revoke = pair.revoke; revoke(); // bool succeeded; // bool rv = js_preventextensions(cx, proxy, &succeeded); // // rv == false, succeeded is indeterminate the second case occurs when no internal error is encountered, but the object simply refuses to be made non-extensible.
... 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).
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.
...for managing,you want this to be false, for menus and such, you want this to be true.
... checkurlsecurity(aurinode) parameters aurinode a uri node return type return true if it's safe to open the node in the browser, false otherwise.
IAccessibleAction
s_false if there is nothing to return, [out] value is null.
...s_false if there are no relations, [out] values are null and 0 respectively.
...s_false if there is nothing to return, [out] value is null.
...s_false if there is nothing to return, [out] value is null.
IAccessibleApplication
return value s_false if there is nothing to return, [out] value is null.
... return value s_false if there is nothing to return, [out] value is null.
... return value s_false if there is nothing to return, [out] value is null.
... return value s_false if there is nothing to return, [out] value is null.
IAccessibleHyperlink
s_false if there is nothing to return, [out] value is null.
...s_false if there is nothing to return, [out] value is null.
...[propget] hresult valid( [out] boolean valid ); parameters valid true if the referenced target is still valid and false otherwise.
... return value s_false if there is nothing to return, [out] value is false.
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.
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.
nsIAppShellService
this will usually be false on all non-mac platforms.
... ashowwindow obsolete since gecko 1.8 the window remains invisible if pr_false.
... caninteract if false and ui is needed, will fail.
... amodal true if awindow is becoming modal or false if awindow is becoming nonmodal (or being closed).
nsICategoryManager
you must pass false for this parameter.
... exceptions thrown ns_error_invalid_arg this error is returned if areplace is false and the category entry already has a value, or if apersist is true.
...you should always pass false for this parameter.
...let categorymanager = cc['@mozilla.org/categorymanager;1']; categorymanager.getservice(ci.nsicategorymanager).deletecategoryentry('gecko-content-viewers', content_type, false); // update pref manager to prevent plugins from loading in future var stringtypes = ''; var types = []; var pref_disabled_plugin_types = 'plugin.disable_full_page_plugin_for_types'; if (services.prefs.prefhasuservalue(pref_disabled_plugin_types)) { stringtypes = services.prefs.getcharpref(pref_disabled_plugin_types); } if (stringtypes !== '') { types = stringtypes.split(','); } if (ty...
nsIClipboardDragDropHooks
otherwise, false to indicates to the operating system that drop is not allowed.
...otherwise, false to show the drag is canceled (does not go to operating system).
...otherwise, false to indicate that the copy/drag is canceled, does not go to operating system.
...otherwise, false to indicate the action was not overridden, do built-in behavior.
nsICryptoHash
if false, then the returned value is binary data.
...inputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = components.classes["@mozilla.org/security/hash;1"] .createinstance(components.interfaces.nsicryptohash); // we want to use the sha256 algorithm ch.init(ch.sha256); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } // convert the binary hash data to a hex string.
...the single parameter to this method is false in this example to return binary data.
...charset = "utf-8"; // result is an out parameter, // result.value will contain the array length var result = {}; // data is an array of bytes var data = converter.converttobytearray(str, result); var ch = components.classes["@mozilla.org/security/hash;1"] .createinstance(components.interfaces.nsicryptohash); ch.init(ch.sha256); ch.update(data, data.length); var hash = ch.finish(false); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } // convert the binary hash data to a hex string.
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.
nsIEditorSpellCheck
if there are no available dictionaries, the return value is false.
...boolean checkcurrentword( in wstring suggestedword ); parameters suggestedword missing description return value true if the specified word is misspelled; otherwise false.
... return value true if the word is misspelled; otherwise false.
...if false, only the first occurrence is replaced.
nsIHttpChannelInternal
this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false.
...this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false.
...this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false.
...this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false.
nsIMsgDBView
if false kb are used.
...false if it is disabled.
...false otherwise.
...if false then replace current selection.
Component; nsIPrefBranch
false holds a strong reference to aobserver.
...in particular, this method will return false for such a preference and the preference will not be saved to a file by nsiprefservice.savepreffile().
...false the preference only has a default value.
...false the preference is not locked.
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.
... void runw( in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately.
...var args = ["argument1", "argument2"]; process.run(false, args, args.length); see also nsifile nsiprocess2 obsolete since gecko 1.9.2 ...
nsIProcessScriptLoader
it's possible that the child process for this chromemessagesender is not yet available at the time of the loadprocessscript() call, and if you pass false in this situation, your process script won't be loaded.
...for example data:,dump("foo\n"); aallowdelayedload boolean if this flag is false, the process script will only be loaded into child processes that are already running at the time of the call.
...the return value is a list of pairs [<url>, false].
...each script is returned as a pair: [<url>, false].
nsITextInputProcessorCallback
example of simple js-ime: var simpleime = { _hasfocus: 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) { this._tip = components.classes["@mozilla.org/text-input-processor;1"].
... createinstance(components.interfaces.nsitextinputprocessor); } if (!this._tip.begininputtransaction(window, this._callback)) { return false; } ...
...otherwise, false.
nsIWindowMediator
, ci: interfaces} = components; var windowlistener = { onopenwindow: function (awindow) { // wait for the window to finish loading let domwindow = awindow.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidomwindowinternal || ci.nsidomwindow); domwindow.addeventlistener("load", function () { domwindow.removeeventlistener("load", arguments.callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domwindow.gbrowser && domwindow.gbrowser.tabcontainer) { domwindow.gbrowser.tabcontainer.addeventlistener('tabselect', function () { ...
... domwindow.alert('tab was selected') }, false); } }, false); }, onclosewindow: function (awindow) {}, onwindowtitlechange: function (awindow, atitle) {} }; //to register services.wm.addlistener(windowlistener); //services.wm.removelistener(windowlistener); //once you want to remove this listener execute removelistener, currently its commented out so you can copy paste this code in scratchpad and see it work native code only!calculatezposition a window wants to be moved in z-order.
...back to front if false.
...back to front if false.
Version, UI, and Status Information - Plugins
if false is returned, windowless plug-ins will not work, and the developer must provide alternatives.
...*/ 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.
... bool has_windowless() { npbool supportswindowless = false; nperror ret = npn_getvalue(instance, npnvsupportswindowless, &supportswindowless); return ret == nperr_no_error && supportswindowless; } reloading a plug-in when the browser starts up, it loads all the plug-ins it finds in the plugins directory for the platform.
... void npn_reloadplugins(npbool reloadpages); the reloadpages parameter is a boolean that indicates whether to reload the page (true) or not (false).
Debugger.Frame - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its debugger.frame instances, without worrying about interfering with other debuggers.) when the debuggee pops a stack frame (say, because a function call has returned or an exception has been thrown from it), the debugger.frame instance referring to that frame becomes inactive: its live property becomes false, and accessing its other properties or calling its methods throws an exception.
... 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.Script - Firefox Developer Tools
false otherwise.
...false otherwise.
...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.
... isincatchscope([offset]) if the instance refers to a jsscript, this is true if this offset falls within the scope of a try block, and false otherwise.
Intensive JavaScript - Firefox Developer Tools
th 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 = false; console.log(primes); } we're just running a (very inefficient) primality test 50 times, for some quite large numbers.
... it's pretty simple to split up calculateprimes(): we will just calculate primality for each number in a separate function: function dopointlesscomputationswithrequestanimationframe() { function testcandidate(index) { // finishing condition if (index == iterations) { console.log(primes); pointlesscomputationsbutton.disabled = false; return; } // test this number var candidate = index * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } // schedule the next var testfunction = ...
... the main thread code would look something like this: const iterations = 50; const multiplier = 1000000000; var worker = new worker("js/calculate.js"); function dopointlesscomputationsinworker() { function handleworkercompletion(message) { if (message.data.command == "done") { pointlesscomputationsbutton.disabled = false; console.log(message.data.primes); worker.removeeventlistener("message", handleworkercompletion); } } worker.addeventlistener("message", handleworkercompletion, false); worker.postmessage({ "multiplier": multiplier, "iterations": iterations }); } the main difference here, compared with the original, is that we need to: create a worker send it a message when ...
...lier); 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.
Cache.match() - Web APIs
WebAPICachematch
it defaults to false.
... 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.
...it defaults to false.
...if our if() condition is false, then this fetch handler won't intercept the request.
Event() - Web APIs
WebAPIEventEvent
the default is false.
...the default is false.
...the default is false.
... 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.
HTMLSelectElement - Web APIs
this attribute is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
...it is false if any conditions bar it from constraint validation.
...if the element fails its constraints, the browser fires a cancelable invalid event at the element (and returns false).
...if there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true.
IDBKeyRange - Web APIs
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.
... the upper value of the key range is one of the following: undefined greater than key value equal to key value if upperopen is false.
... idbkeyrange.loweropen read only returns false if the lower-bound value is included in the key range.
... idbkeyrange.upperopen read only returns false if the upper-bound value is included in the key range.
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.
... if false, no audio track is included.
...ment = 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.
...nt = 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 bandwidth saving measure).
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.
... if false, no video track is included.
...nt = 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.
...elementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 15 } }).then(stream => videoelement.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 video constraints that indicate a preference for a video track whose dimensions are as close as possible to 160x120 pixels, and whose frame rate is as close to 15 frames per second as possible.
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.
... when enabled is set to false, the track only generates empty frames.
... usage notes if the mediastreamtrack represents the video input from a camera, disabling the track by setting enabled to false also updates device activity indicators to show that the camera is not currently recording or streaming.
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.
...this is false if the video being captured is coming from a foreground (user-visible) source.
Capabilities, constraints, and settings - Web APIs
let videodefaultconstraintstring = '{\n "width": 320,\n "height": 240,\n "framerate": 30\n}'; let audiodefaultconstraintstring = '{\n "samplesize": 16,\n "channelcount": 2,\n "echocancellation": false\n}'; these defaults ask for a pretty common camera configuration, but don't insist on any property being of special importance.
... we also need to set up an event listener to watch for the "start video" button to be clicked: document.getelementbyid("startbutton").addeventlistener("click", function() { startvideo(); }, false); applying constraint set updates next, we set up an event listener for the "apply constraints" button.
...otrack.applyconstraints(videoconstraints).then(function() { videosettingstext.value = json.stringify(videotrack.getsettings(), null, 2); }).catch(handleerror); } if (audiotrack) { audiotrack.applyconstraints(audioconstraints).then(function() { audiosettingstext.value = json.stringify(audiotrack.getsettings(), null, 2); }).catch(handleerror); } } }, false); handling the stop button then we set up the handler for the stop button.
...key == "tab") { let elem = event.target; let str = elem.value; let position = elem.selectionstart; let newstr = str.substring(0, position) + " " + str.substring(position, str.length); elem.value = newstr; elem.selectionstart = elem.selectionend = position + 2; event.preventdefault(); } } videoconstrainteditor.addeventlistener("keydown", keydownhandler, false); audioconstrainteditor.addeventlistener("keydown", keydownhandler, false); show constrainable properties the browser supports the last significant piece of the puzzle: code that displays, for the user's reference, a list of the constrainable properties which their browser supports.
MouseEvent() - Web APIs
"ctrlkey", optional and defaulting to false, of type boolean, that indicates if the ctrl key was simultaneously pressed.
... "shiftkey", optional and defaulting to false, of type boolean, that indicates if the shift key was simultaneously pressed.
... "altkey", optional and defaulting to false, of type boolean, that indicates if the alt key was simultaneously pressed.
... "metakey", optional and defaulting to false, of type boolean, that indicates if the meta key was simultaneously pressed.
MutationObserverInit.subtree - Web APIs
the default value, false, indicates only the target node itself is to be monitored for changes.
... syntax var options = { subtree: true | false } value a boolean value.
... the default, false, indicates that only the target node specified when calling mutationobserver.observe() is to be monitored for changes.
... for example, to watch the target node only for attribute changes, the mutationobserverinit passed into mutationobserver() can be: var options = { attributes: true, subtree: false }; since the default value of subtree is false, line 3 is optional.
Node - Web APIs
WebAPINode
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.
...*/ removeallchildren(document.body) recurse through child nodes the following function recursively calls a callback function for each node contained by a root node (including the root itself): function eachnode(rootnode, callback) { if (!callback) { const nodes = [] eachnode(rootnode, function(node) { nodes.push(node) }) return nodes } if (false === callback(rootnode)) { return false } if (rootnode.haschildnodes()) { const nodes = rootnode.childnodes for (let i = 0, l = nodes.length; i < l; ++i) { if (false === eachnode(nodes[i], callback)) { return } } } } syntax eachnode(rootnode, callback) description recursively calls a function for each descendant node of rootnode (including the root itse...
... if callback is provided, and it returns boolean false when called, the current recursion level is aborted, and the function resumes execution at the last parent's level.
... we use a wrapper function named grep to do the searching: function grep(parentnode, pattern) { const matches = [] let endscan = false eachnode(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) { e...
Page Visibility API - Web APIs
// warn if the browser doesn't support addeventlistener or the page visibility api if (typeof document.addeventlistener === "undefined" || hidden === undefined) { console.log("this demo requires a browser, such as google chrome or firefox, that supports the page visibility api."); } else { // handle page visibility change document.addeventlistener(visibilitychange, handlevisibilitychange, false); // when the video pauses, set the title.
... // this shows the paused videoelement.addeventlistener("pause", function(){ document.title = 'paused'; }, false); // when the video plays, set the title.
... videoelement.addeventlistener("play", function(){ document.title = 'playing'; }, false); } properties added to the document interface the page visibility api adds the following properties to the document interface: document.hidden read only returns true if the page is in a state considered to be hidden to the user, and false otherwise.
... //startsimulation and pausesimulation defined elsewhere function handlevisibilitychange() { if (document.hidden) { pausesimulation(); } else { startsimulation(); } } document.addeventlistener("visibilitychange", handlevisibilitychange, false); specifications specification status comment page visibility (second edition) recommendation initial definition.
PaymentRequest.PaymentRequest() - Web APIs
the default is false.
...the default is false.
...the default is false.
...the default is false.
Pointer Lock API - Web APIs
if ("onpointerlockchange" in document) { document.addeventlistener('pointerlockchange', lockchangealert, false); } else if ("onmozpointerlockchange" in document) { document.addeventlistener('mozpointerlockchange', lockchangealert, false); } function lockchangealert() { if(document.pointerlockelement === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); // do something useful in response } else { console.log('the pointer lock s...
... document.addeventlistener('pointerlockerror', lockerror, false); document.addeventlistener('mozpointerlockerror', lockerror, false); function lockerror(e) { alert("pointer lock failed"); } note: until firefox 50 the above events were prefixed with moz in firefox.
... // pointer lock event listener // hook pointer lock state change events for different browsers document.addeventlistener('pointerlockchange', lockchangealert, false); document.addeventlistener('mozpointerlockchange', lockchangealert, false); this function checks the pointlockelement property to see if it is our canvas.
... function lockchangealert() { if (document.pointerlockelement === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); document.addeventlistener("mousemove", updateposition, false); } else { console.log('the pointer lock status is now unlocked'); document.removeeventlistener("mousemove", updateposition, false); } } the updateposition() function updates the position of the ball on the canvas (x and y), and also includes if() statements to check whether the ball has gone off the edges of the canvas.
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).
... the default is 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.
... the default is false.
ServiceWorkerRegistration.showNotification() - Web APIs
the default is false.
...if this value is absent or false, the desktop version of chrome will auto-minimize notifications after approximately twenty seconds.
... the default value is false.
...the default value is false.
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.wrapKey() - Web APIs
*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-kw key using pbkdf2.
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-gcm key using pbkdf2.
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-cbc key using pbkdf2.
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-gcm key using pbkdf2.
TouchEvent() - Web APIs
"ctrlkey", optional and defaulting to false, of type boolean, that indicates if the ctrl key was simultaneously pressed.
... "shiftkey", optional and defaulting to false, of type boolean, that indicates if the shift key was simultaneously pressed.
... "altkey", optional and defaulting to false, of type boolean, that indicates if the alt key was simultaneously pressed.
... "metakey", optional and defaulting to false, of type boolean, that indicates if the meta key was simultaneously pressed.
Multi-touch interaction - Web APIs
// log events flag var logevents = false; // touch point cache var tpcache = new array(); register event handlers event handlers are registered for all four touch event types.
... // ev.preventdefault(); if (logevents) log("touchmove", ev, false); // to avoid too much color flashing many touchmove events are started, // don't update the background if two touch points are active if (!(ev.touches.length == 2 && ev.targettouches.length == 2)) update_background(ev); // set the target element's border to dashed to give a clear visual // indication the element received a move event.
... function end_handler(ev) { ev.preventdefault(); if (logevents) log(ev.type, ev, false); if (ev.targettouches.length == 0) { // restore background and border to original values ev.target.style.background = "white"; ev.target.style.border = "1px solid black"; } } application ui the application uses <div> elements for the touch areas and provides buttons to enable logging and clear the log.
...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.leng...
Simple color animation - Web APIs
text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : inline-block; font-size : inherit; margin : auto; padding : 0.6em; } window.addeventlistener("load", function setupanimation (evt) { "use strict" window.removeeventlistener(evt.type, setupanimation, false); // a variable to hold a timer that drives the animation.
... var button = document.queryselector("#animation-onoff"); var verb = document.queryselector("strong"); function startanimation(evt) { button.removeeventlistener(evt.type, startanimation, false); button.addeventlistener("click", stopanimation, false); verb.innerhtml="stop"; // setup animation loop by redrawing every second.
... drawanimation(); } function stopanimation(evt) { button.removeeventlistener(evt.type, stopanimation, false); button.addeventlistener("click", startanimation, false); verb.innerhtml="start"; // stop animation by clearing the timer.
... function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
A simple RTCDataChannel sample - Web APIs
connectbutton = document.getelementbyid('connectbutton'); disconnectbutton = document.getelementbyid('disconnectbutton'); sendbutton = document.getelementbyid('sendbutton'); messageinputbox = document.getelementbyid('message'); receivebox = document.getelementbyid('receivebox'); // set event listeners for user interface widgets connectbutton.addeventlistener('click', connectpeers, false); disconnectbutton.addeventlistener('click', disconnectpeers, false); sendbutton.addeventlistener('click', sendmessage, false); } this is quite straightforward.
...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.
... when the local peer experiences an open or close 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 in...
... 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() { var width = 320; // we will scale the photo width to this var height = 0; // this will be computed based on the input stream var streaming = false; var video = null; var canvas = null; var photo = null; var startbutton = null; those variables are: width whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide.
... 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.
... handle clicks on the button to capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued: startbutton.addeventlistener('click', function(ev){ takepicture(); ev.preventdefault(); }, false); this method is simple enough: it just calls our takepicture() function, defined below in the section capturing a frame from the stream, then calls event.preventdefault() on the received event to prevent the click from being handled more than once.
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.
... window.addeventlistener("load", function() { logelement = document.queryselector(".log"); dialbutton = document.queryselector("#dial"); dialbutton.addeventlistener("click", connectanddial, false); }); starting the connection process when the dial button is clicked, connectanddial() is called.
...if it does, we set hasaddtrack to true; otherwise, we set it to false.
Using IIR filters - Web APIs
the play button html looks like this: <button class="button-play" role="switch" data-playing="false" aria-pressed="false">play</button> and the click event listener starts like so: playbutton.addeventlistener('click', function() { if (this.dataset.playing === 'false') { srcnode = playsourcenode(audioctx, sample); ...
... }, false); the toggle that turns the iir filter on and off is set up in the similar way.
... first, the html: <button class="button-filter" role="switch" data-filteron="false" aria-pressed="false" aria-describedby="label" disabled></button> the filter button's click handler then connects the iirfilter up to the graph, between the source and the detination: filterbutton.addeventlistener('click', function() { if (this.dataset.filteron === 'false') { srcnode.disconnect(audioctx.destination); srcnode.connect(iirfilter).connect(audioctx.destination); ...
... }, false); frequency response we only have one method available on iirfilternode instances, getfrequencyresponse(), this allows us to see what is happening to the frequencies of the audio being passed into the filter.
Synchronous and asynchronous requests - Web APIs
var request = new xmlhttprequest(); request.open('get', '/bar/foo.txt', false); // `false` makes the request synchronous request.send(null); if (request.status === 200) { console.log(request.responsetext); } line 3 sends the request.
... mytask.js (the worker): self.onmessage = function (event) { if (event.data === "hello") { var xhr = new xmlhttprequest(); xhr.open("get", "myfile.txt", false); // synchronous request xhr.send(null); self.postmessage(xhr.responsetext); } }; note: the effect is asynchronous, because of the use of the worker.
... window.addeventlistener('unload', logdata, false); function logdata() { var client = new xmlhttprequest(); client.open("post", "/log", false); // third parameter indicates sync xhr.
... window.addeventlistener('unload', logdata, false); function logdata() { navigator.sendbeacon("/log", analyticsdata); } ...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
the default value, false, means the depth buffer will be used, if available.
...if false, the depth buffer's contents are used, if one is present.
...the default is false (depth values are used by default).
... 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.
Using the aria-invalid attribute - Accessibility
values vocabulary: false (default) no errors detected grammar a grammatical error has been detected.
...note that since the default value for aria-required is false, it is not strictly necessary to add the attribute to input.
... <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 form is submitted (though this is not necessarily recommended).
...ce of a particular character (in the real world, validation will likely be more sophisticated): function checkvalidity(aid, asearchterm, amsg){ var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); updatealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); ...
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.
... - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - checkbox simple checkbox testcases: set aria-checked="false" for unchecked both remove or set attribute for unchecked case -- also includes an invalid and required checkbox hierarchical (newly added test not in test results yet) dojo nightly build expected at behavior: screen reader should speak the accessible name followed by both the type being checkbox and the state (checked, unchecked).
... 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 presented as checked, ie exposing incorrect state for no aria-checked attribute) fail fail nvda fail on #2 -- repetitive text spoken, first checkbox toggle speaks incorrect state n/a fail fail zoom (leopard) pass n/a pass pass ...
... 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.
ARIA: feed role - Accessibility
<section role="feed" aria-busy="false"> ...
...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.
...make sure it's reset to false when the operation is complete or the changes may not become visible.
...for example, setting aria-busy to true during the update operation if needed, and then to false upon completion.
Using media queries - CSS: Cascading Style Sheets
queries involving unknown media types are always false.
... note: a style sheet with a media query attached to its <link> tag will still download even if the query returns false.
... not the not operator is used to negate a media query, returning true if the query would otherwise return false.
...} if a feature doesn't apply to the device on which the browser is running, expressions involving that media feature are always false.
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.
... aria-atomic on ancestor element event-from-input "true" | "false" (described more below) browser could not calculate this was the root cause of this event explicit user input?
...in iaccessible2, this is retrieved from the object attribute "event-from-input", which will be set to "true" or "false".
Audio and Video Delivery - Developer guides
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.
... 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 find out more, ...
...ementbyid('my-control'); function switchstate() { if (myaudio.paused == true) { myaudio.play(); mycontrol.innerhtml = "pause"; } else { myaudio.pause(); mycontrol.innerhtml = "play"; } } function checkkey(e) { if (e.keycode == 32 ) { //spacebar switchstate(); } } mycontrol.addeventlistener('click', function() { switchstate(); }, false); window.addeventlistener( "keypress", checkkey, false ); } you can try this example out here.
... app search in firefox os"> </a> <p>click image to play a video demo of dynamic app search</p> </video> var v = document.queryselector('video'), sources = v.queryselectorall('source'), lastsource = sources[sources.length-1]; lastsource.addeventlistener('error', function(ev) { var d = document.createelement('div'); d.innerhtml = v.innerhtml; v.parentnode.replacechild(d, v); }, false); audio/video javascript libraries a number of audio and video javascript libaries exist.
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.
... to represent a false value, the attribute has to be omitted altogether.
... 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="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
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.
...'click', function(e) { e.preventdefault(); }); for(var i = 0; i < ingredients.length; i++) { ingredients[i].addeventlistener('click', updatedisplay); } function updatedisplay() { var checkedcount = 0; for(var i = 0; i < ingredients.length; i++) { if(ingredients[i].checked) { checkedcount++; } } if(checkedcount === 0) { overall.checked = false; overall.indeterminate = false; } else if(checkedcount === ingredients.length) { overall.checked = true; overall.indeterminate = false; } else { overall.checked = false; overall.indeterminate = true; } } note: if you submit a form with an indeterminate checkbox, the same thing happens as if the checkbox were unchecked — no data is submitted to rep...
...however, most of the validitystates will always be false.
BigInt - JavaScript
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...
...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.
... if (0n) { console.log('hello from the if!') } else { console.log('hello from the else!') } // ↪ "hello from the else!" 0n || 12n // ↪ 12n 0n && 12n // ↪ 0n boolean(0n) // ↪ false boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true constructor bigint() creates a new bigint value.
...ver, you can implement your own tojson method if needed: bigint.prototype.tojson = function() { return this.tostring() } instead of throwing, json.stringify now produces a string like this: json.stringify(bigint(1)) // '"1"' examples calculating primes // returns true if passed bigint is a prime number function isprime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true } // takes a bigint as an argument, returns nth prime number as bigint function nthprime(nth) { let maybeprime = 2n let prime = 0n while (nth >= 0n) { if (isprime(maybeprime)) { nth-- prime = maybeprime } maybeprime++ } return prime } nthprime(20n) // ↪ 73n specifications specification ecmascript (ecma-262)the defi...
Generator.prototype.next() - JavaScript
has the value false if the iterator was able to produce the next value in the sequence.
... examples using next() 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); // generator { } page.next(); // object {value: (3) [1, 2, 3], done: false} page.next(); // object {value: (3) [4, 5, 6], done: false} page.next(); // object {value: (2) [7, 8], done: false} page.next(); // object {value: undefined, done: true} sending values to the generator in this example, next is called with a value.
... function* gen() { while (true) { let value = yield null; console.log(value); } } const g = gen(); g.next(1); // "{ value: null, done: false }" g.next(2); // 2 // "{ value: null, done: false }" specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.next' in that specification.
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 false, there will be no special handling of numeric values in strings.
...to set the value to false, you must specify in by adding "false" after the kn key.
... let numericviastr = new intl.locale("fr-latn-fr-u-kn-false"); console.log(numericstr.numeric); // prints "false" setting the numeric value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types.
Object.defineProperties() - JavaScript
defaults to false.
... defaults to false.
... defaults to false.
...eys.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.propertyIsEnumerable() - JavaScript
if the object does not have the specified property, this method returns false.
...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.
... inherited properties var a = []; a.propertyisenumerable('constructor'); // returns false function firstconstructor() { this.property = 'is not enumerable'; } 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 retu...
...rn false as they are on the prototype which // propertyisenumerable does not consider (even though the last two // are iteratable with for-in) o.propertyisenumerable('prototype'); // returns false (as of js 1.8.1/ff3.6) o.propertyisenumerable('constructor'); // returns false o.propertyisenumerable('firstmethod'); // returns false specifications specification ecmascript (ecma-262)the definition of 'object.prototype.propertyisenumerable' in that specification.
handler.setPrototypeOf() - JavaScript
return value the setprototypeof() method returns true if the [[prototype]] was successfully changed, otherwise false.
... examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an exception.
... approach 1: returning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself.
... const handlerreturnsfalse = { setprototypeof(target, newproto) { return false; } }; const newproto = {}, target = {}; const p1 = new proxy(target, handlerreturnsfalse); object.setprototypeof(p1, newproto); // throws a typeerror reflect.setprototypeof(p1, newproto); // returns false approach 2: throwing an exception the latter approach will cause any operation that attempts to mutate, to throw.
Reflect.isExtensible() - JavaScript
reflect.preventextensions(empty) reflect.isextensible(empty) // === false // sealed objects are by definition non-extensible.
... let sealed = object.seal({}) reflect.isextensible(sealed) // === false // frozen objects are also by definition non-extensible.
... let frozen = object.freeze({}) reflect.isextensible(frozen) // === false difference to object.isextensible() if the target argument to this method is not an object (a primitive), then it will cause a typeerror.
... reflect.isextensible(1) // typeerror: 1 is not an object object.isextensible(1) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.isextensible' 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.
...reflect.setprototypeof({}, null) // true // returns false if target is not extensible.
... reflect.setprototypeof(object.freeze({}), null) // false // returns false if it cause a prototype chain cycle.
... let target = {} let proto = object.create(target) reflect.setprototypeof(target, proto) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.setprototypeof' in that specification.
RegExp.prototype.test() - JavaScript
returns true or false.
...otherwise, false.
... when test() returns false, the calling regex's lastindex property will reset to 0.
... the following example demonstrates this behaviour: const regex = /foo/g; // the "global" flag is set // regex.lastindex is at 0 regex.test('foo') // true // regex.lastindex is now at 3 regex.test('foo') // false // regex.lastindex is at 0 regex.test('barfoo') // true // regex.lastindex is at 6 regex.test('foobar') //false // regex.lastindex is at 0 // (...and so on) specifications specification ecmascript (ecma-262)the definition of 'regexp.test' 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.
...for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
... 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.
TypedArray.prototype.some() - JavaScript
return value true if the callback function returns a truthy value for any array element; otherwise, false.
...otherwise, some returns false.
... function isbiggerthan10(element, index, array) { return element > 10; } new uint8array([2, 5, 8, 1, 4]).some(isbiggerthan10); // false new uint8array([12, 5, 8, 1, 4]).some(isbiggerthan10); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
... new uint8array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false new uint8array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.some' in that specification.
Conditional (ternary) operator - JavaScript
expriftrue : expriffalse parameters condition an expression whose value is used as a condition.
... expriffalse an expression which is executed if the condition is falsy (that is, has a value which can be converted to false).
... description besides false, possible falsy expressions are: null, nan, 0, the empty string (""), and undefined.
... if condition is any of these, the result of the conditional expression will be the result of executing the expression expriffalse.
<mtable> - MathML
WebMathMLElementmtable
note: the <mtable> element resets the displaystyle attribute to false.
... displaystyle a boolean value specifying whether more vertical space is used for displayed equations or, if set to false, a more compact layout is used to display formulas.
...false is default.
...false is default.
Autoplay guide for media and Web Audio APIs - Web media technologies
this is currently false by default (except in nightly builds, where it's true by default).
... if this is false, the allowedtoplay property is missing from the htmlmediaelement interface, and is thus not present on either <audio> or <video> elements.
...setting this value to false disables this capability.
...if this has been changed to false, media with an audio track will not be permitted to play even if muted.
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.
... notes a number evaluates to false if it is positive or negative zero or nan.
... a string evaluates to false if it an empty string.
Communicating using "postMessage" - Archive of obsolete content
el").panel({ onmessage: function(contentscriptmessage) { // handle message from the content script } }); message events versus user-defined events you can use message events as an alternative to user-defined events: var pagemodscript = "window.addeventlistener('mouseover', function(event) {" + " self.postmessage(event.target.tostring());" + "}, false);"; var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.on('message', function(message) { console.log('mouseover: ' + message); }); } }); the reason to prefer user-defined events is that as soon as you need to send more than one type of message, then both sending and receiving messages gets more...
... the event type in the message payload, and implement a switch function in the receiver to dispatch the message: var pagemodscript = "window.addeventlistener('mouseover', function(event) {" + " self.postmessage({" + " kind: 'mouseover'," + " element: event.target.tostring()" + " });" + "}, false);" + "window.addeventlistener('mouseout', function(event) {" + " self.postmessage({" + " kind: 'mouseout'," + " element: event.target.tostring()" + " });" + " }, false);" var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, ...
... break; case 'mouseout': console.log('mouseout: ' + message.element); break; } }); } }); implementing the same add-on with user-defined events is shorter and more readable: var pagemodscript = "window.addeventlistener('mouseover', function(event) {" + " self.port.emit('mouseover', event.target.tostring());" + "}, false);" + "window.addeventlistener('mouseout', function(event) {" + " self.port.emit('mouseout', event.target.tostring());" + "}, false);"; var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.port.on('mouseover', function(message) { console.log('mo...
frame/utils - Archive of obsolete content
defaults to false.
...defaults to false.
...defaults to false.
system/events - Archive of obsolete content
var events = require("sdk/system/events"); var { ci } = require("chrome"); function listener(event) { var channel = event.subject.queryinterface(ci.nsihttpchannel); channel.setrequestheader("user-agent", "mybrowser/1.0", false); } events.on("http-on-modify-request", listener); globals functions emit(type, event) send an event to observer service parameters type : string the event type.
...this object has three attributes: type: the event type name subject: the event subject object data: the event data string strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it.
... strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it.
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/button/toggle - Archive of obsolete content
y button", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.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.
...defaults to false.
...it's initialized to false, or the value of the checked option to the button's constructor.
Creating Event Targets - Archive of obsolete content
d: function(aitemid, afolder, aindex) { console.log("added ", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, time) { console.log("visited ", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; exports.main = function() { bookmarkservice.addobserver(bookmarkobserver, false); }; exports.onunload = function() { bookmarkservice.removeobserver(bookmarkobserver); } try running this add-on, adding and visiting bookmarks, and observing the output in the console.
...arkobserver = { onitemadded: function(aitemid, afolder, aindex) { emit(exports, "added", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, time) { emit(exports, "visited", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; bookmarkservice.addobserver(bookmarkobserver, false); exports.on = on.bind(null, exports); exports.once = once.bind(null, exports); exports.removelistener = function removelistener(type, listener) { off(exports, type, listener); }; this code implements a module which can emit added and visited events.
...temadded: function(aitemid, afolder, aindex) { emit(target, "added", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, time) { emit(target, "visited", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; bookmarkservice.addobserver(bookmarkobserver, false); } var bookmarkmanager = class({ extends: eventtarget, initialize: function initialize(options) { eventtarget.prototype.initialize.call(this, options); merge(this, options); createobserver(this); } }); exports.bookmarkmanager = bookmarkmanager; the code to interact with the places api is the same here.
Creating Reusable Modules - Archive of obsolete content
.createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string.
... .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string.
... .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string.
Displaying web content in an extension without security issues - Archive of obsolete content
so in the simplest case you would have: <iframe type="content" src="data:text/html,%3chtml%3e%3cbody%3e%3c/body%3e%3c/html%3e"/> but usually you don’t want to start with an empty document, you would rather want to load some template into the frame: var request = new xmlhttprequest(); request.open("get", "chrome://foo/content/template.html", false); request.send(null); frame.setattribute("src", "data:text/html," + encodeuricomponent(request.responsetext)); that way you can have the template in your extension but still strip it off all privileges when it is loaded in a frame.
...it won’t harm disabling everything else as well unless it is really required: frame.docshell.allowauth = false; frame.docshell.allowimages = false; frame.docshell.allowjavascript = false; frame.docshell.allowmetaredirects = false; frame.docshell.allowplugins = false; frame.docshell.allowsubframes = false; but what about interactivity, for example if you want a certain reaction to mouse clicks?
...instead, nsiscriptableunescapehtml.parsefragment() method should be used that is meant for just that scenario: var target = entry.getelementsbyclassname("description")[0]; var fragment = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(description, false, null, target); target.appendchild(fragment); this will add the html code to the specified node — minus all the potentially dangerous content.
Installing Extensions and Themes From Web Pages - Archive of obsolete content
/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.example.com/foo.xpi" iconurl="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="return install(event);">install extension!</a> let's go through this piece by piece.
... return false; this last part is the most important - the install function must return false so that when the link is clicked, only the script is run, and the link href is not navigated to.
...and your site is not in the whitelist, when the user invokes that code, updateenabled will return false because your site isn't whitelisted, and since it was updateenabled that discovered this, not a call to install, there will be no notification to the user.
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); then all we need is some persistent flag that ensures that the first run code is only run once.
...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.
... } } in this case you would need to declare the first run preference in your default preferences file, with a default value of false.
Appendix D: Loading Scripts - Archive of obsolete content
this behavior can be reversed by setting the wantsxrays parameter to false when constructing the sandbox.
... const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest", "open"); function loadscript(name, context) { // create the sandbox let sandbox = components.utils.sandbox(context, { sandboxprototype: context, wantxrays: false }); // get the caller's filename let file = components.caller.stack.filename; // strip off any prefixes added by the sub-script loader // and the trailing filename let directory = file.replace(/.* -> |[^\/]+$/g, ""); let scriptname = directory + name; // read the script let xmlhttp = xmlhttprequest("get", scriptname, false); xmlhttp.overridemimetype("text...
... function loadscript(name, context) { // create the sandbox let sandbox = components.utils.sandbox(context, { sandboxprototype: context, wantxrays: false }); // get the caller's filename let file = components.caller.stack.filename; // strip off any prefixes added by the sub-script loader // and the trailing filename let directory = file.replace(/.* -> |[^\/]+$/g, ""); services.scriptloader.loadsubscript(directory + name, sandbox, "utf-8"); } loadscript("foo.js", this); javasc...
Appendix F: Monitoring DOM changes - Archive of obsolete content
; } to { clip: rect(0px, auto, auto, auto); } \n\ }\n'; let properties = [ 'animation-duration: 0.0001s;', 'animation-name: ' + event + ' !important;' ]; properties = properties.map(function (prop) ' ' + watchnodes.namespace + prop) .join('\n'); doc.addeventlistener('animationstart', listener, false); function listener(event) { if (event.animationname == event) callback.call(this, event); } style.textcontent = ' ' + preamble + selector + '{' + properties + '}'; (doc.head || doc.documentelement).appendchild(style); // this will only work in chrome privileged code.
... style = components.utils.getweakreference(style); return function unwatch() { if (style.get()) { style.get().ownerdocument.removeeventlistener('animationstart', listener, false); style.get().parentnode.removechild(style.get()); } }; } watchnodes.namespace = 'mozcsskeyframerule' in window ?
... '-moz-' : ''; watchnodes.prefix = 'keyframe-node-inserted-' + math.floor(math.random() + 0xffffffff) + '-'; watchnodes._i = 0; } else { watchnodes = function watchnodes(selector, callback, doc) { doc = doc || document; doc.addeventlistener('domnodeinserted', listener, false); function listener(event) { if (event.target.mozmatchesselector(selector)) callback.call(this, event); } return function unwatch() { doc.removeeventlistener('domnodeinserted', listener, false); }; } } xbl xbl is similar in approach to the above animation-based method.
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.
...it's a bit smarter to have // yourself notified when to start and stop tracking therefore: svc.obs.add("weave:engine:start-tracking", this); svc.obs.add("weave:engine:stop-tracking", this); } footracker.prototype = { __proto__: tracker.prototype, _enabled: false, observe: function observe(subject, topic, data) { switch (topic) { case "weave:engine:start-tracking": if (!this._enabled) { // register event handler or observer here ...
... this._enabled = false; } break; }, onevent: function onevent() { /* here is where you'd handle the event.
JavaScript crypto - Archive of obsolete content
<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 = deregister; </script> with the above example, your web site will automaticall...
... if (typeof(crypto.version) != "undefined") { crmfobject = crypto.generatecrmfrequest( "cn=" + form.name.value, form.password.value, authenticator, keytransportcert, "setcrmfrequest();", 1024, null, "rsa-dual-use"); } return false; } function setcrmfrequest() { form.cert_request.value = crmfobject.request; form.submit(); } form.onsubmit = validate; </script> on completion of the request, the ca may submit a page that looks something like this: <!doctype html> <h2>certificate request successful</h2> <p>hit 'load' to load your certificate</p> <form name="reqform"> <p><input type=submit name="load" value="submit"></p...
...> </form> <script> /* the following values could be filled in by the server cgi */ var nickname= "mycertnickname"; var cert = "mkjflakdjfiwjflaksufklasf ..."; var forcebackup = false; function loadcertificate() { window.crypto.importusercertificates(nickname, cert, forcebackup); return false; } document.forms[0].onsubmit = loadcertificate; </script> signing text domstring signtext(domstring stringtosign, domstring caoption /* ...
Supporting private browsing mode - Archive of obsolete content
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);...
...ons 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-application"); this._os.removeobserver(this, "private-browsing"); } }, get inprivatebrowsing() { return this._inprivatebrowsing; }, get...
... asubject.queryinterface(components.interfaces.nsisupportsprbool); // if another extension has not already canceled entering the private mode if (!asubject.data) { if (adata == "exit") { // if we are leaving the private mode /* you should display some user interface here */ asubject.data = true; // cancel the operation } } }, "private-browsing-cancel-vote", false); note: a well-mannered extension should display some sort of user interface to indicate that private browsing mode will be kept on, and possibly offer the option to cancel whatever operation is preventing the extension from allowing private browsing to be shut off.
Elements - Archive of obsolete 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.
... property <!entity % property-content "(getter?,setter?)"> <!element property %property-content;> <!attlist property id id #implied name cdata #required readonly (true|false) #implied onget cdata #implied onset cdata #implied > the property element represents a single property of an implementation.
...rs cdata #implied keycode cdata #implied key cdata #implied charcode cdata #implied clickcount (1|2|3) #implied command id #implied preventdefault false|true #implied > the handler element describes a single event handler.
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="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.
Tree Widget Changes - Archive of obsolete content
this will be hidden if the column redordering is disabled using enablecolumndrag="false".
...when the user clicks the cell, the view's setcellvalue method will be called with either the value true or false.
...in this case, disable editing for that cell by setting editable to false for that cell, as in the following: <treecell value="true" editable="false"/> or, for custom views, return false from the iseditable method.
Modifying a XUL Interface - Archive of obsolete content
if false, only the node is copied, such that the copy won't have any children.
...note that while the label and value properties are strings, the checked property is a boolean property which will be set either true or false.
... note: if you're creating the checkbox dynamically and it's not yet added to the dom, you must use setattribute("checked", "false") instead, because the xbl isn't initiated yet.) example 6 : source view <button label="change" oncommand="this.nextsibling.checked = !this.nextsibling.checked;"/> <checkbox label="check for messages"/> radio buttons may be selected as well using properties, however since only one in a group may be selected at a time, the others must all be unchecked when one is checked.
XUL Questions and Answers - Archive of obsolete content
specifying window.onload function to specify a function to run when the window is loaded,add the following code between the script tags in the xul file: window.addeventlistener("load", function(e) { startup(); }, false); similarly, for onunload use the code: window.addeventlistener("unload", function(e) { shutdown(); }, false); is there an event which is called when the firefox browser is initialized?
... instead of <menulist id="abpopup"> <menupopup id="abpopup-menupopup" ref="moz-abdirectory://" datasources="rdf:addressdirectory" sortactive="true" sortdirection="ascending" sortresource="http://home.netscape.com/nc-rdf#dirtreenamesort"> <template> <rule nc:iswriteable="false"/> <rule nc:ismaillist="false"> <menuitem uri="..." label="rdf:http://home.netscape.com/nc-rdf#dirname" value="rdf:http://home.netscape.com/nc-rdf#diruri"/> </rule> <rule nc:ismaillist="true"> <menuitem uri="..." label="rdf:http://home.netscape.com/nc-rdf#dirname" value="rdf:http://home.netscape.com/nc-rdf#diruri"/> <...
.../rule> </template> </menupopup> </menulist> it should be written as follows: <menulist id="abpopup22"> <menupopup id="abpopup-menupopup" ref="moz-abmdbdirectory://abook.mab" datasources="rdf:addressdirectory" sortactive="true" sortdirection="ascending" sortresource="http://home.netscape.com/nc-rdf#dirtreenamesort"> <template> <rule nc:iswriteable="false"/> <rule nc:ismaillist="true"> <menuitem uri="..." label="rdf:http://home.netscape.com/nc-rdf#dirname" value="rdf:http://home.netscape.com/nc-rdf#diruri"/> </rule> </template> </menupopup> </menulist> drawwindow with transparent background possible?
arrowscrollbox - Archive of obsolete content
if false, the mouse must be hovered over the arrows to scroll automatically.
...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.
button - Archive of obsolete content
if this attribute is false, the checked state must be adjusted manually.
...if you wish to have different behavior for how the states are adjusted, set the autocheck attribute to false and adjust the state with a script.
...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.
menu - Archive of obsolete content
ArchiveMozillaXULmenu
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.
...the menu may be opened by setting the open property to true and closed by setting it to false.
... selected type: boolean this property's value is true if this element is selected, or false if it is not.
menupopup - Archive of obsolete content
returning false from this event handler prevents the popup from appearing.
... iscontextmenu the iscontextmenu argument should be true for context menus and false for all other types of popups.
...if attributesoverride is false, the attribute is only used if the position argument is empty.
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.
... bool a boolean set to either true or false.
... there's a special case of value === undefined, indicating that the preference does not have a user-set value (hasuservalue == false).
toolbar - Archive of obsolete content
when set to false, the default, the toolbar is visible.
...when set to false, the default, the grippy will be shown.
...otherwise, if the beforepermanent argument is false, the new item is added to the end of the toolbar.
toolbarbutton - Archive of obsolete content
if this attribute is false, the checked state must be adjusted manually.
...if you wish to have different behavior for how the states are adjusted, set the autocheck attribute to false and adjust the state with a script.
...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.
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> </treeitem> </treechildren> </tree> to make the checkbox visible on some platforms, the following styles need to be added to the stylesheet (see treecol.type).
...individual treecell elements in the column may be marked editable="false" in order to disable editing.
...if false or not specified, the user can adjust the size of the column, typically by dragging the column header with the mouse.
CommandLine - Archive of obsolete content
an nsicommandline object is passed as the first argument of the launched window: example var cmdline = window.arguments[0]; cmdline = cmdline.queryinterface(components.interfaces.nsicommandline); alert(cmdline.handleflagwithparam("test", false)); see also: chrome: command line for single instance applications of course, for a single instance application (see toolkit.singletonwindowtype for more information), the last example still applies the first time your application is launched.
...spec) { 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, "commandline-args-changed", false); }, unregister: function() { var observerservice = components.classes["@mozilla.org...
...var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(window.arguments[0], "commandline-args-changed", null); addeventlistener("unload", observer.unregister, false); finally, add a reference in your application window to the observer: chrome/content/window.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="main" title="&window.title;" windowtype="xulmine" style="width: 300px; height: 350px;" persist="screenx sc...
XULRunner tips - Archive of obsolete content
s.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("extensions.getmoreextensionsurl", "chrome://mozapps/locale/extensions/extensions.propertie...
...anager.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.opendelay", 0); pref("browser.download.manager.focuswhenstarting", false); pref("browser.download.manager.flashcount", 2); // pref("alerts.slideincrement", 1); pref("alerts.slideincrementtime", 10); pref("alerts.totalopentime", 4000); pref("alerts.height", 50); if you are missing preferences that a dialog requires, you will get the following errors: component returned failure code: 0x8000ffff (ns_error_unexpected) [nsiprefbranch.getboolpref] error: dialog has no p...
... 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.
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 plug-in ignores key events, return false, and the key events will be processed by the browser itself.
... if you don't want a special cursor, return false and the browser will use the standard arrow cursor.
The global XML object - Archive of obsolete content
observe: var element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // returns 0 element.toxmlstring(); // returns <foo><bar/></foo> xml.ignorecomments = false; element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // returns 1 element.toxmlstring(); // returns <foo><!-- my comment --><bar/></foo> ignoreprocessinginstructions true by default.
...for example var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // returns <foo><bar/></foo> xml.ignoreprocessinginstructions = false; var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // returns <foo><?process x="true"?><bar/><?process x="false"?></foo> ignorewhitespace true by default.
...ignored if prettyprinting is false.
Desktop mouse and keyboard controls - Game development
first, we'd need an event listener to listen for the pressed keys: document.addeventlistener('keydown', keydownhandler, false); document.addeventlistener('keyup', keyuphandler, false); whenever any key is pressed down, we're executing the keydownhandler function, and when press finishes we're executing the keyuphandler function, so we know when it's no longer pressed.
... to do that we'll hold the information on whether the keys we are interested in are pressed or not: var rightpressed = false; var leftpressed = false; var uppressed = false; var downpressed = false; then we will listen for the keydown and keyup events and act accordingly in both handler functions.
...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.
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
a falsy (sometimes written falsey) value is a value that is considered false when encountered in a boolean context.
... there are 8 falsy values: false the keyword false 0 the number zero -0 the number negative zero 0n bigint, when used as a boolean, follows the same rule as a number.
... examples examples of falsy values in javascript (which are coerced to false in boolean contexts, and thus bypass the if block): if (false) if (null) if (undefined) if (0) if (-0) if (0n) if (nan) if ("") the logical and operator, && if the first object is falsy, it returns that object false && "dog" // ↪ false 0 && "dog" // ↪ 0 specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that spe...
WAI-ARIA basics - Learn web development
when this is checked/unchecked, we update the text inside the hidden live region to tell screenreader users what the result of checking this checkbox is, as well as updating the aria-disabled state, and some visual indicators too: function togglemusician(bool) { let instruitem = formitems[formitems.length-1]; if(bool) { instruitem.input.disabled = false; instruitem.label.style.color = '#000'; instruitem.input.setattribute('aria-disabled', 'false'); hiddenalert.textcontent = 'instruments played field now enabled; use it to tell us what you play.'; } else { instruitem.input.disabled = true; instruitem.label.style.color = '#999'; instruitem.input.setattribute('aria-disabled', 'true'); instruitem.input.removeattribute('...
...we've updated the structure of the tabbed interface like so: <ul role="tablist"> <li class="active" role="tab" aria-selected="true" aria-setsize="3" aria-posinset="1" tabindex="0">tab 1</li> <li role="tab" aria-selected="false" aria-setsize="3" aria-posinset="2" tabindex="0">tab 2</li> <li role="tab" aria-selected="false" aria-setsize="3" aria-posinset="3" tabindex="0">tab 3</li> </ul> <div class="panels"> <article class="active-panel" role="tabpanel" aria-hidden="false"> ...
...in addition, because of the aria-hidden settings (only the non-hidden tab ever has aria-hidden="false" set), the non-hidden content is the only one you can navigate down to, meaning the selected content is easier to find.
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 false, we display a generic greeting and do the opposite.
... // 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.
Client-Server Overview - Learn web development
chrome/52.0.2743.116 safari/537.36 accept: text/html,application/xhtml+xml,application/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).
...: apache x-backend-server: developer1.webapp.scl3.mozilla.com vary: accept,cookie, accept-encoding content-type: text/html; charset=utf-8 date: wed, 07 sep 2016 00:11:31 gmt keep-alive: timeout=5, max=999 connection: keep-alive x-frame-options: deny allow: get x-cache-info: caching content-length: 41823 <!doctype html> <html lang="en-us" dir="ltr" class="redesign no-js" data-ffo-opensanslight=false data-ffo-opensans=false > <head prefix="og: http://ogp.me/ns#"> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <script>(function(d) { d.classname = d.classname.replace(/\bno-js/, ''); })(document.documentelement);</script> ...
...37.36 content-type: application/x-www-form-urlencoded accept: text/html,application/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_u...
Componentizing our React app - Learn web development
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.
... to follow the same pattern we had initially, let's give each instance of the <todo /> component an id in the format of todo-i, where i gets larger by one every time: <todo name="eat" completed={true} id="todo-0" /> <todo name="sleep" completed={false} id="todo-1" /> <todo name="repeat" completed={false} id="todo-2" /> now go back to todo.js and make use of the id prop.
... in src/index.js, make a new const beneath the final import, but above reactdom.render(): const data = [ { id: "todo-0", name: "eat", completed: true }, { id: "todo-1", name: "sleep", completed: false }, { id: "todo-2", name: "repeat", completed: false } ]; next, we'll pass data to <app /> as a prop, called tasks.
Focus management with Vue refs - Learn web development
focusoneditbutton() { const editbuttonref = this.$refs.editbutton; editbuttonref.focus(); } next, add a call to this.focusoneditbutton() at the end of the itemedited() and editcancelled() methods: itemedited(newitemname) { this.$emit("item-edited", newitemname); this.isediting = false; this.focusoneditbutton(); }, editcancelled() { this.isediting = false; this.focusoneditbutton(); }, try editing and then saving/cancelling a to-do item via your keyboard.
... you might now be thinking "hey, don’t we set isediting=false before we try to access the ref, so therefore shouldn't the v-if now be displaying the button?” this is where the virtual dom comes into play.
... because vue is trying to optimize and batch changes, it won't immediately update the dom when we set isediting to false.
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.
Adding a new event
if acopytargets is false, don't copy its event target related members.
...therefore, super classes always set it false.
...if your event cannot be fired easy, you should add the test but canrun should return false and call todo().
Listening to events on all tabs
if any registered progress listener returns false from this method then the attempt to refresh will be blocked.
...false if awebprogress is requesting a redirection to a different uri.
...false if the refresh should be aborted.
Cross Process Object Wrappers
for example, this frame script sends a dom node to chrome when the user clicks it, as the clicked property of the third argument: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-e10s-extension-message", {}, { clicked : event.target }); }, false); in the chrome script, the dom node is now accessible through a cross process object wrapper, as a property of the objects property of the message.
...*/ var button = content.document.getelementbyid("click-me"); button.addeventlistener("mouseover", function (event) { sendasyncmessage("my-addon-message", {}, { element : event.target }); }, false); // chrome script /* load the frame script, then listen for the message.
...*/ browsermm.loadframescript("chrome://my-addon/content/frame-script.js", false); browsermm.addmessagelistener("my-addon-message", function(message) { let wrapper = message.objects.element; wrapper.addeventlistener("click", function() { console.log("they clicked"); }); }); mapping content documents to xul browsers a common pattern is to get the xul <browser> that corresponds to a content document.
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).
HTMLIFrameElement.setVisible()
on the contrary, if its visible state is set to false, it has low priority over the resources it needs.
...however, if the visible state is set to false, window.requestanimationframe will be called only when there are free resources to do it.
... parameters visible a boolean that indicates if the browser <iframe> visible state is true or false.
Addon
foreigninstall read only boolean true or false depending on whether the add-on is a third party add-on installation or not.
... iscompatible read only boolean true or false depending on whether the add-on is compatible with the current application version and platform version.
... isplatformcompatible read only boolean true or false depending on whether the add-on is compatible with the current operating system.
InstallListener
a listener may return false to cancel the download.
...a listener may return false to cancel the download.
...a listener may return false to cancel the install.
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.
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.
...nctrue = myworker.post('resolvetest', [true]); promise_domyfunctrue.then( function(aval) { console.log('fullfilled - promise_domyfunctrue - ', aval); }, function(areason) { console.error('rejected - promise_domyfunctrue - ', areason); } ).catch( function(acaught) { console.error('caught - promise_domyfunctrue - ', 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_domyfunctrue - " "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.
Sqlite.jsm
here is an example: components.utils.import("resource://gre/modules/sqlite.jsm"); try { const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); // connection is the opened sqlite connection (see below for api).
... it is possible to automatically close the connection when the browser is closed with the shutdown hook: const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); try { sqlite.shutdown.addblocker("my connection closing", async () => await conn.close()); } catch (e) { // it's too late to block shutdown, just close the connection.
... these functions receive the following arguments: readonly (optional) if true the clone will be read-only, default is false.
PR_ASSERT
terminates execution when a given expression is false.
... syntax #include <prlog.h> void pr_assert ( expression ); parameters the macro has this parameter: expression any valid c language expression that evaluates to true or false.
...when the result is zero (false) the application terminates; otherwise the application continues.
PR_STATIC_ASSERT
prevents code from compiling when an expression has the value false at compile time.
... syntax #include <prlog.h> pr_static_assert ( expression ); parameters the macro has this parameter: expression any valid expression which evaluates at compile-time to true or false.
...when the result is zero (false) program compilation will fail with a compiler error; otherwise compilation completes successfully.
NSS Sample Code sample5
ectpublickeyinfo; char *pvtkstr = base64_encoded_privatekeyinfo; secitem der; secitem nickname; pk11slotinfo *slot = null; /* initialize nss * you need to explicitly authenticate to the internal token if you use * nss_init insteadf of nss_nodb_init * invoke this after getting the internal token handle * pk11_authenticate(slot, pr_false, null); */ rv = nss_nodb_init("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_geterror()); goto cleanup; } /* get internal slot */ slot = pk11_getinternalkeyslot(); if (slot == null) { fprintf(stderr, "couldn't find slot (err %d)\n", pr_geterror()); goto cleanup; } rv = atob_convertasciitoitem(&der, pubk...
...str); if (rv!= secsuccess) { fprintf(stderr, "atob_convertasciitoitem failed %d\n", pr_geterror()); goto cleanup; } spki = seckey_decodedersubjectpublickeyinfo(&der); secitem_freeitem(&der, pr_false); pubkey = seckey_extractpublickey(spki); if (pubkey == null) { fprintf(stderr, "couldn't extract public key (err %d)\n", pr_geterror()); goto cleanup; } modulus_len = seckey_publickeystrength(pubkey); fprintf(stderr, "public key modulus %d bytes\n", modulus_len); buf1 = (char *)malloc(modulus_len); buf2 = (char *)malloc(modulus_len); /* initialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'a'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "buffer being encrypted = \n%s\n", buf1); /* encrypt buf1, result will be in buf2 *...
... * 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, b...
NSS PKCS11 Functions
if the slot is implemented in software, pr_false.
...if token is disabled or missing, pr_false.
...otherwise, pr_false.
pkfnc.html
if the slot is implemented in software, pr_false.
... if token is disabled or missing, pr_false.
... otherwise, pr_false.
Hacking Tips
│ auto funcptr = js_data_to_func_ptr(exportfuncptr, codebase() + func.entryoffset()); │ if (!call_generated_2(funcptr, exportargs.begin(), &tlsdata_)) │ return false; after it's set, x/64i funcptr will show you the trampoline code.
... for (; iter != current->end(); iter++) { ionspew(ionspew_codegen, "instruction %s", iter->opname()); […] masm.store16(imm32(iter->id()), address(stackpointer, -8)); // added if (!iter->accept(this)) return false; […] } this modification will add an instruction which abuse the stack pointer to store an immediate value (the lir id) to a location which would never be generated by any sane compiler.
...the other being disable this check in "about:config", by temporarily switching "security.fileuri.strict_origin_policy" to false note 2: the files can be very big and take a long time to load in the browser.
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.istrue(), 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), val.setnumber(dou...
...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.
... js type jsval type tests jsval constants and constructors jsval accessors null jsval_is_null(v) jsval_null undefined jsval_is_void(v) jsval_void boolean jsval_is_boolean(v) jsval_true, jsval_false, boolean_to_jsval(b) jsval_to_boolean(v) number jsval_is_number(v), jsval_is_int(v), jsval_is_double(v) jsval_zero, jsval_one, int_to_jsval(i), double_to_jsval(d) jsval_to_int(v), jsval_to_double(v) string jsval_is_string(v) string_to_jsval(str) jsval_to_string(v), js_getstringchars(str), js_getstringlength(str) object !jsval_is_primitive(v) o...
JSAutoByteString
examples use constructor arguments { jsstring *str = js::tostring(cx, strval); if (!str) return false; jsautobytestring bytes(cx, str); /* calls js_encodestring internally */ if (!bytes) return false; /* ...do something with bytes...
...*/ } use method to encode string { js::rootedstring str(cx, js::tostring(cx, strval)); if (!str) return false; jsautobytestring bytes; if (!bytes.encodeutf8(cx, str)) /* calls js_encodestringtoutf8 internally */ return false; /* ...do something with bytes...
...*/ } take ownership of other buffer { char *buff = cx->pod_malloc<char>(length + 1); if (!buff) return false; memcpy(buff, other_buff, length + 1) jsautobytestring bytes; bytes.initbytes(buff); /* ...do something with bytes...
JSVAL_TO_BOOLEAN
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.
...if the property is not found on obj, this sets *foundp to false and returns true (to indicate that no error occurred).
... if the search fails with an error or exception, this returns false.
JS_DeleteElement2
on success, *succeeded receives false if the property was not deleted because it is permanent and true otherwise.
...otherwise it returns false and the value of *succeeded is undefined.
... for javascript 1.2 and earlier, if deletion fails because the property is permanent, js_deleteelement2 reports the error and returns false.
JS_EncodeCharacters
*/ size_t dstlen = 0; if (!js_encodecharacters(cx, src, srclen, null, &dstlen)) return js_false; /* allocate.
... */ char *dst = (char *) js_malloc(cx, dstlen); if (dst == null) return js_false; /* convert characters to bytes.
...otherwise it reports an error and returns js_false.
JS_GetPropertyAttributes
if no error occurs, *foundp receives js_true if the specified property is found and js_false if it is not found.
... if an error occurs, the return value is js_false, and the values left in *attrsp and *foundp are unspecified.
... if obj does not have the specified property, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false.
JS_HasElement
on success, it stores true to *foundp, false otherwise.
...if not, it sets *foundp to false and returns true (to indicate no error occurred).
... if the search fails with an error or exception, js_haselement returns false, and the value left in *foundp is undefined.
JS_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 object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred).
... if an error occurs during the search, the function returns false, and the value of *foundp is undefined.
JS_HasProperty
on success, js_hasproperty stores true in this variable if obj has a property with the given name, and false if not.
...if the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred).
... if an error occurs during the search, the function returns false, and the value of *foundp is undefined.
JS_ResolveStandardClass
false otherwise.
...if id does not name a standard class or a top-level property induced by initializing a standard class, store false in *resolved and just return true.
... return false on error, as usual for bool result-typed api entry points.
JS_SetPropertyAttributes
if js_setpropertyattributes cannot locate an object with the specified property, it returns js_false, and the value left in *foundp is undefined.
... if the specified property or the specified object does not exist, foundp is set to js_false.
...if not, it returns js_false.
XPCOM array guide
MozillaTechXPCOMGuideArrays
can or should be modified, then use nsimutablearray: // array is read-only because it uses nsiarray void printsize(nsiarray* elements) { pruint32 count; elements->getlength(&count); printf("there are %d elements.\n", count); } // using nsimutablearray, so callee may modify void tweakarray(nsimutablearray* elements) { elements->removeelementat(0); elements->appendelement(newelement, pr_false); } while it is usually possible to call queryinterface on an nsiarray to get access to the nsimutablearray interface, this is against convention and it should be avoided.
... *elements->removeelementat(0); *elements->appendelement(newelement, pr_false); } in-place enumeration when accessing all members of an nsiarray, in-place enumeration is preferred over indexed access.
...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; } ...
Finishing the Component
if these two strings do not match, then the component returns return false and blocks the load.
... *_retval = pr_false; nsresult rv; nscomptr<nsiservicemanager> servman; rv = ns_getservicemanager(getter_addrefs(servman)); if (ns_failed(rv)) return rv; nscomptr<nsiioservice> mioservice; // get a pointer to the ioservice rv = servman->getservicebycontractid("@mozilla.org/network/io-service;1", ns_get_iid(nsiioservice), ...
... getter_addrefs(mioservice)); if (ns_failed(rv)) return rv; urlnode* node = mrooturlnode; prbool match = pr_false; while (node) { nscomptr<nsiuri> uri; nsembedcstring urlstring(node->urlstring); rv = mioservice->newuri(urlstring, nsnull, nsnull, getter_addrefs(uri)); // if anything bad happens, just abort if (ns_failed(rv)) return rv; nsembedcstring host; uri->gethost(host); if (strcmp(hosttoload.get(), host.get()) == 0) { // match found.
Mozilla internal string guide
ause 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.
...the return value is pr_true or pr_false, indicating whether or not the string was found.
... these versions return 'false' instead of aborting if allocation fails .
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?
...rue; }, 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.Sandbox
if the sandbox interacts with untrusted content this should be set to false when possible to further reduce possible attack surface.
...default: false.
... var sandboxscript = 'alert($)'; var options = { sandboxprototype: content, wantxrays: false // only set this to false if you need direct access to the page's javascript.
IAccessibleTableCell
return value s_false if there is no header, [out] values are null and 0 respectively.
...[propget] hresult isselected( [out] boolean isselected ); parameters isselected returns true if the specified cell is selected and false otherwise.
... return value s_false if there is no header, [out] values are null and 0 respectively.
inIDOMUtils
in particular, this will be false if certain css white-space styles are in effect.
... 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.
mozIStorageVacuumParticipant
return value return true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed.
... you may wish to return false, for example, if you're in the middle of an operation that you don't want to (or can't) interrupt.
...void onendvacuum( in boolean asucceeded ); parameters asucceeded true if the vacuum operation was successful, or false if it wasn't successful.
nsIApplicationCacheChannel
the default value is false.
... loadedfromapplicationcache prbool true if the resource was loaded from the application cache, otherwise false.
... this value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback.
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.
nsICacheSession
if false, expired entries will be returned (useful for offline mode and clients, such as http, that can update the valid lifetime of cached content).
...if blockingmode is set to false, it will return ns_error_cache_wait_for_validation rather than block when another descriptor has been given write access but hasn't validated the entry yet.
...blockingmode true or false value to turn blocking mode for calling the thread to on/off respectively.
nsIClipboard
otherwise it returns false.
...otherwise it returns false.
...otherwise it returns false.
nsIDocShell
note: starting in gecko 8.0, isactive is false for documents in minimized windows.
... top should be true for the toplevel docshell that is being restored; it will be set to false when this method is called for child docshells.
...return value returns true if the docshell is being destroyed, false otherwise.
nsILocalFileMac
if followlinks is false, returns the unresolved alias file.
...if followlinks is false, returns the unresolved alias file.
...if followlinks is false, returns the unresolved alias file.
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.
...if false, login saving is disabled.
nsIMemory
if false, the flush will be scheduled to happen when the app is idle.
...otherwise false.
... note: from gecko 2.0 always returns false.
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
if false mark as undread.
...if false remove flag.
...if false mark as not having attachments.
nsINavHistoryService
return value returns true if this uri would be added to the history, otherwise returns false.
...this will be "0" if the uri is not valid for adding to history (canadduri = false).
...if ownsweak is false, the history service will keep an owning reference to the observer.
nsIParentalControlsService
aflag pass true if the event was blocked or false if it was allowed.
... return value true if the block was successfully overridden, otherwise false.
... return value true if the block was successfully overridden, otherwise false.
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.
nsISelection
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.
nsISessionStore
will always be false when in private browsing mode.
... if the preference browser.sessionstate.enabled is false when this method is called, then you will get an exception about "awindows[i] has no properties".
...if it's false, the tabs in astate are added to the tabs already in the window.
nsITaskbarPreviewButton
this is false by default.
...if false, the button doesn't participate in the layout of buttons underneath the preview.
... this is false by default.
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
since other threads may add events to the current thread, it's possible that by the time this method returns, the event queue may no longer be empty, even if a false result is reported.
...if false, this method returns immediately if the queue is empty.
... return value returns true if an event was processed, or false if there were no pending events.
nsIURI
return value true if the two uris represent the same location; otherwise false.
... return value true if the two uris represent the same location; otherwise false.
... return value true if the uri is for the specified scheme; otherwise false.
nsIXPCScriptable
implementations may skip writing to *_retval unless they want to return pr_false.
... 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.
Mail and RDF
gaccounts:/ +-- 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.netscape.com/nc-rdf#messagechild --> | | imap_message://alecf@imap.mywork.com/inbox#2 | +-- http://home.netscape.com/nc-rdf#messagechild --> | | imap_message://alecf@imap.mywork.com/inbox#3 | +-...
... +-- 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://home.netscape.com/nc-rdf#messagechild --> | mailbox_message://alecf@pop.mywork.com/inbox#2 | etc...
... an example of how this might work inside the datasource: var msgcountarc = rdf.getresource("http://home.netscape.com/nc-rdf#totalmessages"); function gettarget(target, property, unused) { var folder = target.queryinterface(components.interfaces.nsimsgfolder); if (property == msgcountarc) { var msgcount = folder.gettotalmessages(false); var result = rdf.getliteral(msgcount.tostring()); return result; } } asynchronously notifying rdf when a mail object's data changes and the data is reflected in rdf by notifying all of the observers that rdf has registered with the datasource.
Adding items to the Folder Pane
the following code snippet listens for that 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.
...first, our "numbers" container looks like this: let containerrow = { _numbers: 3, id: "numbers-main-container", text: "numbers", level: 0, open: false, _children: null, get children() { if (!this._children) { this._children = []; for (var i = 1; i <= this._numbers; i++) this._children.push(new numberrow(i)); } return this._children; }, getproperties: function gne_getprops() { // put your css attributes here }, command: function gne_command() { ...
...tservice) .alert(window, null, this.text); } }; second, our child items (the numbers 1, 2, and 3) are copies of the following prototype: function numberrow(anumber) { this._number = anumber; } numberrow.prototype = { get id() { return "numbers-child-row-" + this._number; }, get text() { return this._number; }, level: 1, open: false, children: [], getproperties: function gne_kid_getprops() {}, // no-op command: function gne_kid_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.text); } }; putting it a...
Type conversion
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()); // 'false' mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' mystruct.v = 0; console.log(mystruct.v.tostring()); // 'false' mystruct.v = 10; // thr...
...ows 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(mystru...
..."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 (only if fits to the size) parse src as base-10 or base-16 string ...
URLs - Plugins
to post data from a memory buffer, set the flag file to false, the buffer buf to the data to post, and len to the length of the buffer.
... char* ppostdata = "content-type:\tapplication/x-www-form-urlencoded\ncontent-length:\t17\n\nname=aaashun@gmail.com\n"; uint32 npostdatalen = (uint32)strlen(ppostdata); npn_posturl(npinstance, "http://www.baidu.com","_blank", npostdatalen, ppostdata, false); uploading files to an ftp server plug-ins can use npn_posturl or npn_posturlnotify to upload files to a remote server using ftp.
... char* mydata = "\nhi fred, this is a message from my plug-in!"; uint32 mylength = strlen(mydata) + 1; err = npn_posturlnotify(instance, "mailto:fred@example.com", null, mylength, mydata, false); the example starts by defining the mail message, mydata, and its length, mylength.
Waterfall - Firefox Developer Tools
ode 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 console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.
... for example, consider code like this: var timerbutton = document.getelementbyid("timer"); timerbutton.addeventlistener("click", handleclick, false); function handleclick() { console.time("timer"); runtimer(1000).then(timerfinished); } function timerfinished() { console.timeend("timer"); console.log("ready!"); } function runtimer(t) { return new promise(function(resolve) { settimeout(resolve, t); }); } the waterfall will display a marker for the period between time() and timeend(), and if you select it, you'll see the asy...
...nction 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: ...
Attr - Web APIs
WebAPIAttr
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.
... hasattributes() obsolete since gecko 21.0 this method now always returns false.
... haschildnodes() this method now always returns false.
AudioTrack.enabled - Web APIs
if the track is disabled by setting enabled to false, the track is muted and does not produce audio.
... 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.
... setting enabled to false effectively mutes the audio track, preventing it from contributing to the media's audio performance.
CSS.registerProperty() - Web APIs
inherits a boolean value defining whether the defined property should be inherited (true), or not (false).
... defaults to false.
... examples the following will register a custom property, --my-color, using registerproperty(), as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); in this example, the custom property --my-color has been registered using the syntax <color> .
Using the CSS properties and values API - Web APIs
css.registerproperty the following will register a css custom properties, --my-prop, using css.registerproperty, as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-prop', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); @property the same registration can take place in css.
... the following will register a css custom properties, --my-prop, using @property, as a color, give it a default value, and have it not inherit its value: @property --my-prop { syntax: '<color>'; inherits: false; initial-value: #c0ffee; } using registered custom properties one of the advantages of registering a property is that the browser now knows how it should handle your custom property through things like transitions!
...istered { --unregistered: #c0ffee; background-image: linear-gradient(to right, #fff, var(--unregistered)); transition: --unregistered 1s ease-in-out; } .unregistered:hover, .unregistered:focus { --unregistered: #b4d455; } button { height: 40vh; display: block; width: 100%; font-size: 3vw; } window.css.registerproperty({ name: '--registered', syntax: '<color>', inherits: false, initialvalue: 'red', }); while not functionally accurate, a good way to think about the difference between the unregistered property in the above example and the registered property is the difference between a <custom-ident> and a number when trying to animate height.
Cache.keys() - Web APIs
WebAPICachekeys
it defaults to false.
... 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.
...it defaults to false.
Cache.matchAll() - Web APIs
WebAPICachematchAll
it defaults to false.
... 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.
...it defaults to false.
CacheStorage.match() - Web APIs
it defaults to false.
... 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.
...it defaults to false.
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).
...set this property to false to retain the pixels' sharpness.
...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' in that specification.
console.assert() - Web APIs
WebAPIConsoleassert
the console.assert() method writes an error message to the console if the assertion is false.
...if the assertion is false, the message is written to the console.
... console.log('the word is %s', 'foo'); // output: the word is foo ...the use of such a string does not currently work as intended as a parameter for console.assert in all browsers: console.assert(false, 'the word is %s', 'foo'); // correct output in node.js and some browsers // (e.g.
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.
... reportvalidity() htmlformelement method checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available.
ConvolverNode.normalize - Web APIs
if normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response.
... syntax var audioctx = new audiocontext(); var convolver = audioctx.createconvolver(); convolver.normalize = false; value a boolean.
... convolver.normalize = false; // must be set before the buffer, to take effect convolver.buffer = concerthallbuffer; specifications specification status comment web audio apithe definition of 'normalize' in that specification.
DOMTokenList.replace() - Web APIs
if the first token doesn't exist, replace() returns false immediately, without adding the new token to the token list.
... return value a boolean value, which is true if oldtoken was successfully replaced, or false if not.
...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.
Document: drag event - Web APIs
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; } javascript var dragged; /* events fired on the draggable target */ document.addeventlistener("drag", function(event) { }, false); document.addeventlistener("dragstart", function(event) { // store a ref.
... on the dragged elem dragged = event.target; // make it half transparent event.target.style.opacity = .5; }, false); document.addeventlistener("dragend", function(event) { // reset the transparency event.target.style.opacity = ""; }, false); /* events fired on the drop targets */ document.addeventlistener("dragover", function(event) { // prevent default to allow drop event.preventdefault(); }, false); document.addeventlistener("dragenter", function(event) { // highlight potential drop target when the draggable element enters it if (event.target.classname == "dropzone") { event.target.style.background = "purple"; } }, false); document.addeventlistener("dragleave", function(event) { // reset background of potential drop target when the draggable element leaves it ...
...if (event.target.classname == "dropzone") { event.target.style.background = ""; } }, false); document.addeventlistener("drop", function(event) { // prevent default action (open as link for some elements) event.preventdefault(); // move dragged elem to the selected drop target if (event.target.classname == "dropzone") { event.target.style.background = ""; dragged.parentnode.removechild( dragged ); event.target.appendchild( dragged ); } }, false); specifications specification status comment html living standardthe definition of 'drag event' in that specification.
Document.queryCommandEnabled() - Web APIs
return value returns a boolean which is true if the command is enabled and false if the command isn't.
... the 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action.
... example var flg = document.querycommandenabled("selectall"); if(flg) { document.execcommand("selectall", false, null); // command is enabled, run it } specifications specification status comment execcommand ...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
as another example, if you have a certain subset of elements that you want to do something to based on whether they are empty (have no child nodes) or not, you could check whether each element is empty using something like node.haschildnodes(), but again, if any target elements contain text nodes, you could end up with false results.
... * * @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.
Element: mousedown event - Web APIs
the mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isdrawing to false.
... html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the 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.
...wn', 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 ui eventsthe definition of 'mousedown' in that specification.
Element: mousemove event - Web APIs
the mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isdrawing to false.
... html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the 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.
...wn', 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 ui eventsthe definition of 'mousemove' in that specification.
Element: mouseup event - Web APIs
the mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isdrawing to false.
... html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the 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.
...wn', 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 ui eventsthe definition of 'mouseup' in that specification.
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.
...<head> <title>mouse capture example</title> <style type="text/css"> #mybutton { border: solid black 1px; color: black; padding: 2px; box-shadow: black 2px 2px; } </style> <script type="text/javascript"> function init() { var btn = document.getelementbyid("mybutton"); if (btn.setcapture) { btn.addeventlistener("mousedown", mousedown, false); btn.addeventlistener("mouseup", mouseup, false); } else { document.getelementbyid("output").innerhtml = "sorry, there appears to be no setcapture support on this browser"; } } function mousedown(e) { e.target.setcapture(); e.target.addeventlistener("mousemove", mousemoved, false); } function mouseup(e) { e.target.removeev...
...entlistener("mousemove", mousemoved, false); } function mousemoved(e) { var output = document.getelementbyid("output"); output.innerhtml = "position: " + e.clientx + ", " + e.clienty; } </script> </head> <body onload="init()"> <p>this is an example of how to use mouse capture on elements in gecko 2.0.</p> <p><a id="mybutton" href="#">test me</a></p> <div id="output">no events yet</div> </body> </html> view live examples notes the element may not be scrolled completely to the top or bottom, depending on the layout of other elements.
Event.eventPhase - Web APIs
WebAPIEventeventPhase
if event.bubbles is false, processing the event is finished after this phase is complete.
...id="chcapture" /> <label for="chcapture">use capturing</label> <div id="d1">d1 <div id="d2">d2 <div id="d3">d3 <div id="d4">d4</div> </div> </div> </div> <div id="divinfo"></div> css div { margin: 20px; padding: 4px; border: thin black solid; } #divinfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; } javascript let clear = false, divinfo = null, divs = null, usecapture = false; window.onload = function () { divinfo = document.getelementbyid('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 ?
FormDataEvent() - Web APIs
the default is false.
...the default is false.
...the default is false.
Fullscreen API - Web APIs
this is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported).
... 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.
... document.addeventlistener("keypress", function(e) { if (e.keycode === 13) { togglefullscreen(); } }, false); toggling full-screen mode this code is called by the event handler above when the user hits the enter key.
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).
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.
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.
...it is up to the programmer to decide how to respond to false.
...when false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
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.
...= lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ...
... for androidsafari on iossamsung internetcompletechrome full support 1edge full support 12firefox full support yesie full support 8notes full support 8notes notes ie reports false for broken images.opera full support yessafari full support yeswebview android full support yeschrome android full support yesfirefox android full support yesopera android ...
HTMLMediaElement: play event - Web APIs
the play event is fired when the paused property is changed from true to false, as a result of the play method, or the autoplay attribute.
... using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('play', (event) => { console.log('the boolean paused property is now false.
... either the ' + 'play() method was called or the autoplay attribute was toggled.'); }); using the onplay event handler property: const video = document.queryselector('video'); video.onplay = (event) => { console.log('the boolean paused property is now false.
HTMLMediaElement - Web APIs
true if the audio is muted and false otherwise.
...if set to false, the pitch will adjust to the speed of the audio.
... 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.
Option() - Web APIs
if this is not specified, a default value of false is used.
... selected optional a boolean that sets the option's selected state; the default is false (not selected).
...nd options with different parameters /* assuming we have the following html <select id="s"> <option>first</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="">o...
IDBIndex.multiEntry - Web APIs
this method takes an optional options parameter whose multientry property is set to true/false.
... false there is one record for each key that is an array.
... the multi-entry status of the index is logged to the console: it should be returned as false.
MediaCapabilitiesInfo - Web APIs
otherwise, it is false.
... 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.
...once every track has ended, the stream's active property becomes false.
... syntax var isactive = mediastream.active; value a boolean value which is true if the stream is currently active; otherwise, the value is false.
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.
... the default value is false.
... subtree lets you specify whether to watch the target node and all of its descendants (true), or just the target node (false).
MutationObserverInit.childList - Web APIs
if childlist is false (the default), adding or removing new nodes does not trigger mutation callbacks.
... 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..
... if subtree is false, only the node indicated by the observer's target node is monitored for changes.
Notification.Notification() - Web APIs
the default is false, which means they won't be notified.
...the default value is false.
...the default is false, which means it won't be silent.
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.
... target.addeventlistener('pointerdown', function(event) { if (event.isprimary) process_primary_pointer(event); else process_secondary_pointer(event); }, false); specifications specification status comment pointer events – level 2the definition of 'isprimary' in that specification.
Multi-touch interaction - Web APIs
// log events flag var logevents = false; // event caches, one per touch target var evcache1 = new array(); var evcache2 = new array(); var evcache3 = new array(); register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
... // log events flag var logevents = false; function enablelog(ev) { logevents = logevents ?
... 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 = ""; } ...
RTCPeerConnection.createDataChannel() - Web APIs
t 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).
... negotiated optional by default (false), data channels are negotiated in-band, where one side calls createdatachannel, and the other side listens to the rtcdatachannelevent event using the ondatachannel eventhandler .
...default: false.
Range.collapse() - Web APIs
WebAPIRangecollapse
syntax range.collapse(tostart); parameters tostart optional a boolean value: true collapses the range to its start, false to its end.
... if omitted, it defaults to false .
... living standard the parameter is now optional and default to false.
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.
...occasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
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.
... the speechrecognitionresult.isfinal property is false.) speechrecognition.maxalternatives sets the maximum number of speechrecognitionalternatives provided per result.
...occasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } recognition.onresult = function(event) { var color = event.results[0][0].transcript; di...
SubtleCrypto.deriveKey() - Web APIs
/* derive an aes key, given: - our ecdh private key - their ecdh public key */ function derivesecretkey(privatekey, publickey) { return window.crypto.subtle.derivekey( { name: "ecdh", public: publickey }, privatekey, { name: "aes-gcm", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agreesharedsecretkey() { // generate 2 ecdh key pairs: one for alice and one for bob // in more normal usage, they would generate their key pairs // separately and exchange public keys securely let aliceskeypair = await window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivekey"...
...] ); let bobskeypair = await window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivekey"] ); // alice then generates a secret key using her private key and bob's public key.
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", 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...
TouchEvent.altKey - Web APIs
WebAPITouchEventaltKey
otherwise, it is false.
... 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.
... someelement.addeventlistener('touchstart', function(e) { // log the state of this event's modifier keys console.log("altkey = " + e.altkey); console.log("ctrlkey = " + e.ctrlkey); console.log("metakey = " + e.metakey); console.log("shiftkey = " + e.shiftkey); }, false); specifications specification status comment touch events – level 2 draft non-stable version.
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.
WebGLRenderingContext.makeXRCompatible() - Web APIs
javascript the code that handles starting up graphics, switching to vr mode, and so forth looks like this: const outputcanvas = document.queryselector(".output-canvas"); const gl = outputcanvas.getcontext("webgl"); let xrsession = null; let usingxr = false; let currentscene = "scene1"; 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 rest...
..., "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 other button was clicked, we ensure that xrsession is null and clear usingxr to false.
WebGLRenderingContext.sampleCoverage() - Web APIs
the default value is false.
... gl.enable(gl.sample_coverage); gl.samplecoverage(0.5, false); to check the sample coverage values, query the sample_coverage_value and sample_coverage_invert constants.
... gl.getparameter(gl.sample_coverage_value); // 0.5 gl.getparameter(gl.sample_coverage_invert); // false specifications specification status comment webgl 1.0the definition of 'samplecoverage' in that specification.
Clearing by clicking - Web APIs
window.removeeventlistener(evt.type, setupwebgl, false); // adding the same click event handler to both canvas and // button.
... var canvas = document.queryselector("#canvas-view"); var button = document.queryselector("#color-switcher"); canvas.addeventlistener("click", switchcolor, false); button.addeventlistener("click", switchcolor, false); // a variable to hold the webglrenderingcontext.
... function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Color masking - Web APIs
ck; font-family : serif; font-size : inherit; font-weight : 900; color : white; margin : auto; padding : 0.6em 1.2em; } #red-toggle { background-color : red; } #green-toggle { background-color : green; } #blue-toggle { background-color : blue; } window.addeventlistener("load", function setupanimation (evt) { "use strict" window.removeeventlistener(evt.type, setupanimation, false); var canvas = document.queryselector("canvas"); var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); var timer = setin...
...terval(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.
Scissor animation - Web APIs
does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } ;(function(){ "use strict" window.addeventlistener("load", setupanimation, false); // variables to hold the webgl context, and the color and // position of animated squares.
... var gl, color = getrandomcolor(), position; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) return; gl.enable(gl.scissor_test); gl.clearcolor(color[0], color[1], color[2], 1.0); // unlike the browser window, vertical position in webgl is // measured from bottom to top.
... position = [0, gl.drawingbufferheight]; var button = document.queryselector("button"); var timer; function startanimation(evt) { button.removeeventlistener(evt.type, startanimation, false); button.addeventlistener("click", stopanimation, false); document.queryselector("strong").innerhtml = "stop"; timer = setinterval(drawanimation, 17); drawanimation(); } function stopanimation(evt) { button.removeeventlistener(evt.type, stopanimation, false); button.addeventlistener("click", startanimation, false); document.queryselector("strong").innerhtml = "start"; clearinterval(timer); } stopanimation({type: "click"}); } // variables to hold ...
Adding 2D content to a WebGL context - Web APIs
if that's false, we know the shader failed to compile, so show an alert with log information obtained from the compiler using gl.getshaderinfolog(), then delete the shader and return null to indicate a failure to load the shader.
... { const numcomponents = 2; // pull out 2 values per iteration const type = gl.float; // the data in the buffer is 32bit floats const normalize = false; // don't normalize const stride = 0; // how many bytes to get from one set of values to the next // 0 = use type and numcomponents above const offset = 0; // how many bytes inside the buffer to start from gl.bindbuffer(gl.array_buffer, buffers.position); gl.vertexattribpointer( programinfo.attriblocations.vertexposition, ...
... numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } // tell webgl to use our program when drawing gl.useprogram(programinfo.program); // set the shader uniforms gl.uniformmatrix4fv( programinfo.uniformlocations.projectionmatrix, false, projectionmatrix); gl.uniformmatrix4fv( programinfo.uniformlocations.modelviewmatrix, false, modelviewmatrix); { const offset = 0; const vertexcount = 4; gl.drawarrays(gl.triangle_strip, offset, vertexcount); } } the first step is to clear the canvas to our background color; then we establish the camera's perspective.
Example and tutorial: Simple synth keyboard - Web APIs
function setup() { notefreq = createnotetable(); volumecontrol.addeventlistener("change", changevolume, false); mastergainnode = audiocontext.creategain(); mastergainnode.connect(audiocontext.destination); mastergainnode.gain.value = volumecontrol.value; // create the keys; skip any that are sharp or flat; for // our purposes we don't need them.
... let keylist = object.entries(keys); let octaveelem = document.createelement("div"); octaveelem.classname = "octave"; keylist.foreach(function(key) { if (key[0].length == 1) { octaveelem.appendchild(createkey(key[0], idx, key[1])); } }); keyboard.appendchild(octaveelem); }); document.queryselector("div[data-note='b'][data-octave='5']").scrollintoview(false); sineterms = new float32array([0, 0, 1, 0, 1]); cosineterms = new float32array(sineterms.length); customwaveform = audiocontext.createperiodicwave(cosineterms, sineterms); for (i=0; i<9; i++) { osclist[i] = []; } } setup(); the table which maps note names and octaves to their frequenies is created by calling createnotetable().
... = document.createelement("div"); let labelelement = document.createelement("div"); keyelement.classname = "key"; keyelement.dataset["octave"] = octave; keyelement.dataset["note"] = note; keyelement.dataset["frequency"] = freq; labelelement.innerhtml = note + "<sub>" + octave + "</sub>"; keyelement.appendchild(labelelement); keyelement.addeventlistener("mousedown", notepressed, false); keyelement.addeventlistener("mouseup", notereleased, false); keyelement.addeventlistener("mouseover", notepressed, false); keyelement.addeventlistener("mouseleave", notereleased, false); return keyelement; } after creating the elements that will represent the key and its label, we configure the key's element by setting its class to "key" (which establishes its appearance).
window.postMessage() - Web APIs
the dispatched event otherwindow can listen for dispatched messages by executing the following javascript: window.addeventlistener("message", receivemessage, false); function receivemessage(event) { if (event.origin !== "http://example.org:8080") return; // ...
... the secret response is: rheeeeet!" } window.addeventlistener("message", receivemessage, false); /* * in the popup's scripts, running on <http://example.com>: */ // called sometime after postmessage is called function receivemessage(event) { // do we trust the sender of this message?
... the secret response " + "is: rheeeeet!", event.origin); } window.addeventlistener("message", receivemessage, false); notes any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message.
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 ...
...this test file is small and is not well-formed xml: <title>&amp;&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(callback) { if (!window.xmlhttprequest) { window.settimeout(function() { callback(false); }, 0); return; } var done = false; var xhr = new window.xmlhttprequest(); xhr.onreadystatechange = function() { if (this.readystate == 4 && !done) { done = true; callback(!!(this.responsexml && this.responsexml.title && this.responsexml.title == "&&<")); } } xhr.onabort = xhr.onerror = function() { if (!done) { done = true; callback(false); ...
... } } try { 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.
Sending and Receiving Binary Data - Web APIs
function load_binary_resource(url) { var req = new xmlhttprequest(); req.open('get', url, false); //xhr binary charset opt by marcus granado 2006 [http://mgran.blogspot.com] req.overridemimetype('text\/plain; charset=x-user-defined'); req.send(null); if (req.status != 200) return ''; return req.responsetext; } the magic happens in line 5, which overrides the mime type, forcing the browser to treat it as plain text, using a user-defined character set.
... var myarray = new arraybuffer(512); var longint8view = new uint8array(myarray); // generate some data for (var i=0; i< longint8view.length; i++) { longint8view[i] = i % 256; } var xhr = new xmlhttprequest; xhr.open("post", url, false); xhr.send(myarray); this is building a 512-byte array of 8-bit integers and sending it; you can use any binary data you'd like, of course.
...s["@mozilla.org/mime;1"] .getservice(components.interfaces.nsimimeservice); mimetype = mimeservice.gettypefromfile(file); // file is an nsifile instance } catch (oevent) { /* eat it; just use text/plain */ } // send var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); req.open('put', url, false); /* synchronous!
XRPose.emulatedPosition - Web APIs
if the position is precisely gbased on direct sensor inputs, the value is false.
... contrariwise, xr devices which can also track movement forward and backward as well as laterally—six degree of freedom (6dof) devices—don't require any information from other sources to determine the user's position, so the value of emulatedposition is false.
...a hand controller that can directly report its position would have a value of false for this property as well.
XRSystem: isSessionSupported() - Web APIs
otherwise, the promise resolves with false.
... return value a promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false.
... if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { userbutton.addeventlistener('click', onbuttonclicked); userbutton.innerhtml = 'enter xr'; userbutton.disabled = false; } }); } function onbuttonclicked() { if (!xrsession) { navigator.xr.requestsession('immersive-vr') .then((session) => { xrsession = session; // onsessionstarted() not shown for reasons of brevity and clarity.
XRView.eye - Web APIs
WebAPIXRVieweye
gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0,0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit, gl.depth_buffer_bit); for (let view of xrpose.views) { let skipview = false; if (view.eye == "left" && body.lefteye.injured) || skipview = updateinjury(body.lefteye); } else if (view.eye == "right" && body.righteye.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 vi...
... updateinjury() returns true if the eye is still injured or false if the eye has been restored to health by the function,.
... if the result is false, indicating that the eye is now healthy, we render the scene for that eye.
XRWebGLLayer() - Web APIs
antialias optional a boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false.
...the default is false.
...the default is false.
XRWebGLLayer.ignoreDepthValues - Web APIs
if the depth buffer is being used to determine the position of vertices, this property is false.
...since the xr compositor uses the depth buffer by default, this value is false unless explicitly set otherwise when creating the xrwebgllayer using its constructor, xrwebgllayer().
... usage notes when the ignoredepthvalues property is false, the xr compositor uses the values found in the depth buffer, which should be accurate for the scene, in order to potentially improve the quality or the output as well as the comfort level for the viewer.
XRWebGLLayerInit.depth - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose depth property is false will request that the new layer be created without a depth buffer.
... syntax let layerinit = { depth: false }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { depth: false }); value a boolean which can be set to false to specify that the new webgl layer should not have a depth buffer.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { depth: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.depth' in that specification.
XRWebGLLayerInit.stencil - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose stencil property is false requests that the new layer be created without a stencil buffer.
... syntax let layerinit = { stencil: false }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { stencil: false }); value a boolean which can be set to false to specify that the new webgl layer should not include a stencil buffer.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { stencil: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.stencil' in that specification.
XRWebGLLayerInit - Web APIs
antialias optional a boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false.
...the default is false.
...the default is false.
ARIA live regions - Accessibility
the possible settings are: false or true.
... the default setting is false.
... aria-atomic is not set (false by default) so that only the added or removed users should be spoken and not the entire roster each time.
Using the aria-hidden attribute - Accessibility
using aria-hidden="false" will not re-expose the element to assistive technology if any of its parents specify aria-hidden="true".
... wai-aria authoring practices 1.1 notes that aria-hidden="false" currently behaves inconsistently across browsers.
... values false (default) the element is exposed to the accessibility api.
Basic form hints - Accessibility
<h3 id="rg1_label">lunch options</h3> <ul 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> describing with aria form controls somet...
... <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.
Cross-browser audio basics - Developer guides
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.
... seeked seeked occurs when the seeking attribute changes to false.
Video player styling basics - Developer guides
'unmute' : 'mute'); } } this function is then called by the relevant event handlers: video.addeventlistener('play', function() { changebuttonstate('playpause'); }, false); video.addeventlistener('pause', function() { changebuttonstate('playpause'); }, false); stop.addeventlistener('click', function(e) { video.pause(); video.currenttime = 0; progress.value = 0; // update the play/pause button's 'data-state' which allows the correct button image to be set via css changebuttonstate('playpause'); }); mute.addeventlistener('click', function(e) { v...
... 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.
... checkvolume() is also called when the volumechange event is raised: video.addeventlistener('volumechange', function() { checkvolume(); }, false); progress bar a small change also needs to be made to the click handler for the <progress> element.
Rich-Text Editing in Mozilla - Developer guides
figure 4 : executing rich editing commands html: <button onclick="doricheditcommand('bold')" style="font-weight:bold;">b</button> javascript: function doricheditcommand(aname, aarg){ getiframedocument('editorwindow').execcommand(aname,false, aarg); document.getelementbyid('editorwindow').contentwindow.focus() } 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.innerhtml); odoc.innerhtml = ""; var opre = document.createelement("pre"); odoc.contenteditable = false; opre.id = "sourcetext"; opre.contenteditable = true; opre.appendchild(ocontent); odoc.appendchild(opre); } else { if (document.all) { odoc.innerhtml = odoc.innertext; } else { ocontent = document.createrange(); ocontent.selectnodecontents(odoc.firs...
...px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textbox #sourcetext { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editmode label { cursor: pointer; } </style> </head> <body onload="initdoc();"> <form name="compform" method="post" action="sample.php" onsubmit="if(validatemode()){this.mydoc.value=odoc.innerhtml;return true;}return false;"> <input type="hidden" name="mydoc"> <div id="toolbar1"> <select onchange="formatdoc('formatblock',this[this.selectedindex].value);this.selectedindex=0;"> <option selected>- formatting -</option> <option value="h1">title 1 &lt;h1&gt;</option> <option value="h2">title 2 &lt;h2&gt;</option> <option value="h3">title 3 &lt;h3&gt;</option> <option value="h4">title 4 &lt;h4&gt;</option> <option value=...
draggable - HTML: Hypertext Markup Language
false: the element cannot be dragged.
...a value of true or false is mandatory, and shorthand like <img draggable> is forbidden.
... the correct usage is <img draggable="false">.
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.
Details of the object model - JavaScript
note: this may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string ("").
..._.__proto__ == null; given this, you could write an instanceof function as follows: function instanceof(object, constructor) { object = object.__proto__; while (object != null) { if (object == constructor.prototype) return true; if (typeof object == 'xml') { return constructor.prototype == xml.prototype; } object = object.__proto__; } return false; } note: the implementation above checks the type of the object against "xml" in order to work around a quirk of how xml objects are represented in recent versions of javascript.
... using the instanceof function defined above, these expressions are true: instanceof(chris, engineer) instanceof(chris, workerbee) instanceof(chris, employee) instanceof(chris, object) but the following expression is false: instanceof(chris, salesperson) global information in constructors when you create constructors, you need to be careful if you set global information in the constructor.
Indexed collections - JavaScript
the simplest way to do this is as follows: let colors = ['red', 'green', 'blue'] for (let i = 0; i < colors.length; i++) { console.log(colors[i]) } if you know that none of the elements in your array evaluate to false in a boolean context—if your array consists only of dom nodes, for example—you can use a more efficient idiom: let divs = document.getelementsbytagname('div') for (let i = 0, div; div = divs[i]; i++) { /* process div in some way */ } this avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop ...
... function isnumber(value) { return typeof value === 'number' } let a1 = [1, 2, 3] console.log(a1.every(isnumber)) // logs true let a2 = [1, '2', 3] console.log(a2.every(isnumber)) // logs false some(callback[, thisobject]) returns true if callback returns true for at least one item in the array.
... function isnumber(value) { return typeof value === 'number' } let a1 = [1, 2, 3] console.log(a1.some(isnumber)) // logs true let a2 = [1, '2', 3] console.log(a2.some(isnumber)) // logs true let a3 = ['1', '2', '3'] console.log(a3.some(isnumber)) // logs false reduce(callback[, initialvalue]) applies callback(accumulator, currentvalue[, currentindex[, array]]) for each value in the array for the purpose of reducing the list of items down to a single value.
Meta programming - JavaScript
handler.preventextensions() object.preventextensions() reflect.preventextensions() object.preventextensions(proxy) only returns true if object.isextensible(proxy) is false.
... in strict mode, a false value returned from the defineproperty handler will throw a typeerror exception.
... in strict mode, a false return value from the set handler will throw a typeerror exception.
Array.prototype.filter() - JavaScript
return true to keep the element, false otherwise.
...isbigenough(value) { return value >= 10 } let filtered = [12, 5, 8, 130, 44].filter(isbigenough) // filtered is [12, 130, 44] find all prime numbers in an array the following example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log(array.filter(isprime)); // [2, 3, 5, 7, 11, 13] filtering invalid entries from json the following example uses filter() to create a filtered json of all elements with non-zero, numeric id.
... 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.
Date.prototype.toLocaleString() - JavaScript
to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocalestringsupportslocales() { try { new date().tolocalestring('i'); } catch (e) { return e instanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats.
...dezember 2012" // an application may want to use utc and make that visible options.timezone = 'utc'; options.timezonename = 'short'; console.log(date.tolocalestring('en-us', options)); // → "thursday, december 20, 2012, gmt" // sometimes even the us needs 24-hour time console.log(date.tolocalestring('en-us', { hour12: false })); // → "12/19/2012, 19:00:00" avoid comparing formatted date values to static values most of the time, the formatting returned by tolocalestring() is consistent.
... 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.
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 goin...
...g to be nan after it is coerced to a number, while the latter will return true only if the value is currently nan: isnan('hello world'); // 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.
Number.isInteger() - JavaScript
description if the target value is an integer, return true, otherwise return false.
... if the value is nan or infinity, return false.
... 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.isi...
Number.isNaN() - JavaScript
return value true if the given value is nan and its type is number; otherwise, false.
... description due to both equality operators, == and ===, evaluating to false when checking if nan is nan, the function number.isnan() has become necessary.
...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 specificati...
Object.prototype.constructor - JavaScript
changed new object(), {}, new regexp(), /(?:)/, new string(), 'test' // remains unchanged ] for (let i = 0; i < types.length; i++) { types[i].constructor = type types[i] = [types[i].constructor, types[i] instanceof type, types[i].tostring()] } console.log(types.join('\n')) this example displays the following output (comments added for reference): function type() {},false, // new array() function type() {},false, // [] function type() {},false,false // new boolean() function boolean() { [native code] },false,true // true function type() {},false,mon sep 01 2014 16:03:49 gmt+0600 // new date() function type()...
... {},false,error // new error() function type() {},false,function anonymous() { } // new function() function type() {},false,function () {} // function () {} function type() {},false,[object math] // math function type() {},false,0 // new number() function number() { [native code] },false,1 // 1 function type() {},false,[object object] // new object() function type() {},false,[object object] // {} function type() {},false,/(?:)/ // new regexp() function type() {},false,/(?:)/ ...
... // /(?:)/ function type() {},false, // new string() function string() { [native code] },false,test // 'test' changing the constructor of a function mostly this property is used for defining a function as a function-constructor with further calling it with new and prototype-inherits chain.
Object.create() - JavaScript
e new object's prototype works even better: ocn = object.create( null ); // create "null" object (same as before) object.setprototypeof(ocn, object.prototype); // set new object's prototype to the "generic" object (not standard-object) (in addition to all the string-related functions shown above, this also adds:) > ocn.valueof() // shows {} > ocn.hasownproperty("x") // shows "false" > ocn.constructor // shows "object() { [native code] }" // ...and all the rest of the properties and methods of object.prototype.
...(note that the second parameter // maps keys to *property descriptors*.) o = object.create(object.prototype, { // foo is a regular 'value property' foo: { writable: true, configurable: true, value: 'hello' }, // bar is a getter-and-setter (accessor) property bar: { configurable: false, get: function() { return 10; }, set: function(value) { console.log('setting `o.bar` to', value); } /* with es2015 accessors our code can look like this get() { return 10; }, set(value) { console.log('setting `o.bar` to', value); } */ } }); function constructor() {} o = new constructor(); // is equivalent to: o = object.create(constructor.prototype); // of ...
...o = object.create({}, { p: { value: 42 } }); // by default properties are not writable, // enumerable or configurable: o.p = 24; o.p; // 42 o.q = 12; for (var prop in o) { console.log(prop); } // 'q' delete o.p; // false // to specify an es3 property o2 = object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } }); /* is not equivalent to: this will create an object with prototype : {p: 42 } o2 = object.create({p: 42}) */ specifications specification ecmascript (ecma-262)the definition of 'object.create' in that specification.
Object.prototype.hasOwnProperty() - JavaScript
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.
...[name]); } else { console.log(name); // tostring or something else } } using hasownproperty as a property name javascript does not protect the property name hasownproperty; thus, if the possibility 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 cas...
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.
...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 specifications specification ecmascript (ecma-262)...
handler.set() - JavaScript
if the set() method returns false, and the assignment happened in strict-mode code, a typeerror will be thrown.
... in strict mode, a false return value from the set() handler will throw a typeerror exception.
... 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.
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.
... 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 specificat...
Set.prototype.delete() - JavaScript
return value returns true if value was successfully removed from myset; otherwise false.
... examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false.
... myset.has('foo'); // returns false.
Set - JavaScript
set.prototype.has(value) will return false afterwards.
...amples 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.log(myset) // logs set(4) [ 1, "so...
......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 symme...
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.
...ring.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.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.
Symbol.match - JavaScript
now, if the match symbol is set to false (or a falsy value), it indicates that the object is not intended to be used as a regular expression object.
... however, if you set symbol.match to false, the isregexp check (that uses the match property) will indicate that the object is not a regular expression object.
... 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.
WeakSet.prototype.delete() - JavaScript
false if the key is not found in the weakmap or if the key is not an object.
... examples using the delete method var ws = new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // returns false.
... ws.has(window); // returns false.
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.
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 ...
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 c...
...onsole.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.
yield* - JavaScript
function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 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.,...
... function* g3() { yield* [1, 2]; yield* '34'; yield* array.from(arguments); } const iterator = g3(5, 6); 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: 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.
... function* g4() { yield* [1, 2, 3]; return 'foo'; } function* g5() { const g4returnvalue = 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.
function* - JavaScript
the start of the function // until the first yield statement gen.next(); // 0 gen.next('pretzel'); // 1 pretzel gen.next('california'); // 2 california gen.next('mayonnaise'); // 3 mayonnaise return statement in a generator function* yieldandreturn() { yield "y"; return "r"; yield "unreachable"; } var gen = yieldandreturn() console.log(gen.next()); // { value: "y", done: false } console.log(gen.next()); // { value: "r", done: true } console.log(gen.next()); // { value: undefined, done: true } generator as an object property const someobj = { *generator () { yield 'a'; yield 'b'; } } const gen = someobj.generator() console.log(gen.next()); // { value: 'a', done: false } console.log(gen.next()); // { value: 'b', done: false } console.log(gen.next()); // ...
...{ value: undefined, done: true } generator as an object method class foo { *generator () { yield 1; yield 2; yield 3; } } const f = new foo (); const gen = f.generator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: undefined, done: true } generator as a computed property class foo { *[symbol.iterator] () { yield 1; yield 2; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } console.log(array.from(new foo)); // [ 1, 2 ] console.log(array.from(someobj)); // [ 'a', 'b' ] generators are not constructable function* f() {} var obj = new f; // throws "typeerror: f is not a con...
...structor generator defined in an expression const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false} generator example function* powers(n){ //endless loop to generate for(let current =n;; current *= n){ yield current; } } for(let power of powers(2)){ //controlling generator if(power > 32) break; console.log(power) //2 //4 //8 //16 //32 } specifications specification ecmascript (ecma-262)the definition of 'function*' in that specification.
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.
... any value that is not false, undefined, null, 0, -0, nan, or the empty string (""), and any object, including a boolean object whose value is false, is considered truthy when used as the condition.
... for example: var b = new boolean(false); if (b) // this condition is truthy examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript.
preserveAlpha - SVG: Scalable Vector Graphics
ody, 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_only_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.
... false this value indicates that the convolution will apply to all channels, including the alpha channel.
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 a null string or empty string value is given to attribute requiredfeatures, the attribute is evaluate to false.
...<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.
lang - XPath
WebXPathFunctionslang
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the lang function determines whether the context node matches the given language and returns boolean true or false.
...otherwise, false.
...if the language cannot be determined (no ancestor has an xml:lang attribute), this function will return false.
/loader - Archive of obsolete content
if (subject.wrappedjsobject === unloadsubject) console.log("i am about to unload, reason is " + reason); }}; observerservice.addobserver(observer, 'sdk:loader:destroy', false); unload the loader module exposes an unload() function that can be used to unload specific loader instance and undo changes made by modules loaded into it.
... let sandbox = sandbox({ name: 'resource:///modules/foo/bar.js', wantxrays: false, prototype: { console: { log: dump.bind(dump, 'log: '), info: dump.bind(dump, 'info: '), warn: dump.bind(dump, 'warn: '), error: dump.bind(dump, 'error: ') } } }); evaluate() evaluates code in the supplied sandbox.
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.
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)); // [] environment variable will be unset, sh...
... env.foo = null; console.log('foo' in env); // false env.bar = ''; console.log(env.bar); // undefined ...
util/match-pattern - Archive of obsolete content
r.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.
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) ...
...defaults to false.
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.
... main.js now in the lib directory open main.js and add the following code: var widgets = require('sdk/widget'); var data = require('sdk/self').data; var annotatorison = false; function toggleactivation() { annotatorison = !annotatorison; return annotatorison; } exports.main = function() { var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: 'ready', contentscriptfile: data.url('widget/widget.js') }); widget.port.on('left-click', function() { console.log('activate/deactivate'); widget.cont...
Alerts and Notifications - Archive of obsolete content
this works on windows, linux and (if growl is installed) mac os x: function popup(title, text) { try { components.classes['@mozilla.org/alerts-service;1'] .getservice(components.interfaces.nsialertsservice) .showalertnotification(null, title, text, false, '', null); } catch(e) { // prevents runtime error on platforms that don't implement nsialertsservice } } if you need to display a comparable alert on a platform that doesn't support nsialertsservice, you can do this: function popup(title, msg) { var image = null; var win = components.classes['@mozilla.org/embedcomp/window-watcher;1'] .getservice(components.in...
...terfaces.nsiwindowwatcher) .openwindow(null, 'chrome://global/content/alerts/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes', null); win.arguments = [image, title, msg, false, '']; } using notification box another way of non-modal notification and further interaction with users is using of xul elements notificationbox and notification (implicitly).
IsDefaultNamespace - Archive of obsolete content
if (att.localname === 'xmlns') { return att.value === namespaceuri; } } } if (node.parentnode) { // entityreferences may have to be skipped to get to it return isdefaultnamespace(node.parentnode, namespaceuri); } else { return false; // unknown; } case 9: // document_node return isdefaultnamespace(node.documentelement, namespaceuri); case 6: // entity_node case 12: // notation_node case 10: // document_type_node case 11: // document_fragment_node return false; // unknown case 2: // attribute_node: if (node.ownerelement ) { ...
... return isdefaultnamespace(node.ownerelement , namespaceuri); } else { return false; // unknown } default: if (node.parentnode) { // entityreferences may have to be skipped to get to it return isdefaultnamespace(node.parentnode, namespaceuri); } else { return false; // unknown } } } ...
JavaScript Debugger Service - Archive of obsolete content
jsd.scripthook = { onscriptcreated: function(script) { // your function here }, onscriptdestroyed: function(script) { // your function here } }; jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { // your function here } }; // triggered when jsd.errorhook[onerror] returns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumeratescripts({ // the enumeratescript method will be called once for every script jsd knows about enumeratescript: function(script) { // your function here } }); a simple stack trace here, we will show how to implement a simple javascript stack trace using the jsd.
...ook = components.interfaces.jsdierrorhook; var messagetype; if (flags & jsdierrorhook.report_error) messagetype = "error"; if (flags & jsdierrorhook.report_warning) messagetype = "warning"; if (flags & jsdierrorhook.report_exception) messagetype = "uncaught-exception"; if (flags & jsdierrorhook.report_strict) messagetype += "-strict"; dump(messagetype + "\n"); return false; // trigger debughook // return true; if you do not wish to trigger debughook } }; // note that debughook does not _always_ trigger when jsd.errorhook[onerror] returns false // it is not well-known why debughook sometimes fails to trigger jsd.debughook = { onexecute: function(frame, type, rv) { stacktrace = ""; for (var f = frame; f; f = f.callingframe) { stacktrace += f.script.file...
Inline options - Archive of obsolete content
ptions 1"> <menulist> <menupopup> <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 ha...
...for example: var observer = { observe: function(asubject, atopic, adata) { if (atopic == "addon-options-displayed" && adata == "my_addon@my_domain") { var doc = asubject; var control = doc.getelementbyid("myaddon-pref-control"); control.value = "test"; } } }; services.obs.addobserver(observer, "addon-options-displayed", false); // don't forget to remove your observer when your add-on is shut down.
Adding Events and Commands - Archive of obsolete content
window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); you can do something similar with the onunload event, to do any cleanup you may need.
...document.addeventlistener( "xshellogreetingevent", function(aevent) { /* do stuff*/ }, false); be careful when doing this!
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
if (nodes && key == "key") { nodes[val] = elem; continue; } var attrns = namespace(key); if (typeof val == "function") { // special case for function attributes; don't just add them as 'on...' attributes, but as events, using addeventlistener elem.addeventlistener(key.replace(/^on/, ""), val, false); } else { // note that the default namespace for xml attributes is, and should be, blank (ie.
...the following two code fragments are roughly equivalent: function clickify(elem, address) { elem.addeventlistener("click", function (event) { openwindow(address) }, false); } function clickify(elem, address) { elem.onclick = function (event) { openwindow(address) }; } multiple attributes sometimes there is a need for event listeners to appear as attributes in the dom.
Intercepting Page Loads - Archive of obsolete content
asubject.setrequestheader("referer", "http://example.com", false); } else if (re_url_to_cancel.test(url)) { // re_url_to_cancel is a regular expression.
...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.removeeventlistener("tabclose", this, false); }, handleevent : function(aevent) { l...
XPCOM Objects - Archive of obsolete content
this._prefservice = cc["@mozilla.org/preferences-service;1"].getservice(ci.nsiprefbranch); this._prefvalue = this._prefservice.getboolpref("somepreferencename"); this._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.addobserver("somepreferencename", this, false); this._prefservice.queryinterface(ci.nsiprefbranch); this is a common piece of code you'll see when initializing components or jsm that rely on preferences.
... this._prefservice.addobserver( "extensions.xulschoolhello.somepref", this, false); }, observe : function(asubject, atopic, adata) { // do stuff here.
Adding preferences to an extension - Archive of obsolete content
ockwatcher = { prefs: null, tickersymbol: "", // initialize the extension startup: function() { // register to receive notifications of preference changes this.prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice) .getbranch("extensions.stockwatcher2."); this.prefs.addobserver("", this, false); this.tickersymbol = this.prefs.getcharpref("symbol").touppercase(); this.refreshinformation(); window.setinterval(this.refreshinformation, 10*60*1000); } }, our object has two member variables.
... window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); window.addeventlistener("unload", function(e) { stockwatcher.shutdown(); }, false); design the preference dialog now that we've written all the code, we need to build the xul file for the options dialog.
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
ple </h2> <p>click the tabbed menu to dynamically load the headlines into this web page.</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('/viewsou...
...rce/catalog-new_en.xml',this);return false;\">devedge news</a> <a href=\"javascript:\" class=\"tab\" onclick=\"calldevedge('/central/css/catalog-new_en.xml',this);return false;\" title=\"css articles\">css</a> <a href=\"javascript:\" class=\"tab\" onclick=\"calldevedge('/central/xml/catalog-new_en.xml',this);return false;\" title=\"xml articles\">xml</a> <a href=\"javascript:\" class=\"tab\" onclick=\"calldevedge('/central/dom/catalog-new_en.xml ',this);return false;\" title=\"dom articles\">dom</a></span>"); } </script> <!-- ***** this represents the container ***** --> <div style="margin-left:0px;border:1px solid #dddddd;" > <div style="padding:10px;" id="container"> </div> </div> </body> </html> original document information author(s): marcio galli, netscape communications; ...
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 ' + ...
...s || err == install.reboot_needed) { if (!this.silentinstall && this.extpostinstallmessage) { install.alert(this.extpostinstallmessage); } } else { this.handleerror(err); return; } }, parsearguments: function() { // can't use string handling in install, so use if statement instead var args = install.arguments; if (args == 'p=0') { this.profileinstall = false; this.silentinstall = true; } else if (args == 'p=1') { this.profileinstall = true; this.silentinstall = true; } }, handleerror: function(err) { if (!this.silentinstall) { install.alert('error: could not install ' + this.extfullname + ' ' + this.extversion + ' (error code: ' + err + ')'); } install.cancelinstall(err); } }; xpiinstaller.install(); ...
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
isshowing boolean true if the menu is currently visible and false otherwise.
...(note that any falsey value will suffice, including undefined, null, and the empty string.
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-connection = false (allow connections without displaying a confirmation prompt.
... this can be a security risk, especially if you also set the force-local preference to false.) set up firefox for desktop on the desktop, remote debugging is enabled by a setting in the toolbox.
Frequently Asked Questions - Archive of obsolete content
when you double click on the pref you will see its value change to and from true/false, turning the native support on/off.
...to be able to use it, you must make sure the svg.enabled pref is set to false.
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.
Supporting per-window private browsing - Archive of obsolete content
function pbobserver() { /* clear private data */ } var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(pbobserver, "last-pb-context-exited", false); preventing a private session from ending if there are unfinished transactions involving private data, where the transactions will be terminated by the ending of a private session, an add-on can vote to prevent the session from ending (prompting the user is recommended).
...terfaces.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.
Table Layout Regression Tests - Archive of obsolete content
execute the baseline test shutdown the layoutdebugger execute mozilla -layoutdebug - p foo >selftest.txt execute the verify test make a note which tests have failed grep 'failed' selftest.txt (these are false positives, quite frequently they indicate reflow problems, pages showing differently when loaded from cache) make your changes to the source, recompile.
... execute mozilla -layoutdebug - p foo >outputfile.txt execute the verify test make a note which tests have failed grep 'failed' outputfile.txt check how many tests have failed and analyze your results: if the regression tests have failed at the same place as the previous diagnosed false positives => ignore try to figure out what the other regressions are: are they improving the picture or are they regressions?
Using Breakpoints in Venkman - Archive of obsolete content
if the breakpoint script returns a true value (it doesn't have to strictly be a boolean true, any non-null, non-empty string, non-zero, non-undefined, and non-false value will do), execution will continue normally.
... if, on the other hand, the script returns a false value, venkman will stop execution at that point.
Install script template - Archive of obsolete content
tus = registerplid(hkey_local_machine, reg_moz_path, plid, qualifiedsecondaryfolderdll, qualifiedsecondaryfolderxpt, plugin_description, company_name, software_name, version, mimetype, suffix, suffix_description); logcomment("moz first install installation: registerplid("+hkey_local_machine+") returned, status "+hklm_status); if (hklm_status == false) { // write plid keys (mozilla.org/projects/plugins/first-install-problem.html) // write plid keys to hkcu var hkcu_status = registerplid(hkey_current_user, reg_moz_path, plid, qualifiedsecondaryfolderdll, qualifiedsecondaryfolderxpt, plugin_description, company_name, software_name, version, mimetype, suffix, suffix_description); logcomment...
...available = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spacerequired + " k"); logcomment(" available: " + spaceavailable + " k"); return(false); } return(true); } /** * function for writing keys to the win32 system registry.
Windows Install - Archive of obsolete content
ceavailable = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spacerequired + " k"); logcomment(" available: " + spaceavailable + " k"); return(false); } return(true); } function updatewinreg4ren8dot3() { var fprogram = getfolder("program"); var ftemp = getfolder("temporary"); //notes: // can't use a double backslash before subkey // - windows already puts it in.
...nreg.createkey(subkey,""); valname = "ren8dot3"; value = fprogram + "ren8dot3.exe " + ftemp + "ren8dot3.ini"; err = winreg.setvaluestring(subkey, valname, value); } } function prepareren8dot3(listlongfilepaths) { var ftemp = getfolder("temporary"); var fprogram = getfolder("program"); var fren8dot3ini = getwinprofile(ftemp, "ren8dot3.ini"); var binicreated = false; var 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); binicr...
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 } ...
keyExists - Archive of obsolete content
method of winreg object syntax boolean keyexists ( string key); parameters the method has the following parameter: key a string representing the path to the key returns boolean value description if the user does not have read access to the given key, this will also return false.
... example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.keyexists("software\\mozilla")) { //keyexists returned true } else { //keyexists returned false } } ...
valueExists - Archive of obsolete content
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 } } ...
treelines - Archive of obsolete content
« xul reference home treelines type: boolean when set to true, lines are drawn connecting the lines in the tree; when false, the lines are not drawn.
... this is false by default.
hidecolumnpicker - Archive of obsolete content
« xul reference home hidecolumnpicker type: boolean when set to false, a drop-down will appear in the upper right corner of the tree, which the user may use to show and hide columns.
...the default value is false.
showpopup - Archive of obsolete content
if false, the popup will not be shown, but the autocomplete results will still be available.
... you can set this to false and set the autofill attribute to true to emulate a communicator 4.x style autocomplete textbox.
XUL Events - Archive of obsolete content
returning false from this event handler prevents the popup from appearing.
...returning false from this event handler prevents the popup from appearing.
Moving, Copying and Deleting Files - Archive of obsolete content
if false, a directory will only be removed if it is empty.
... var file = io.newfile("home", "photo.jpg"); file.remove(false); this example removes the file called 'photo.jpg'.
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.
openPopup - Archive of obsolete content
iscontextmenu the iscontextmenu argument should be true for context menus and false for all other types of popups.
...if attributesoverride is false, the attribute is only used if the position argument is empty.
Positioning - Archive of obsolete content
for example, the following might be used with the above example to open the popup: menupopup.openpopup(label, "end_before", 0, 0, false, false); note that the position has been set to 'end_before', as above.
...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.
canAdvance - Archive of obsolete content
if this property is false, the user cannot navigate to the next page.
...set to false to disallow moving to the next page.
canRewind - Archive of obsolete content
if this property is false, the user cannot navigate to the previous page.
...set to false to disallow moving to the previous page.
Providing Command-Line Options - Archive of obsolete content
entry: "m-myapp" }], queryinterface: xpcomutils.generateqi([ ci.nsicommandlinehandler ]), /* nsicommandlinehandler */ 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 // follow the guidelines in nsicommandlinehandler.idl // specifically, flag descriptions should start at // character 24, and lines should be wrapped at // 72 characters with embedded newlines, // and finally, the string should end with a newline helpinfo : " -myapp open my application\n" + " -viewapp <uri> view and edit the uri in my application,\n" + " wrapping this description\n" }; var nsgetfactory = xpcomutils.generatensgetfactory([commandlinehandler]); ...
Template and Tree Listeners - Archive of obsolete content
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 retur...
...ns false since we do not want to allow before and after drops.
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].setattribute("style", "visibility: visible"); } else { document.getanonym...
...e, 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","visibility: collapse"); } </body> </method> </implementation> </bindin...
Creating a Wizard - Archive of obsolete content
if it returns false, then the wizard does not close, which might occur if the function savedoginfo() encountered invalid input, for example.
...as soon as one returns false, the navigation will be cancelled.
Custom Tree Views - Archive of obsolete content
here is an example of defining such as object, which can be called whatever you want: //moz 1.8 var treeview = { rowcount : 10000, getcelltext : function(row,column){ if (column.id == "namecol") return "row "+row; else return "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ return false; }, isseparator: function(row){ return false; }, issorted: function(){ return false; }, getlevel: function(row){ return 0; }, getimagesrc: function(row,col){ return null; }, getrowproperties: function(row,props){}, getcellproperties: function(row,col,props){}, getcolumnproperties: function(colid,col,props){} }; the functions in the example not described above do not ...
...tree-window" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="setview();"> <script> //moz 1.8 var treeview = { rowcount : 10000, getcelltext : function(row,column){ if (column.id == "namecol") return "row "+row; else return "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ return false; }, isseparator: function(row){ return false; }, issorted: function(){ return false; }, getlevel: function(row){ return 0; }, getimagesrc: function(row,col){ return null; }, getrowproperties: function(row,props){}, getcellproperties: function(row,col,props){}, getcolumnproperties: function(colid,col,props){} }; function setview(){ document.getelementbyid('my-tree'...
Document Object Model - Archive of obsolete content
function dofind(){ var meter = document.getelementbyid('progmeter'); meter.hidden = false; } this function first gets a reference to the progress meter using its id, progmeter.
... function dofind(){ var meter=document.getelementbyid('progmeter'); meter.hidden = false; var searchtext=document.getelementbyid('find-text').value; alert("searching for \"" + searchtext + "\""); } now, with that alert box in there, we know what should happen when we click the find button.
Input Controls - Archive of obsolete content
you should set this to either true or false.
... disabled set this to either true or false to disable or enable the check box or radio button.
More Wizards - Archive of obsolete content
remember to return false in this case, because you have already changed the page yourself.
...if set to false, the next button is disabled.
Simple Menu Bars - Archive of obsolete content
this attribute can be set to either true or false.
...this attribute can be set to either true or false where the latter is the default.
XPCOM Interfaces - Archive of obsolete content
the code below demonstrates these two steps: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); if (afile instanceof components.interfaces.nsilocalfile){ afile.initwithpath("/mozilla/testfile.txt"); afile.remove(false); } this code will take the file at /mozilla/testfile.txt and delete it.
... function copyfile(sourcefile,destdir) { // get a component for the file to copy var afile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); if (!afile) return false; // get a component for the directory to copy to var adir = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); if (!adir) return false; // next, assign urls to the file components afile.initwithpath(sourcefile); adir.initwithpath(destdir); // finally, copy the file, without renaming it afile.copyto(adir,null); } copyfile("/...
The Implementation of the Application Object Model - Archive of obsolete content
the persistent attribute has values of true and false, with true specifying that local annotations that are persistent are desired.
...note that even if the persistent attribute is set to false, that changes can still be made to a window's content tree.
browser - Archive of obsolete content
autoscroll type: boolean set to false to disable autoscroll for this browser.
...default is false.
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.
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.
...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.
...for non-popup datepickers, this property is always false.
listbox - 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.
...if isselectingrange is false, any existing selection is cleared.
listitem - 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.
menulist - Archive of obsolete content
if this attribute is false, the selection is never updated to match the text box.
...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.
menuseparator - 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.
radio - Archive of obsolete content
ArchiveMozillaXULradio
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.
radiogroup - 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.
...if it is false, the previous radio button is selected.
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.
...if isselectingrange is false, any existing selection is cleared.
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
ArchiveMozillaXULrule
false: the rule will only match nodes that are not marked as containers.
... false: the rule will only match nodes that contain one or more child elements.
scale - Archive of obsolete content
ArchiveMozillaXULscale
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.
...if false, clicking the slide area moves the thumb only one increment in that direction.
tab - Archive of obsolete content
ArchiveMozillaXULtab
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.
tabbrowser - Archive of obsolete content
autoscroll type: boolean set to false to disable autoscroll for this browser.
... parameters inbackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab.
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
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.
...if this attribute is false, the focus does not change during navigation.
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.
... ispm type: boolean if false, the hour is between 0 and 11, and if true, the hour is 12 or greater.
where - Archive of obsolete content
ArchiveMozillaXULwhere
otherwise, the default value is false, to indicate that the value should match with the same case.
...the where clause matches if the condition is false, and does not match if the condition is true.
Application Update - Archive of obsolete content
pref("app.update.silent", false); // update service url: // you do not need to use all the %var% parameters.
...pref("app.update.showinstalledui", false); // 0 = suppress prompting for incompatibilities if there are updates available // to newer versions of installed addons that resolve them.
How to enable locale switching in a XULRunner application - Archive of obsolete content
edit the application preferences file and set "intl.locale.matchos" to false.
...defaults/preferences/prefs.js /* don't inherit os locale */pref("intl.locale.matchos", "false");/* choose own fallback locale; later it can be overridden by the user */pref("general.useragent.locale", "en-gb"); note that some distributions of xulrunner or firefox don't honour the "intl.locale.matchos" setting, so in those cases you won't be able to override the os locale [debian iceweasel bug #417961].
Opening a Link in the Default Browser - Archive of obsolete content
to suppress this warning for particular protocols that are safe to open in the default application, you must set default prefs (thunderbird sets the following prefs): // suppress external-load warning for standard browser schemes pref("network.protocol-handler.warn-external.http", false); pref("network.protocol-handler.warn-external.https", false); pref("network.protocol-handler.warn-external.ftp", false); you can also check whether an external handler for a scheme exists.
...-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); if (extps.externalprotocolhandlerexists("http")) { // handler for http:// urls exists } link within an iframe to enable a link inside an html document that is the "src" of an iframe to be opened in the default browser, setting the preference: pref("network.protocol-handler.expose-all", false); seems to work.
NPN_Invoke - Archive of obsolete content
returns true if the method was successfully invoked, otherwise false.
...if the method invocation succeeds, npn_invoke() returns true, else false.
NPN_InvokeDefault - Archive of obsolete content
returns true if the default method was successfully invoked, otherwise false.
...if the method invocation succeeds, npn_invoke() returns true, else false.
NPN_PostURL - Archive of obsolete content
false: post the raw data in buf.
... to post data from a memory buffer, set the flag file to false, the buffer buf to the data to post, and len to the length of buffer.
What is RSS - Archive of obsolete content
for example: <?xml version="1.0"?> <rss version="2.0"> <channel> <title>example news site</title> <description>this is an example news site.</description> <lastbuilddate>wed, 27 jul 2005 00:30:30 -0700</lastbuilddate> <link>http://news.example.com/</link> <item> <title>news flash: i like bread</title> <guid ispermalink="false">4d4a0a12-f188-4c97-908b-eea27213c2fe</guid> <pubdate>wed, 27 jul 2005 00:30:30 -0700</pubdate> <link>http://news.example.com/artcle/554</link> </item> <item> <title>big news today: birds fly</title> <guid ispermalink="false">c4a63f09-b45b-466b-8773-6ff264001ab7</guid> <pubdate>tue, 19 jul 2005 04:32:51 -0700</pubdate> ...
... <link>http://news.example.com/artcle/553</link> </item> <item> <title>fire is hot</title> <guid ispermalink="false">c1795324-d5ea-44fa-95b1-b5ce2090d4f1</guid> <pubdate>sun, 15 may 2005 13:02:08 -0700</pubdate> <link>http://news.example.com/artcle/552</link> </item> </channel> </rss> bloggers use rss to provide everyone with a list of their newest blog posts.
-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.
... 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.
Enumerator.atEnd - Archive of obsolete content
otherwise, it returns false.
... example in following code, the atend method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } return(s); } ...
@if - Archive of obsolete content
text2 optional text to be parsed if condition1 is false and condition2 is true.
... text3 optional text to be parsed if both condition1 and condition2 are false.
Old Proxy API - Archive of obsolete content
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; } } else { // 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.
Reference - Archive of obsolete content
while also holding in account the previous example where it was avalable in both instances when prototyping object it should be : function->object->instance or (function=object)->instance and ofcourse function == object return false ;) and the following statements also tells me that function == object although math is only an instance of object...
... 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 ...
XForms Select Element - Archive of obsolete content
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.
...characteristics appearance attribute contains the value full there are no analogue widgets in xhtml or in xul visual grouping by choices element is supported if incremental attribute value is false then bound node is updated when item is blurred examples <xf:model> <xf:instance> <data xmlns=""> <values>g</values> </data> </xf:instance> </xf:model> <xf:select ref="/data/values" appearance="full"> <xf:choices> <xf:label>green colors</xf:label> <xf:item> <xf:label>pale green</xf:label> <xf:value>pg</xf:value> </xf:item> <xf:item> <xf:label>green</xf:label> <xf:value>g</xf:value> </xf:item> ...
Efficient animation for web games - Game development
when the callback is executed, you can unset that flag so that calls to that function will request a new frame again, like this: function redraw() { drawpending = false; // do drawing ...
... } 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.
Create the Canvas and draw on it - Game development
try adding this to the bottom of your javascript, saving and refreshing: ctx.beginpath(); ctx.arc(240, 160, 20, 0, math.pi*2, false); ctx.fillstyle = "green"; ctx.fill(); ctx.closepath(); as you can see we're using the beginpath() and closepath() methods again.
...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.
2D maze game with device orientation - Game development
c methods: for(var i=0; i<this.maxlevels; i++) { var newlevel = this.add.group(); newlevel.enablebody = true; newlevel.physicsbodytype = phaser.physics.arcade; for(var e=0; e<this.leveldata[i].length; e++) { var item = this.leveldata[i][e]; newlevel.create(item.x, item.y, 'element-'+item.t); } newlevel.setall('body.immovable', true); newlevel.visible = false; this.levels.push(newlevel); } first, add.group() is used to create a new group of items.
...to load specific levels, we make sure the previous levels are hidden, and show the current one: showlevel: function(level) { var lvl = level | this.level; if(this.levels[lvl-2]) { this.levels[lvl-2].visible = false; } this.levels[lvl-1].visible = true; } thanks to that the game gives the player a challenge - now he have to roll the ball across the play area and guide it through the labyrinth built from the blocks.
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 english mathematician george boole, who pioneered the field of mathematical logic.
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
all values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and nan).
... 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.
Basic native form controls - Learn web development
you've met some of these already, but below is a list of those common attributes, for your reference: attribute name default value description autofocus false this boolean attribute lets you specify that the element should automatically have input focus when the page loads.
... disabled false this boolean attribute indicates that the user cannot interact with the element.
Graceful asynchronous programming with Promises - Learn web development
instead, they succeed, but with the response.ok property set to false.
... 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.
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
add the following function to your 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 spinn...
... set the variable isover to false, so we can track whether the correct keys were pressed for player 1 or 2 to win.
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.
... important: with while and do...while — as with all loops — you must make sure that the initializer is incremented or, depending on the case, decremented, so the condition eventually becomes false.
Function return values - Learn web development
the isnan() function to test whether the num value is not a number — if so, it returns true, and if not, it returns false.
... if the test returns false, the num value is a number.
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.
... 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).
Basic math in JavaScript — numbers and operators - Learn web development
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.
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.
...as you might expect, it returns false, because 6 is not less than 3!
Ember interactivity: Events, classes and state - Learn web development
add the following import statement below the existing one: import { tracked } from '@glimmer/tracking'; now add the following class below the previous line you added: class todo { @tracked text = ''; @tracked iscompleted = false; constructor(text) { this.text = text; } } this class represents a todo — it contains a @tracked text property containing the text of the todo, and a @tracked iscompleted property that specifies whether the todo has been completed or not.
... when instantiated, a todo object will have an initial text value equal to the text given to it when created (see below), and an iscompleted value of false.
Accessibility in React - Learn web development
surely we could add a condition to our useeffect to focus on the edit button if isediting is false?
... our useeffect() hook is behaving exactly as we designed it: it runs as soon as the component renders, sees that isediting is false, and focuses the "edit" button.
React interactivity: Events and state - Learn web development
putting that all together, your addtask() function should read like so: function addtask(name) { const newtask = { id: "id", name: name, completed: false }; settasks([...tasks, newtask]); } now you can use the browser to add a task to our data!
...update your newtask constant declaration to this: const newtask = { id: "todo-" + nanoid(), name: name, completed: false }; save everything, and try your app again — now you can add tasks without getting that warning about duplicate ids.
Beginning our React todo list - Learn web development
</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> </button> <button type="button" classname="btn toggle-btn" aria-pressed="false"> <span classname="visually-hidden">show </span> <span>completed</span> <span classname="visually-hidden"> tasks</span> ...
... notes: to use boolean values (true and false) in jsx attributes, you must enclose them in curly braces.
Adding a new todo form: Vue events, methods, and models - Learn web development
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...
... update your addtodo() method like so: addtodo(todolabel) { this.todoitems.push({id:uniqueid('todo-'), label: todolabel, done: false}); } try testing your form again, and you should see new to-do items get appended to the end of the list.
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.
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 "false", the start index and end index/run length are used as given.
Mozilla’s UAAG evaluation report
(p1) p the following line can be added to a user's prefs.js file to control blinking: user_pref("browser.blink_allowed", false); bug 89144 has been filed to expose this pref in the ui.
...x 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.
Creating Sandboxed HTTP Connections
use false.
...var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(listener, "http-on-modify-request", false); observerservice.addobserver(listener, "http-on-examine-response", false); the final piece is to manipulate the cookies.
Debugging JavaScript
(note that before firefox 28, this was labeled "browser debugger" and only the debugger was available, not the whole toolbox.) note that you must accept the incoming connection : (you may disable the pop-up above with the devtools.debugger.prompt-connection set to false in about:config.
... this can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) then, the browser toolbox displays the available tools for debugging.
Displaying Places information using views
at least one of flatlist and showroot must be false.
...at least one of showroot and flatlist must be false.
Frame script loading and lifetime
if allowdelayedload is false, the script will only be loaded into frames which are open when the call was made.
... var gcontentframemessagemanager = this; addeventlistener('unload', function(aevent) { if (aevent.target == gcontentframemessagemanager) { sendasyncmessage('my-addon-id', 'framescript-died'); // if you did not set third argument of `services.mm.addmessagelistener` to `true`, then this will fail to send a message } }, false); note about unload during uninstallation/upgrade when your add-on is uninstalled, or disabled, you should: cancel it, if you have used allowdelayedload, by calling removedelayedframescript; ensuring the frame script is not loaded into any new tabs.
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
note: for activities where the receiving app's activity definition in its manifest does not include returnvalue or returnvalue is false, no mozbrowseractivitydone event will be generated as of the landing of bug 1194525 in firefox os 2.5.
... details the details property returns an anonymous javascript object with the following properties: success a boolean that indicates whether the activity has completed successfully (true) or not (false).
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).
Extending a Protocol
create dom/ipc/echochild.cpp and implement: #include "echochild.h" namespace mozilla { namespace dom { echochild::echochild() : mactoralive(true) {} void echochild::actordestroy(actordestroyreason awhy) { mactoralive = false; } } // end of namespace dom } // end of namespace mozilla ok, now add 'echochild.cpp' to the unified_sources of dom/ipc/moz.build.
... return ipc_ok(); } mozilla::ipc::ipcresult echoparent::recv__delete__() { mactoralive = false; return ipc_ok(); } void echoparent::actordestroy(actordestroyreason awhy) { mactoralive = false; } } // end of namespace dom } // end of namespace mozilla ok, now add 'echoparent.cpp' to the unified_sources of dom/ipc/moz.build.
IPDL Type Serialization
return false if deserialization failed } }; } // namespace ipc the standard ipdl types (integers, floats, and xpcom strings) already have serializers.
...amtype; static void write(message* amsg, const paramtype& aparam) { writeparam(amsg, aparam.i); writeparam(amsg, aparam.j); for (int i = 0; i < 4; ++i) writeparam(amsg, aparam.k[i]); } static bool read(const message* amsg, void** aiter, paramtype* aresult) { if (!readparam(amsg, aiter, &(aresult->i)) || !readparam(amsg, aiter, &(aresult->j))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<examplestruct>) by simply declaring "using nstarray<examplestruct>;' in your ipdl file, then using it in a ipc method.
Assert.jsm
we check using the most exact approximation of equality between two objects to keep the chance of false positives to a minimum.
...expected expected result from the test author message short explanation 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); } }); ...
AsyncShutdown.jsm
return value returns true if a blocker has been removed, or false otherwise.
... note that a result of false may mean either that the blocker has never been installed or that the phase has completed and the blocker has already been resolved.
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.
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.
Mozilla DOM Hacking Guide
else, *aisnumber is false and -1 is returned.
... #define dom_classinfo_map_begin_no_class_if(_class, _interface) _dom_classinfo_map_begin(_class, &ns_get_iid(_interface), pr_false) this macro should be used for dom classes that have no "leaf" interface.
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.
...when the user then runs developeredition again, the preference value will be false as no user preference was written by nightly.
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.
... false (default) no action triggered (see bug 736985).
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.
... false (default) new tab with search results will be opened in the foreground.
mail.tabs.drawInTitlebar
the old behavior can be restored by setting the preference mail.tabs.drawintitlebar to false.
... false the tabs are drawn in a separate tab bar, and the title bar shows the title of the current tab (e.g.
nglayout.debug.disable xul fastload
type:boolean default value: false (true in debug builds) exists by default: yes application support:?
... bugs: values false (default) xul fastload is used.
reader.parse-on-load.force-enabled
type:boolean default value: false exists by default: yes application support:firefox mobile 23.0 status: active; last updated 2013-05-11 introduction: pushed to nightly on 2013-05-06 bugs: bug 867875 values true reader mode is enabled independent of memory available.
... false (default) reader mode is only enabled if memory available exceeds a threshold (currenlty 384mb).
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.
...the old behavior can be restored by setting the preference mail.tabs.drawintitlebar to false.nglayout.debug.disable xul fastloadthe preference nglayout.debug.disable_xul_fastload controls whether or not xul fastload is used.nglayout.debug.disable_xul_cacheto improve performance, mozilla caches chrome xul documents the first time they load for faster loading later.
Leak And Bloat Tests
fd]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_pref("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.checkdefaultclient", false); // ensure os x and outlook/oe books are disabled user_pref("ldap_2.servers.osx.position", 0); user_pref("ldap_2.servers.oe.position", 0); preferences in generated profile, but not set: user_pref("mail.root.none", "/home/moztest/.thunderbird/t7i1txfw.minimum/mail"); user_pref("mail.root.pop3", "/home/moztest/.thunderbird/t7i1txfw.minimum/mail"); user_pref("mail.server.server1.directory", "/home/moztest/.thunderbird/t7i1...
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.
PRLinger
syntax #include <prio.h> typedef struct prlinger { prbool polarity; printervaltime linger; } prlinger; fields the structure has the following fields: polarity polarity of the option's setting: pr_false means the option is off, in which case the value of linger is ignored.
...the pr_sockopt_linger socket option, with a value represented by a structure of type prlinger, makes it possible to change this default as follows: if polarity is set to pr_false, pr_close returns immediately, but if there are any data remaining in the socket send buffer, the runtime attempts to deliver the data to the peer.
NSS 3.12.5 release_notes
the caller of pk11_readrawattribute should free the data buffer pointed to by item using a secitem_freeitem(item, pr_false) or port_free(item->data) call.
...if pool is null but dest is not null, the caller should free the data buffer pointed to by dest with a secitem_freeitem(dest, pr_false) or port_free(dest->data) 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.
...the default setting for this option is false.
NSS_3.12_release_notes.html
ide trust flags bug 390381: libpkix rejects cert chain when root ca cert has no basic constraints bug 391183: rename libpkix error string number type to pkix error number types bug 397122: nss 3.12 alpha treats a key3.db with no global salt as having no password bug 405966: unknown signature oid 1.3.14.3.2.29 causes sec_error_bad_signature, 3.11 ignores it bug 413010: cert_comparerdn may return a false match bug 417664: false positive crl revocation test on ppc/ppc64 nss_enable_pkix_verify=1 bug 404526: glibc detected free(): invalid pointer bug 300929: certificate policy extensions not supported bug 129303: nss needs to expose interfaces to deal with multiple token sources of certs.
...0: cert_pkixverifycert fails if crls are missing, implement cert_pi_revocationflags bug 427706: nss_3_12_rc1 crashes in passwordmgr tests bug 426245: assertion failure went undetected by tinderbox bug 158242: pk11_putcrl is very memory inefficient bug 287563: please make cert_comparenamewithconstraints a non-static function bug 301496: nss_shutdown failure in p7sign bug 324878: crlutil -l outputs false crl names bug 337010: oom crash [[@ nsc_digestkey] dereferencing possibly null att bug 343231: certutil issues certs for invalid requests bug 353371: klocwork 91117 - null pointer dereference in cert_certchainfromcert bug 353374: klocwork 76494 - null ptr derefs in cert_formatname bug 353375: klocwork 76513 - null ptr deref in nsscertificatelist_docallback bug 353413: klocwork 76541 free uninitia...
NSS 3.14.1 release notes
bug 810582 - tls false start is now only used with servers that negotiate a cipher suite that supports forward secrecy.
... note: the criteria for false start may change again in future nss releases.
NSS Sample Code Sample_2_Initialization of NSS
w_none; pwdata.data = null; } if (newpass) { newpwdata.source = pw_plaintext; newpwdata.data = newpass; } else if (newpwfile) { newpwdata.source = pw_fromfile; newpwdata.data = null; } else { newpwdata.source = pw_none; newpwdata.data = null; } if (pk11_needuserinit(slot)) { newpw = initslotpassword(slot, pr_false, &pwdata); rv = pk11_initpin(slot, (char*)null, newpw); } else { for (;;) { oldpw = getmodulepassword(slot, pr_false, &pwdata); if (pk11_checkuserpassword(slot, oldpw) != secsuccess) { if (pwdata.source == pw_none) { pr_fprintf(pr_stderr, "invalid password.
... again.\n"); } else { pr_fprintf(pr_stderr, "invalid password.\n"); port_memset(oldpw, 0, pl_strlen(oldpw)); port_free(oldpw); return secfailure; } } else { break; } port_free(oldpw); } newpw = initslotpassword(slot, pr_false, &newpwdata); if (pk11_changepw(slot, oldpw, newpw) != secsuccess) { pr_fprintf(pr_stderr, "failed to change password.\n"); return secfailure; } port_memset(oldpw, 0, pl_strlen(oldpw)); port_free(oldpw); pr_fprintf(pr_stdout, "password changed successfully.\n"); } port_memset(newpw, 0, pl_strlen(newpw)); port_free(newpw)...
NSS Sample Code Utilities_1
print32 numbytes; prstatus prstatus; prstatus = pr_getopenfileinfo(src, &info); if (prstatus != pr_success) { return secfailure; } dst->data = 0; if (secitem_allocitem(null, dst, info.size)) { numbytes = pr_read(src, dst->data, info.size); if (numbytes == info.size) { return secsuccess; } } secitem_freeitem(dst, pr_false); dst->data = null; return secfailure; } /* * echooff */ static void echooff(int fd) { if (isatty(fd)) { struct termios tio; tcgetattr(fd, &tio); tio.c_lflag &= ~echo; tcsetattr(fd, tcsaflush, &tio); } } /* * echoon */ static void echoon(int fd) { if (isatty(fd)) { struct termios tio; tcgetattr(fd, &tio); tio.c_lflag |= echo;...
... 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); fflush ...
Initialize NSS database - sample 2
w_none; pwdata.data = null; } if (newpass) { newpwdata.source = pw_plaintext; newpwdata.data = newpass; } else if (newpwfile) { newpwdata.source = pw_fromfile; newpwdata.data = null; } else { newpwdata.source = pw_none; newpwdata.data = null; } if (pk11_needuserinit(slot)) { newpw = initslotpassword(slot, pr_false, &pwdata); rv = pk11_initpin(slot, (char*)null, newpw); if (rv == secsuccess) { pr_fprintf(pr_stderr, "pk11_initpin failed.\n"); return secfailure; } } else { for (;;) { oldpw = getmodulepassword(slot, pr_false, &pwdata); if (pk11_checkuserpassword(slot, oldpw) != secsuccess) { if (pwdata.sour...
... again.\n"); } else { pr_fprintf(pr_stderr, "invalid password.\n"); port_memset(oldpw, 0, pl_strlen(oldpw)); port_free(oldpw); return secfailure; } } else { break; } port_free(oldpw); } newpw = initslotpassword(slot, pr_false, &newpwdata); if (pk11_changepw(slot, oldpw, newpw) != secsuccess) { pr_fprintf(pr_stderr, "failed to change password.\n"); return secfailure; } port_memset(oldpw, 0, pl_strlen(oldpw)); port_free(oldpw); pr_fprintf(pr_stdout, "password changed successfully.\n"); } port_memset(newpw, 0, pl_strlen(newpw)); port_free(newpw)...
Utilities for nss samples
print32 numbytes; prstatus prstatus; prstatus = pr_getopenfileinfo(src, &info); if (prstatus != pr_success) { return secfailure; } dst->data = 0; if (secitem_allocitem(null, dst, info.size)) { numbytes = pr_read(src, dst->data, info.size); if (numbytes == info.size) { return secsuccess; } } secitem_freeitem(dst, pr_false); dst->data = null; return secfailure; } /* * echooff */ static void echooff(int fd) { if (isatty(fd)) { struct termios tio; tcgetattr(fd, &tio); tio.c_lflag &= ~echo; tcsetattr(fd, tcsaflush, &tio); } } /* * echoon */ static void echoon(int fd) { if (isatty(fd)) { struct termios tio; tcgetattr(fd, &tio); tio.c_lflag |= echo;...
... 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); fflush ...
nss tech note4
/* free the secitem fields */ secitem_freeitem(&data.version, pr_false); secitem_freeitem(&data.streetaddress, pr_false); ......
... secitem_freeitem(&data.maxusers, pr_false); } } some miscellaneous helper functions compare two secitems (e.g., two oids) prbool secitem_itemsareequal(const secitem *a, const secitem *b); interpreting a secitem value as an integer if secitem *item->len <=4, then int value = der_getinteger(item); interpreting a secitem value as a string use string copy functions to copy item->len bytes from item->data and null terminate explicitly some higher level extension functions get a specific extension from the list of extensions, given the extension tag secstatus cert_findcertextension (certcertificate *cert, int tag, secitem *value); ...
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.
...e_new_param algtag_to_mechanism mechanism_to_algtag the following files added: test/cipher_test.py test/digest_test.py release 0.6.0 release date 2009-07-08 scm tag source download change log general modifications: fix red hat bug #510343 client_auth_data_callback seg faults if false is returned from callback release 0.5.0 release date 2009-07-01 scm tag source download change log general modifications: restore ssl.nss_init and ssl.nss_shutdown but make them deprecated add __version__ string to nss module release 0.4.0 release date 2009-06-30 scm tag...
NSS Tools modutil
-fips [true | false] enable (true) or disable (false) fips 140-2 compliance for the netscape communicator internal module.
...echanisms 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.
SpiderMonkey compartments
this improves cache utilization by reducing false sharing of cache lines.
... false sharing occurs when we are trying to operate on an object and we have to read an entire cache line of data into the cpu cache.
SpiderMonkey Internals
there are a few special values: nullvalue(), undefinedvalue(), truevalue() and falsevalue().
...in general, both functions inside spidermonkey and jsapi callback functions signal errors by calling js_reporterror or one of its variants, or js_setpendingexception, and returning js_false or null.
BOOLEAN_TO_JSVAL
please use js::booleanvalue/js::truevalue/js::falsevalue instead in spidermonkey 45 or later.
... if b is false, the result is jsval_false.
JS::TrueHandleValue
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 ...
JSNative
js_reporterror or js_reportoutofmemory) or raise an exception (using js_setpendingexception), and the callback must return false.
... (returning false without reporting an error or raising an exception terminates the script with an uncatchable error.
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.
JS_AliasElement
if the property name you specify does not exist, js_aliaselement reports an error, and returns js_false.
... if the element is currently out of scope, already exists, or the alias itself cannot be assigned to the element, js_aliaselement does not report an error, but returns js_false.
JS_AliasProperty
if the property name you specify does not exist, js_aliasproperty reports an error, and returns js_false.
... if the property is currently out of scope, already exists, or the alias itself cannot be assigned to the property, js_aliasproperty does not report an error, but returns js_false.
JS_CallFunction
if js engine fails to get the function, it returns false.
...otherwise it returns false, and rval is undefined.
JS_ClearPendingException
(there is a pending exception if the most recently thrown exception in cx has not yet been caught or cleared.) when any jsapi call fails with an exception, the caller must either use js_clearpendingexception to catch the exception; or return false to allow the exception to propagate to the caller.
...many jsapi functions can simply report an error and return false without building and throwing an exception object.
JS_ConvertArguments
if argc is less than the number of arguments required by format, js_convertargument reports an error and returns false.
...if any argument conversion fails or there are not enough arguments, it returns false.
JS_ConvertValue
converting to jstype_object works exactly like js::toobject if v.isnullorundefined() is false, otherwise the result is nullptr.
...on error or exception, it returns false, and the value left in *vp is undefined.
JS_DeleteElement
otherwise it returns false.
... for javascript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, js_deleteelement reports the error before returning false.
JS_DeleteProperty
if the hook returns false, the error is propagated.
... these functions return true on success, regardless of whether a property was actually deleted, and false on error or exception.
JS_ExecuteRegExp
if test is false, js_executeregexp and js_newregexpobjectnostatics store the match result array 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_HasArrayLength
on failure, js_hasarraylength returns js_false, and the value left in *lengthp is undefined.
...this function may return js_false without having reported any error or exception.
JS_HasInstance
on error or exception, it returns false, and the value left in *bp is undefined.
...otherwise js_hasinstance returns false.
JS_InstanceOf
js_instanceof returns true if obj is of the given class and false otherwise.
...otherwise, it returns false; it also reports a typeerror containing the function's name.
JS_IsConstructing
otherwise it returns js_false.
... ordinary non-constructor jsnatives have no need to call this; it always returns js_false for such functions.
JS_IsExceptionPending
otherwise, it returns false this can be used from jsnative functions which call js code to determine if the called js code threw an exception or not.
...*/ pending = js_isexceptionpending(cx); if (pending) { if (!js_getpendingexception(cx, &exception)) return false; js_clearpendingexception(cx); } /* ...
JS_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_ObjectIsFunction
js_objectisfunction returns true if obj is a function and false otherwise.
...note that the result may be false even for some callable objects, such as regular expression objects or proxy objects see also mxr id search for js_objectisfunction js_valuetofunction js_objectisfunction ...
JS_SetBranchCallback
if the callback raises an exception using js_setpendingexception() and returns js_false, then the javascript engine propagates the exception to the script that was executing at the time.
... if the callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error.
JS_SetContextCallback
if the callback returns js_false, the instance will be destroyed and js_newcontext returns null.
...in a debug build, if the callback returns false, the js engine will halt with an assertion.
JS_SetElement
on error or exception, js_setelement returns false.
...on error or exception, js_setelement returns false and the value left in *vp is unspecified.
JS_SetProperty
if obj is a native object with custom setgeneric op, the op is called with (cx, obj, id, &v, false)).
...on error or exception, it returns false, and the value left in v is unspecified.
JS_ValueToBoolean
on error or exception, it returns js_false, and the value left in *bp is undefined.
... for versions greater than jsversion_1_2, all objects convert to js_true, even boolean wrapper objects like the one produced by new boolean(false).
JS_ValueToNumber
if v is undefined, null, false, or true, conversion succeeds, and the result is nan, 0, 0, or 1 respectively.
...on error or exception, it returns js_false, and the value left in *dp is undefined.
JSAPI reference
ranslate 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 spidermonkey 38 js::value constants: j...
...s::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
js::clonefunctionobject (bug 1088228) interned_string_to_jsid (bug 1045900) js::construct (bug 1017109) js::createerror (bug 984048) js::falsehandlevalue (bug 959787) js::handlesymbol (bug 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 (bu...
... 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.
TPS Bookmark Lists
loadinsidebar: true or false.
...folder that the bookmark should be moved to position: the title of the existing bookmark item, in the current folder, where this bookmark should be moved to (i.e., this bookmark would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below the current one) example: { uri: "http://www.google.com", title: "google", loadinsidebar: false, tags: [ "google", "computers", "misc" ] } livemark objects valid properties are: livemark: the livemark name.
Web Replay
default false.
...default false architecture there are several main components to the project: the record/replay infrastructure records enough information during recording so that the replayed process can run and produce the same observable behaviors.
A Web PKI x509 certificate primer
write extensions file by creating a new file with name openssl.ss.cnf with the following contents: basicconstraints = ca:false subjectaltname =dns:www.example.com extendedkeyusage =serverauth 4.
... write extensions file (make a new file with name openssl.ss.cnf with the following contents) basicconstraints = ca:false subjectaltname =dns:www.example.com extendedkeyusage =serverauth authorityinfoaccess = ocsp;uri:http://ocsp.example.com:80/ intermediate signs the csr (using sha256) and appends the extensions described in the file "openssl x509 -req -sha256 -days 1096 -in example.csr -cakey intkey.pem -ca int.pem -set_serial $some_large_integer -out www.example.com.pem -extfile openssl.int.c...
Retrieving part of the bookmarks tree
rootnode.containeropen = false; if you encounter a node with a type of result_type_folder or another type of container, you can open these folders and descend into the hierarchy.
...rootnode.containeropen = false; ...
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".
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 ...
XPCshell Test Manifest Expressions
operators in order of decreasing precedence: () == != && || literal values booleans: the literal strings true and false.
...ating 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.
IAccessibleRelation
s_false if there is nothing to return, [out] value is null.
...ntargets actual number of targets in the returned array (not more than maxtargets) return value s_false if there is nothing to return, ntargets() is set to 0.
mozIRepresentativeColorCallback
void oncomplete( in boolean success, [optional] in unsigned long color ); parameters success true if analysis was successful, false otherwise.
...if success is false, color is not provided.
mozIThirdPartyUtil
this is done as follows: if achannel is an nsihttpchannel and has the 'forceallowthirdpartycookie' property set, then: if auri is null, return false.
...then: if the parent is the same as the bottommost window, and the channel has the load_document_uri flag set, return false.
nsIAccessibleSelectable
return value true if the child is selected, false if not.
...return value if the object does not accept multiple selection, return false.
nsIApplicationUpdateService
obsolete since gecko 1.9.1.7pre isdownloading boolean true if a download is in progress, otherwise false.
...background true to download the update in the background or false to download it in the foreground.
nsIAuthPrompt2
note: exceptions thrown from this function will be treated like a return value of false.
... return value false, authentication should be cancelled, usually because the user did not provide username/password.
nsIAutoCompleteInput
if false, the rollup event will be dispatched.
... disableautocomplete boolean true if auto-complete is currently disabled; otherwise false.
nsIBrowserSearchService
if this value is false, the engine will be added to the list upon successful load, but it will not be selected as the current engine.
... getvisibleengines() returns an array of all installed search engines whose hidden attribute is false.
nsICacheVisitor
return value returns true to start visiting all entries for this device, otherwise returns false to advance to the next device.
... return value returns true to visit the next entry on the current device, or if the end of the device has been reached, advance to the next device, otherwise returns false to advance to the next device.
nsICachingChannel
this may return an error if cacheasfile is false.
...return value returns true if this channel's data is being loaded from the cache, otherwise returns false.
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.
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.
nsIDBChangeListener
the calling function stores the value of astatus, changes the header ahdrtochange, then calls onhdrpropertychanged again with aprechange false.
... aprechange true on first call before change, false on second call after change.
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.
nsIDOMProgressEvent
otherwise, specify false.
...if lengthcomputable is false, this must be zero.
nsIDOMStorageEventObsolete
canbubblearg true if the event is allowed to bubble, otherwise false.
... cancelablearg true if the event can be canceled, otherwise false.
nsIDispatchSupport
classexists returns containing pr_false if the class is not registered.
...boolean isclasssafetohost( in jscontextptr cx, in nscidref cid, in boolean capscheck, out boolean classexists ); parameters cx cid capscheck classexists returns containing pr_false if the class is not registered.
nsIEventListenerService
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.
... return value true if the protocol is exposed, false otherwise.
nsIFaviconService
a false return value means that it's worth trying to load it.
... example var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var pageuri = ioservice.newuri("http://www.mozilla.org/", null, null); var faviconuri = ioservice.newuri("http://www.mozilla.org/favicon.ico", null, null); faviconservice.setandloadfaviconforpage(pageuri, faviconuri, false); setfavicondata() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0.
nsIFocusManager
if false, then the return value will be the frame element if the focus is in a child frame.
... afocusedwindow will be set to the currently focused descendant window of awindow, or to awindow if adeep is false.
nsIFrameScriptLoader
it's possible that the frame for this chromemessagesender is not yet available at the time of the loadframescript() call, and if you pass false in this situation, your process script won't be loaded.
... aruninglobalscope boolean optional, defaults to false.
nsIHttpActivityObserver
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.
... if this is false, the observeactivity() method should not be called.
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 = functio...
... subject.cancel( this.aborted ); alert( "found flash!" ); //handle flash file here } } }; myhttprequestobserver.prototype.register = function ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.addobserver(this, "http-on-examine-response", false); observerservice.addobserver(this, "http-on-examine-cached-response", false); }; myhttprequestobserver.prototype.unregister = function ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.removeobserver( this, "http-on-examine-response" ); observerservice.remove...
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.
nsILoginInfo
return value true if the two logins are exactly equal or false if they're not.
... return value true if the two logins are equivilant or false if they're not.
nsILoginManagerStorage
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.
nsIMicrosummary
false if they aren't.
... note: this method returns false if either objects don't have a generator removeobserver() remove a microsummary observer from this microsummary.
nsIMimeConverter
if false mark as undread.
...if false remove flag.
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...
...false otherwise.
nsIMsgIncomingServer
for nntp, the value is overridden to be false.
... loginatstartup boolean logonfallback boolean maxmessagesize long offlinesupportlevel long password acstring passwordpromptrequired boolean if the password for the server is available either via authentication in the current session or from password manager stored entries, return false.
nsINavHistoryQuery
domainishost boolean this controls the meaning of domain, and whether it is an exact match domainishost = true, or hierarchical (= false).
...if false, only tags in the tags list are included in the results.
nsINavHistoryResultViewObserver
to provide behavior similar to the folder pane in thunderbird, where drops are only permitted on items themselves instead of on the pane as a whole, always return false when the orientation isn't drop_on.
... return value return true if the drop is permitted or false if it isn't.
nsIObserverService
ownsweak if set to false, the nsiobserverservice will hold a strong reference to anobserver.
...(in most cases, you should use false.) enumerateobservers() called to enumerate all observers registered for a particular topic.
nsIPrincipal
return value true if the two principals are equivalent; otherwise false.
...boolean subsumes( in nsiprincipal other ); parameters other missing description return value true if this principal subsumes the specified principal; otherwise false.
nsIPrintingPrompt
isforprinting true - for printing, false for print preview.
...if false is returned it means the observer (usually the caller) shouldn't wait for print preview progress there is intermediate progress.
nsIPushService
example pushservice.unsubscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, ok) => { if (!components.issuccesscode(code)) { cu.reporterror("error unsubscribing: " + code); return; } // `ok === true` if the subscription was removed, or `false` if the // `(scope, principal)` pair didn't have a subscription.
... }); } }; obsservice.addobserver(pushobserver, "push-message", false); obsservice.addobserver(pushobserver, "push-subscription-change", false); see also nsipushsubscription nsipushmessage pushmanager ...
nsIPushSubscription
bool quotaapplies(); nsipushsubscription.quotaapplies() always returns false for system subscriptions.
... bool isexpired(); nsipushsubscription.isexpired() always returns false for system subscriptions.
nsIScriptableUnescapeHTML
isxml set this to true if the fragment is an xml string; otherwise set it to false.
...this parameter is ignored if isxml is false.
nsITelemetry
returns false if the user has not opted into "extended telemetry" on the release channel, when the user has explicitly opted out of telemetry on nightly/aurora/beta or if manually set to false during tests.
... static - true for histograms defined in histograms.json, false for ones defined with newhistogram().
nsITransaction
if the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undotransaction() and redotransaction() methods can be called.
...a true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed.
nsITreeSelection
note: setting this attribute to false will fire a select event.
...if false, everything is cleared except for the specified range.
nsIWebContentHandlerRegistrar
r: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.
... so lets restore it back to false, which is the default value services.prefs.clearuserpref('gecko.handlerservice.allowregisterfromdifferenthost'); } register a webmail service as mailto handler without contentwindow under construction.
nsIWebProgressListener2
false if awebprogress is requesting a redirection to a different uri.
...false if the refresh should be aborted.
nsIWindowsRegKey
return value this method returns true if the key has changed and false otherwise.
... this method will always return false if startwatching() was not called.
nsIXMLHttpRequest
try something like this: nscomptr<nsidomeventtarget> target(do_queryinterface(myxmlhttpreq)); target->addeventlistener(ns_literal_string("load"), mylistener, pr_false) where mylistener is your event listener object that implements the interface nsidomeventlistener.
...00) { cb(xhr.response); 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.
nsIXULTemplateBuilder
return value returns true if the node has content generated for it; otherwise returns false.
...if false, the element's contents are only generated if it's open.
nsIZipEntry
isdirectory boolean true if the name of the entry ends with '/' and false otherwise.
...if the zip file contains an actual entry for a directory, this attribute will be false for the nsizipentry for that directory.
NS_ASSERTION
only if the assertion evaluates to false is there an "assertion failure", which is thrown.
...syntax ns_assertion(expressiontotest, "error text"); see also ns_abort_if_false ns_precondition ns_postcondition disabling assertion dialog box on windows ...
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).
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
custom settings fields to handle custom settings, the settings xhtml page should contain a form with the id "provider-form", with its onsubmit attribute set to "return false;".
... example: <form id="provider-form" onsubmit="return false;"> <label for="username">username:</label> <input id="username" type="text" required="true" /> <label for="server">server:</label> <input id="server" type="text" required="true" /> <label for="port">port:</label> <input id="port" pattern="[0-9]+" required="true" /> </form> the form is expected to use html5 form validation.
Creating a Custom Column
lly 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!
... window.addeventlistener("load", doonceloaded, false); function doonceloaded() { var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", false); } var createdbobserver = { // components.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { addcustomcolumnhandler(); } } in t...
Filter Incoming Mail
f( !amsghdr.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.
... by example, setting it to lower case subject = subject.tolocalelowercase(); // then we rebuild a subject objet by rencoding the string // and assign it to the message headers and we're done amsghdr.subject = 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_subscription - boolean, should we use subscriptions?
...(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)?
Using tab-modal prompts
disabling tab-modal prompts you can disable tab-modal prompts and get back window-modal prompts by setting the prompts.tab_modal.enabled preference to false.
... 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(null, ['title not shown in mod...
Add to iPhoto
if (document.getelementbyid("contentareacontextmenu")) { document.getelementbyid("contentareacontextmenu").addeventlistener("popupshowing", iphoto.onpopup, false); } responding when the context menu is clicked when the user right-clicks an image, our handler gets called: onpopup: function() { var node = iphoto.getcurrentnode(); var item = document.getelementbyid("add-to-iphoto_menuitem"); if (item) { item.hidden = (node == null); // hide it if we're not on an image } } this code finds the image node the user right-clicked in by calling...
...imagebyurl: function(src) { corefoundation.init(); carbon.init(); appservices.init(); // download the image var filepath = this.downloadimage(src); var mutablearray = corefoundation.cfarraycreatemutable(null, 1, corefoundation.kcftypearraycallbacks.address()); if (mutablearray) { var url = corefoundation.cfurlcreatefromfilesystemrepresentation(null, filepath, filepath.length, false); corefoundation.cfarrayappendvalue(mutablearray, url); corefoundation.cfrelease(url); // call launch services to open iphoto and deliver the image var ref = new carbon.struct_fsref; var appparams = appservices.struct_lsapplicationparameters(0, 1, ref.address(), null, null, null, null); var appstr = "file:///applications/iphoto.app"; var appstrcf = corefoundation.cf...
Accessibility Inspector - Firefox Developer Tools
if you don't wish to allow the accessibility features to be automatically enabled, you can use the configuration editor (also known as about:config) to define the preference devtools.accessibility.auto-init.enabled, and set it to false.
... if you don't wish to use the accessibility features at all, you can use the configuration editor to set the preference devtools.accessibility.enabled to false.
Debugger.Environment - Firefox Developer Tools
false otherwise.
...false otherwise.
Debugger.Memory - Firefox Developer Tools
reading the accessor produces true if the debugger is capturing stacks for object allocations, and false otherwise.
...returns false otherwise.
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 false if the property is non-configurable.
about:debugging (before Firefox 68) - Firefox Developer Tools
checking the box sets both preferences to true, and unchecking it sets them both to false.
... if the dom.serviceworkers.enable preference is set to false in about:config.
Animation.playbackRate - Web APIs
bottle.addeventlistener("mousedown", shrinkalice, false); bottle.addeventlistener("touchstart", shrinkalice, false); contrariwise, clicking on the cake causes her to "grow," playing alicechange forwards again: var growalice = function() { alicechange.playbackrate = 1; alicechange.play(); } // on tap or click, alice will grow.
... cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growalice, false); in another example, the red queen's race game, alice and the red queen are constantly slowing down: setinterval( function() { // make sure the playback rate never falls below .4 if (redqueen_alice.playbackrate > .4) { redqueen_alice.playbackrate *= .9; } }, 3000); but clicking or tapping on them causes them to speed up by multiplying their playbackrate: var gofaster = function() { redqueen_alice.playbackrate *= 1.1; } document.addeventlistener("click", gofaster); document.addeventlistener("touchstart", gofaster); specifications specification status comment web animationsthe definition of 'animation.playbackrate' in that specification.
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).
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
eventinitdict optional an optional eventinit dictionary object containing the following fields: bubbles optional defaults to false, of type boolean, indicating if the event bubbles or not.
... cancelable optional defaults to false, of type boolean, indicating if the event can be canceled or not.
AudioBufferSourceNode.loop - Web APIs
the loop property's default value is false.
... syntax var loopingenabled = audiobuffersourcenode.loop; audiobuffersourcenode.loop = true | false; value a boolean which is true if looping is enabled; otherwise, the value is false.
AudioTrack - Web APIs
setting this value to false mutes the track's audio.
... tracks.foreach(function(track) { if (track.language === userlanguage) { track.enabled = true; } else { track.enabled = false; } }); the language is in standard (rfc 5646) format.
AudioTrackList.getTrackById() - Web APIs
function disablecharacter(videoelem, charactername) { videoelem.audiotracks.gettrackbyid(charactername).enabled = false; } this short function gets the audiotracklist containing the video's audio tracks using htmlmediaelement.audiotracks, then calls gettrackbyid() on it, specifying the character's name.
... the resulting track's audio is then disabled by setting its enabled flag to false.
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.requestDevice() - Web APIs
the default is false.
...for example, options.filters is present and options.acceptalldevices is true, or if options.filters is not present and options.acceptalldevices is false.
CSS.supports() - Web APIs
WebAPICSSsupports
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.
CacheStorage.delete() - Web APIs
if no cache object is found, it resolves to false.
... return value a promise that resolves to true if the cache object is found and deleted, and false otherwise.
CacheStorage - Web APIs
if no cache object is found, it resolves to false.
...cachedresponse.ok ) { return false; } return await cachedresponse.json(); } // delete any old caches to respect user's disk space.
CanvasRenderingContext2D.isPointInPath() - Web APIs
return value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false.
... html <canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innertext = ctx.ispointinpath(30, 70); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in a circular path2d path.
CanvasRenderingContext2D.isPointInStroke() - Web APIs
return value boolean a boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false.
... html <canvas id="canvas"></canvas> <p>in stroke: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innertext = ctx.ispointinstroke(50, 10); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical path2d path.
Advanced animations - Web APIs
<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 running = false; var ball = { x: 100, y: 100, vx: 5, vy: 1, 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 clear() { ctx.fillstyle = 'rgba(255, 255, 255, 0.3)'; ctx.fillrect(0,0,canvas.width,canvas.height); } function draw() ...
...); } canvas.addeventlistener('mousemove', function(e) { if (!running) { clear(); ball.x = e.clientx; ball.y = e.clienty; ball.draw(); } }); canvas.addeventlistener('click', function(e) { if (!running) { raf = window.requestanimationframe(draw); running = true; } }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); running = false; }); ball.draw(); move the ball using your mouse and release it with a click.
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, you can remove the lines that call moveto().
...; if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); roundedrect(ctx, 12, 12, 150, 150, 15); roundedrect(ctx, 19, 19, 150, 150, 9); roundedrect(ctx, 53, 53, 49, 33, 10); roundedrect(ctx, 53, 119, 49, 16, 6); roundedrect(ctx, 135, 53, 49, 33, 10); roundedrect(ctx, 135, 119, 25, 49, 10); ctx.beginpath(); ctx.arc(37, 37, 13, math.pi / 7, -math.pi / 7, false); ctx.lineto(31, 37); ctx.fill(); for (var i = 0; i < 8; i++) { ctx.fillrect(51 + i * 16, 35, 4, 4); } for (i = 0; i < 6; i++) { ctx.fillrect(115, 51 + i * 16, 4, 4); } for (i = 0; i < 8; i++) { ctx.fillrect(51 + i * 16, 99, 4, 4); } ctx.beginpath(); ctx.moveto(83, 116); ctx.lineto(83, 102); ctx.beziercurveto(83, 94, 89, 88, 97...
Hit regions and accessibility - Web APIs
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="start game"></canvas> hit regions whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve.
... <canvas id="canvas"></canvas> <script> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: 'circle'}); canvas.addeventlistener('mousemove', function(event) { if (event.region) { alert('hit region: ' + event.region); } }); </script> the addhitregion() method also takes a control option to route events to an element (that is a descendant of the canvas): ctx.addhitregion({control: element}); this can be useful for routing to <input> elements...
Optimizing canvas - Web APIs
nerwidth / canvas.width; var scaley = window.innerheight / canvas.height; var scaletofit = math.min(scalex, scaley); var scaletocover = math.max(scalex, scaley); stage.style.transformorigin = '0 0'; //scale from top left stage.style.transform = 'scale(' + scaletofit + ')'; turn off transparency if your application uses canvas and doesn’t need a transparent backdrop, set the alpha option to false when creating a drawing context with htmlcanvaselement.getcontext().
... var ctx = canvas.getcontext('2d', { alpha: false }); more tips batch canvas calls together.
Using images - Web APIs
so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever.
...you can disable this feature like this: ctx.mozimagesmoothingenabled = false; ctx.webkitimagesmoothingenabled = false; ctx.msimagesmoothingenabled = false; ctx.imagesmoothingenabled = false; « previousnext » ...
DOMMatrix - Web APIs
WebAPIDOMMatrix
if false, the matrix is 3d.
...if the matrix can't be inverted, its components are all set to nan, and is2d returns false.
DOMMatrixReadOnly - Web APIs
if false, the matrix is 3d.
...if the matrix cannot be inverted, the new matrix's components are all set to nan and its is2d property is set to false.
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.toggle() - Web APIs
the toggle() method of the domtokenlist interface removes a given token from the list and returns false.
...if set to false, then token will only be removed, but not added.
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.
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.
...a value of false—the default—indicates that no audio track is to be included in the stream.
DisplayMediaStreamConstraints.video - Web APIs
since a video track must always be included, a value of false results in a typeerror exception being thrown.
...a value of false is not permitted and will throw a typeerror.
DisplayMediaStreamConstraints - Web APIs
the default value is false.
...a value of false is not permitted, and results in a typeerror being thrown.
Document.importNode() - Web APIs
if deep is set to false, then only externalnode is imported — the new node has no children.
...the new default value is false.
Document.queryCommandSupported() - Web APIs
return value returns a boolean which is true if the command is supported and false if the command isn't.
... notes the 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action [1] example var flg = document.querycommandsupported("selectall"); if(flg) { // ...do something } specifications specification status comment execcommand ...
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.
..."thank you." : "please, scroll and read the following text."; } onload = function () { var otoberead = document.getelementbyid("rules"); checkreading.noticebox = document.createelement("span"); document.registration.accept.checked = false; checkreading.noticebox.id = "notice"; otoberead.parentnode.insertbefore(checkreading.noticebox, otoberead); otoberead.parentnode.insertbefore(document.createelement("br"), otoberead); otoberead.onscroll = checkreading; checkreading.call(otoberead); } specifications specification status comment css object model (cssom) view modulethe definition of 'element.sc...
Element.scrollIntoView() - Web APIs
if false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.
... example var element = document.getelementbyid("box"); element.scrollintoview(); element.scrollintoview(false); element.scrollintoview({block: "end"}); element.scrollintoview({behavior: "smooth", block: "end", inline: "nearest"}); notes the element may not be scrolled completely to the top or bottom depending on the layout of other elements.
Element.toggleAttribute() - Web APIs
return value true if attribute name is eventually present, and false otherwise.
...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.composed - Web APIs
WebAPIEventcomposed
most other types of events are not composed, and so will return false.
... if this value is false, the shadow root will be the last node to be offered the event.
Event.initEvent() - Web APIs
WebAPIEventinitEvent
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.
... elem.addeventlistener('click', function (e) { // e.target matches elem }, false); elem.dispatchevent(event); specifications specification status comment domthe definition of 'event.initevent()' in that specification.
Event.preventDefault() - Web APIs
<code>preventdefault()</code> won't let you check this!<br>"; event.preventdefault(); }, false); html <p>please click on the checkbox control.</p> <form> <label for="id-checkbox">checkbox:</label> <input type="checkbox" id="id-checkbox"/> </form> <div id="output-box"></div> result stopping keystrokes from reaching an edit field the following example demonstrates how invalid text input can be stopped from reaching the input field with preventdefault().
...first, listen for keypress events: var mytextbox = document.getelementbyid('my-textbox'); mytextbox.addeventlistener('keypress', checkname, false); the checkname() function, which looks at the pressed key and decides whether to allow it: function checkname(evt) { var charcode = evt.charcode; if (charcode != 0) { if (charcode < 97 || charcode > 122) { evt.preventdefault(); displaywarning( "please use lowercase letters only." + "\n" + "charcode: " + charcode + "\n" ); } } } the displaywarn...
Event.returnValue - Web APIs
WebAPIEventreturnValue
setting this property to false prevents the default action.
... 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.
FetchEvent() - Web APIs
true if yes, and false if not.
...if not present, it defaults to false.
Using Fetch - Web APIs
instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
...he 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 these operations are only useful in serviceworkers, bu...
FileReader.readAsDataURL() - Web APIs
onchange="previewfile()"><br> <img src="" height="200" alt="image preview..."> javascript function previewfile() { const preview = document.queryselector('img'); const file = document.queryselector('input[type=file]').files[0]; const reader = new filereader(); reader.addeventlistener("load", function () { // convert image file to base64 string preview.src = reader.result; }, false); if (file) { reader.readasdataurl(file); } } live result example reading multiple files html <input id="browse" type="file" onchange="previewfiles()" multiple> <div id="preview"></div> javascript function previewfiles() { var preview = document.queryselector('#preview'); var files = document.queryselector('input[type=file]').files; function readandpreview(file) { ...
...// make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new filereader(); reader.addeventlistener("load", function () { var image = new image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendchild( image ); }, false); reader.readasdataurl(file); } } if (files) { [].foreach.call(files, readandpreview); } } note: the filereader() constructor was not supported by internet explorer for versions before 10.
FileSystemEntry - Web APIs
isdirectory read only a boolean which is true if the entry represents a directory; otherwise, it's false.
...if it's not a file, this value is false.
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.
...this attribute is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
HTMLCanvasElement.getContext() - Web APIs
contextattributes you can use several context attributes when creating your rendering context, for example: const gl = canvas.getcontext('webgl', { antialias: false, depth: false }); 2d context attributes: alpha: boolean that indicates if the canvas contains an alpha channel.
... if set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images.
HTMLCanvasElement.mozOpaque - Web APIs
this has been standardized as setting the alpha option to false when creating a drawing context with htmlcanvaselement.getcontext().
... var canvas = document.getelementbyid('canvas'); console.log(canvas.mozopaque); // true // deactivate it canvas.mozopaque = false; specifications not part of any standard.
HTMLFieldSetElement - Web APIs
this is the empty string if the element is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
... htmlfieldsetelement.willvalidate a boolean false, because <fieldset> objects are never candidates for constraint validation.
HTMLFormElement.reportValidity() - Web APIs
when false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
... syntax htmlformelement.reportvalidity() return value boolean example document.forms['myform'].addeventlistener('submit', function() { document.forms['myform'].reportvalidity(); }, false); specifications specification status comment html living standardthe definition of 'htmlformelement.reportvalidity()' in that specification.
HTMLInputElement.webkitdirectory - Web APIs
syntax htmlinputelement.webkitdirectory = boolvalue value a boolean; true if the <input> element should allow picking only directories or false if only files should be selectable.
...ry multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications specification status comment file and directory entries apithe definition of 'webkitdirectory' in that specification.
HTMLKeygenElement - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
... willvalidate is a boolean that is always false because keygen objects are never candidates for constraint validation.
HTMLMediaElement.autoplay - Web APIs
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.
... <video id="video" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile_id=165"> </video> *** disable autoplay (recommended) *** false is the default value document.queryselector('#video').autoplay = false; specifications specification status comment html living standardthe definition of 'htmlmediaelement.autoplay' in that specification.
HTMLMediaElement.ended - Web APIs
if the source of the media is a mediastream, this value is true if the value of the stream's active property is false.
... example var obj = document.createelement('video'); console.log(obj.ended); // false specifications specification status comment html living standardthe definition of 'htmlmediaelement.ended' in that specification.
HTMLMediaElement.muted - Web APIs
true means muted and false means not muted.
... example var obj = document.createelement('video'); console.log(obj.muted); // false specifications specification status comment html living standardthe definition of 'htmlmediaelement.muted' in that specification.
HTMLObjectElement - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
...always false for htmlobjectelement objects.
HTMLElement.focus() - Web APIs
a value of false for preventscroll (the default) means that the browser will scroll the element into view after focusing it.
... function getfocus() { document.getelementbyid("mybutton").focus(); } html <button type="button" id="mybutton">click me!</button> <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: 10...
HTMLOutputElement - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
...if there are problems, fires an invalid event at the element, and returns false; if there are no problems, it returns true.
HTMLSlotElement.assignedElements() - Web APIs
the available options are: flatten: a boolean indicating whether to return the assigned elements of any available child <slot> elements (true) or not (false).
... defaults to false.
HTMLSlotElement.assignedNodes() - Web APIs
the available options are: flatten: a boolean indicating whether to return the assigned nodes of any available child <slot> elements (true) or not (false).
... defaults to false.
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).
IDBDatabase: abort event - Web APIs
/ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('abort', () => { console.log('transa...
.../ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onabort = () => { console.log('transaction aborted');...
IDBDatabase: close event - Web APIs
/ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('close', () => { console.log('databa...
.../ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onclose = () => { console.log('database connection cl...
IDBDatabase.createObjectStore() - Web APIs
defaults to false.
...radeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += "<li>error loading database.</li>"; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += "<li>object store created.</li>"; }; specificat...
IDBDatabase: error event - Web APIs
/ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year:...
.../ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year:...
IDBDatabase: versionchange event - Web APIs
/ open the database const dbopenrequest = window.indexeddb.open('nonexistent', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.addeventlistener('success', event => { const db = event.target.result; db.addeventlistener('versionchange', event => { ...
.../ open the database const dbopenrequest = window.indexeddb.open('nonexistent', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = event.target.result; db.onversionchange = event => { console.log('the version of ...
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
false the current index allows duplicate key values.
... the unique status of the index is logged to the console: it should be returned as false.
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
the default is false.
...the default is false.
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.
... idbkeyrange.prototype.includes = idbkeyrange.prototype.includes || function(key) { var r = this, c; if (r.lower !== undefined) { c = indexeddb.cmp(key, r.lower); if (r.loweropen && c <= 0) return false; if (!r.loweropen && c < 0) return false; } if (r.upper !== undefined) { c = indexeddb.cmp(key, r.upper); if (r.upperopen && c >= 0) return false; if (!r.upperopen && c > 0) return false; } return true; }; specification specification status comment indexed database api draftthe definition of 'includes()' in that specification.
IDBKeyRange.lowerBound() - Web APIs
the default is false.
...here we declare keyrangevalue = idbkeyrange.lowerbound("f", false); — a range that includes the value "f" and everthing after it.
IDBKeyRange.upperBound() - Web APIs
syntax var myidbkeyrange = idbkeyrange.upperbound(upper[, open=false]) parameters bound specifies the upper bound of the new key range.
...the default is false.
IDBObjectStore.createIndex() - Web APIs
if false, it will add one single entry containing the array.
...eneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); }; specifications specification status comment ...
IDBOpenDBRequest: blocked event - Web APIs
st', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { // let's try to open the same database with a higher revision version const req2 = indexeddb.o...
...st', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { // let's try to open the same database with a higher revision version const req2 = indexeddb.o...
IDBOpenDBRequest: upgradeneeded event - Web APIs
todolist', 4); dbopenrequest.addeventlistener('upgradeneeded', event => { const db = event.target.result; console.log(`upgrading to version ${db.version}`); // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); this is the same example, but uses the onupgradeneeded event handler property.
...indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; console.log(`upgrading to version ${db.version}`); // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; ...
IDBRequest: error event - Web APIs
enrequest.addeventlistener('upgradeneeded', event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction, ready fo...
...list', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data...
IDBRequest: success event - Web APIs
list', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.addeventlistener('success', (event) => { console.log('database opened successfully!'); }); the same example, but using t...
...list', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.onsuccess = (event) => { console.log('database opened successfully!'); }; ...
IDBTransaction: abort event - Web APIs
list', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data...
...list', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data...
IDBTransaction: complete event - Web APIs
list', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data...
...list', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data...
IDBTransaction: error event - Web APIs
/ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the da...
.../ open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the da...
IntersectionObserverEntry.isIntersecting - Web APIs
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).
KeyboardEvent.metaKey - Web APIs
the keyboardevent.metakey read-only property returning a boolean that indicates if the meta key was pressed (true) or not (false) when the event occurred.
...keyboardevent.metakey is false when the ⊞ windows is pressed.
KeyboardEvent - Web APIs
alert(`combination of ctrlkey + ${keyname}`); } else { alert(`key pressed ${keyname}`); } }, false); document.addeventlistener('keyup', (event) => { const keyname = event.key; // as the user releases the ctrl key, the key is no longer active, // so event.ctrlkey is false.
... if (keyname === 'control') { alert('control key was released'); } }, false); </script> </head> <body> </body> </html> specifications specification status comment ui eventsthe definition of 'keyboardevent' in that specification.
LockManager.request() - Web APIs
the default value is false.
...the default value is false.
MSManipulationEvent.initMSManipulationEvent() - Web APIs
when false the event does not propagate upward.
...when false, the default action cannot be canceled.
MediaDevices.getUserMedia() - Web APIs
typeerror the list of constraints specified is empty, or has all constraints set to false.
... var front = false; document.getelementbyid('flip-button').onclick = function() { front = !front; }; var constraints = { video: { facingmode: (front?
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.
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.ignoreMutedMedia - Web APIs
if this attribute is false, mediarecorder will record silence for audio and black frames for video.
... the default is false.
MediaRecorder - Web APIs
if this attribute is false, mediarecorder will record silence for audio and black frames for video.
... the default is false.
MediaSessionActionDetails.fastSeek - Web APIs
once fastseek is false or not present, the repeating series of seekto actions is complete and you can finalize the state of your web app or content.
...if the value is false or this property isn't present, the seek is final.
MediaSource.isTypeSupported() - Web APIs
if the returned value is false, then the user agent is certain that it cannot access media of the specified format.
...a value of false is a guarantee that media of the given type will not play, however.
MediaStreamEvent() - Web APIs
"bubbles", optional and defaulting to false, inherited from eventinit, and indicating if the event must bubble or not.
... "cancelable", optional and defaulting to false, inherited from eventinit, and indicating if the event can be canceled or not.
MediaStreamTrack.muted - Web APIs
when a track is disabled by setting enabled to false, it generates only empty frames (audio frames in which every sample is 0, or video frames in which every pixel is black).
... syntax const mutedflag = track.muted value a boolean which is true if the track is currently muted, or false if the track is currently unmuted.
Recording a media element - Web APIs
cordingtimems)) .then (recordedchunks => { let recordedblob = new blob(recordedchunks, { type: "video/webm" }); recording.src = url.createobjecturl(recordedblob); downloadbutton.href = recording.src; downloadbutton.download = "recordedvideo.webm"; log("successfully recorded " + recordedblob.size + " bytes of " + recordedblob.type + " media."); }) .catch(log); }, false); when a click event occurs, here's what happens: lines 2-4 navigator.mediadevices.getusermedia() is called to request a new mediastream that has both video and audio tracks.
... handling the stop button the last bit of code adds a handler for the click event on the stop button using addeventlistener(): stopbutton.addeventlistener("click", function() { stop(preview.srcobject); }, false); this simply calls the stop() function we covered earlier.
MediaTrackSettings.logicalSurface - Web APIs
a visible display surface (that is, a surface for which logicalsurface returns false) is the portion of a logical display surface which is currently visible onscreen.
... 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).
MouseEvent.metaKey - Web APIs
be aware that many operating systems bind special functionality to the meta key, so this property may be false even when the key is actually pressed.
... 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.
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).
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 false, it is not.
MutationObserverInit.characterData - Web APIs
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.
... subtree lets you specify whether to watch the target node and all of its descendants (true), or just the target node (false).
NDEFWriter.write() - Web APIs
WebAPINDEFWriterwrite
will be ignored if overwrite is false.
... notallowederror the permission for this operation was rejected or overwrite is false and there are already records on the tag.
Using Navigation Timing - Web APIs
for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationstart), and outputs that information to the screen by inserting it into an element.
..."navigation"; break; case performancenavigation.type_reload: output += "reload"; break; case performancenavigation.type_back_forward: output += "history"; break; default: output += "unknown"; break; } output += "<br/>redirects: " + performance.navigation.redirectcount; document.queryselector(".output").innerhtml = output; }, false); this amends the previous example by looking at the contents of the performance.navigation object.
Navigator.cookieEnabled - Web APIs
syntax var cookieenabled = navigator.cookieenabled; cookieenabled is a boolean: true or false.
...it returns false in firefox and chromium-based browsers.
Navigator.sendBeacon() - Web APIs
otherwise, it returns false.
... window.addeventlistener("unload", function logdata() { var xhr = new xmlhttprequest(); xhr.open("post", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsdata); }); this is what sendbeacon() replaces.
Navigator - Web APIs
WebAPINavigator
navigator.cookieenabled read only returns false if setting a cookie will be ignored and true otherwise.
... navigatorid.taintenabled() deprecated since gecko 1.7.8 obsolete since gecko 9.0 returns false.
Online and offline events - Web APIs
api navigator.online navigator.online is a property that maintains a true/false value (true for online, false for offline).
...according to the specification: the navigator.online attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...
Network Information API - Web APIs
if a cellular connection is found, then the preloadvideo flag is set to false.
... 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 changes.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
if false, only node will be cloned.
...although deep it still optional, it now defaults to false.
Node.contains() - Web APIs
WebAPINodecontains
as contains is inclusive and determining if the body contains itself isn't the intention of isinpage this case explicitly returns false.
...false : document.body.contains(node); } specifications specification status comment domthe definition of 'node.contains()' in that specification.
Node.getRootNode() - Web APIs
WebAPINodegetRootNode
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).
...otnode().nodename); // #document console.log(child.getrootnode().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.isConnected - Web APIs
WebAPINodeisConnected
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 } `; // attach...
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.
NodeIterator.expandEntityReferences - Web APIs
if this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected.
... syntax expand = nodeiterator.expandentityreferences; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = nodeiterator.expandentityreferences; specifications specification status comment document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator.expandentityreferences' in that specification.
NodeIterator.pointerBeforeReferenceNode - Web APIs
the nodeiterator.pointerbeforereferencenode read-only property returns a boolean flag that indicates whether the nodefilter is anchored before (if this value is true) or after (if this value is false) the anchor node indicated by the nodeiterator.referencenode property.
... syntax flag = nodeiterator.pointerbeforereferencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); flag = nodeiterator.pointerbeforereferencenode; specifications specification status comment domthe definition of 'nodeiterator.pointerbeforereferencenode' in that specification.
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 it fails, we return false in the catch() {} block.
OVR_multiview2 - Web APIs
currently, there is no way to use multiview to render to a multisampled backbuffer, so you should create contexts with antialias: false.
... const gl = document.createelement('canvas').getcontext( 'webgl2', { antialias: false } ); const ext = gl.getextension('ovr_multiview2'); const fb = gl.createframebuffer(); gl.bindframebuffer(gl.draw_framebuffer, fb); const colortex = gl.createtexture(); gl.bindtexture(gl.texture_2d_array, colortex); gl.texstorage3d(gl.texture_2d_array, 1, gl.rgba8, 512, 512, 2); ext.framebuffertexturemultiviewovr(gl.draw_framebuffer, gl.color_attachment0, colortex, 0, 0, 2); const depthstencilt...
OffscreenCanvas.getContext() - Web APIs
contextattributes you can use several context attributes when creating your rendering context, for example: offscreen.getcontext("webgl", { antialias: false, depth: false }); 2d context attributes: alpha: boolean that indicates if the canvas contains an alpha channel.
... if set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images then.
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 like this: handlepaymentchange = event => { const detailsupdate = {}; if (event.methodname === "https://apple.com/apple-pay") { const servicefeeinfo = calculateservicefee(event.met...
...hoddetails); object.assign(detailsupdate, servicefeeinfo); } event.updatewith(detailsupdate); }, false); this begins by looking at the event's methodname property; if that indicates that the user is trying to use apple pay, we pass the methoddetails into a function called calculateservicefee(), which we might create to take the information about the transaction, such as the underlying credit card being used to service the apple pay request, and compute and return an paymentdetailsupdate object that specifies changes to be applied to the paymentrequest in order to add any service fees that the payment method might require.
Permissions.query() - Web APIs
WebAPIPermissionsquery
the default is false.
...the default is false.
Permissions.revoke() - Web APIs
the default is false.
...the default is false.
Pinch zoom gestures - Web APIs
// log events flag var logevents = false; // logging/debugging functions function enablelog(ev) { logevents = logevents ?
... 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 = ""; } ...
Using Pointer Events - Web APIs
function startup() { var el = document.getelementsbytagname("canvas")[0]; el.addeventlistener("pointerdown", handlestart, false); el.addeventlistener("pointerup", handleend, false); el.addeventlistener("pointercancel", handlecancel, false); el.addeventlistener("pointermove", handlemove, false); log("initialized."); } this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur.
... function handlestart(evt) { log("pointerdown."); var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); log("pointerdown: id = " + evt.pointerid); ongoingtouches.push(copytouch(evt)); var color = colorfortouch(evt); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.arc(evt.clientx, evt.clienty, 4, 0, 2 * math.pi, false); // a circle at the start ctx.fillstyle = color; ctx.fill(); } after storing some of the event's processing in the ongoingtouches for later processing, the start point is drawn as a small circle.
PositionOptions - Web APIs
on the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power.
... default: false.
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.
PublicKeyCredentialCreationOptions.extensions - Web APIs
the client must not use any authenticator with false acceptance rate (far) and false rejection rate (frr) below the inputs.
... examples var publickey = { extensions:{ uvi: true, loc: false, uvm: false, exts: true }, 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.c...
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(); } ...
RTCDataChannelEvent() - Web APIs
default is false.
...default is false.
RTCIceCandidateStats - Web APIs
deleted optional a boolean value indicating whether or not the candidate has been released or deleted; the default value is false.
... 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 be using a network connection other than ethernet or a vpn.
RTCOfferAnswerOptions.voiceActivityDetection - Web APIs
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: iceconnectionstatechange event - Web APIs
the ice layer makes this determination upon receiving the end-of-candidates signal, which is provided by caling addicecandidate() with a candidate whose candidate property is an empty string (""), or by setting the rtcpeerconnection property cantrickleicecandidates to false.
... pc.addeventlistener("iceconnectionstatechange", ev => { let stateelem = document.queryselector("#call-state"); stateelem.classname = `${pc.iceconnectionstate}-state`; }, false); this can also be written as: pc.oniceconnectionstatechange = ev => { let stateelem = document.queryselector("#call-state"); stateelem.classname = `${pc.iceconnectionstate}-state`; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'iceconnectionstatechange' in that specification.
RTCPeerConnection: track event - Web APIs
pc = new rtcpeerconnection({ iceservers: [ { urls: "turn:fake.turnserver.url", username: "someusername", credential: "somepassword" } ] }); pc.addeventlistener("track", e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; }, false); the event handler assigns the new track's first stream to an existing <video> element, identified using the variable videoelement.
... pc.ontrack = e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'track' in that specification.
RTCPeerConnectionIceEvent() - Web APIs
"bubbles" (optional, default is false): inherited from eventinit(), this boolean option indicates whether or not the event must bubble.
... "cancelable" (optional, default is false, inherited from eventinit(), this boolean indicates whether or not the event can be canceled.
Selection.containsNode() - Web APIs
when false, containsnode() only returns true when the entire node is part of the selection.
... if not specified, the default value false is used.
SourceBuffer.remove() - Web APIs
this method can only be called when sourcebuffer.updating equals false.
... if sourcebuffer.updating is not equal to false, call sourcebuffer.abort().
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.
SubtleCrypto.deriveBits() - Web APIs
ve("fade-in"); }); sharedsecretvalue.textcontent = `${buffer}...[${sharedsecret.bytelength} bytes total]`; } // generate 2 ecdh key pairs: one for alice and one for bob // in more normal usage, they would generate their key pairs // separately and exchange public keys securely const generatealiceskeypair = window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivebits"] ); const generatebobskeypair = window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivebits"] ); promise.all([generatealiceskeypair, generatebobskeypair]).then(values => { const aliceskeypair = values[0]; const bobskeypair = values[1]; const derivebitsbutton = document.queryselector(".ecdh .derive-bits-button"); derivebi...
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user.
SubtleCrypto.unwrapKey() - Web APIs
*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-kw key using pbkdf2.
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-gcm key using pbkdf2.
Text.isElementContentWhitespace - Web APIs
syntax b = textnode.iselementcontentwhitespace; example in the example below, we create a node with mixed display and whitespace characters and the attribute is false.
... var tn = document.createtextnode("hello world"); tn.iselementcontentwhitespace; /* evaluates to false */ for a node that is all whitespace characters, the iselementcontentwhitespace evaluates to true.
TextDecoder.prototype.decode() - Web APIs
set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked.
... it defaults to false.
Touch.clientX - Web APIs
WebAPITouchclientX
// register touchstart and touchend listeners for element 'source' var src = document.getelementbyid("source"); var clientx, clienty; src.addeventlistener('touchstart', function(e) { // cache the client x/y coordinates clientx = e.touches[0].clientx; clienty = e.touches[0].clienty; }, false); src.addeventlistener('touchend', function(e) { var deltax, deltay; // compute the change in x and y coordinates.
...}, false); specifications specification status comment touch events – level 2 draft non-stable version.
Touch.clientY - Web APIs
WebAPITouchclientY
// register touchstart and touchend listeners for element 'source' var src = document.getelementbyid("source"); var clientx, clienty; src.addeventlistener('touchstart', function(e) { // cache the client x/y coordinates clientx = e.touches[0].clientx; clienty = e.touches[0].clienty; }, false); src.addeventlistener('touchend', function(e) { var deltax, deltay; // compute the change in x and y coordinates.
...}, false); specifications specification status comment touch events – level 2 draft no changes since last version.
TouchEvent.ctrlKey - Web APIs
otherwise, it is false.
... 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
otherwise, it is false.
... 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
otherwise, it is false.
... 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.
Using Touch Events - Web APIs
// register touch event handlers someelement.addeventlistener('touchstart', process_touchstart, false); someelement.addeventlistener('touchmove', process_touchmove, false); someelement.addeventlistener('touchcancel', process_touchcancel, false); someelement.addeventlistener('touchend', process_touchend, false); process an event in an event handler, implementing the application's gesture semantics.
... // create touchstart handler someelement.addeventlistener('touchstart', function(ev) { // iterate through the touch points that were activated // for this element and process each event 'target' for (var i=0; i < ev.targettouches.length; i++) { process_target(ev.targettouches[i].target); } }, false); prevent the browser from processing emulated mouse events.
Touch events - Web APIs
function startup() { var el = document.getelementbyid("canvas"); el.addeventlistener("touchstart", handlestart, false); el.addeventlistener("touchend", handleend, false); el.addeventlistener("touchcancel", handlecancel, false); el.addeventlistener("touchmove", handlemove, false); } document.addeventlistener("domcontentloaded", startup); this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur.
..."touchstart."); var el = document.getelementbyid("canvas"); var ctx = el.getcontext("2d"); var touches = evt.changedtouches; for (var i = 0; i < touches.length; i++) { console.log("touchstart:" + i + "..."); ongoingtouches.push(copytouch(touches[i])); var color = colorfortouch(touches[i]); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.fillstyle = color; ctx.fill(); console.log("touchstart:" + i + "."); } } this calls event.preventdefault() to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered).
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).
TreeWalker.expandEntityReferences - Web APIs
if this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected.
... syntax expand = treewalker.expandentityreferences; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = treewalker.expandentityreferences; specifications document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.expandentityreferences' in that specification.
UIEvent.isChar - Web APIs
WebAPIUIEventisChar
syntax var ischar = uievent.ischar; value a boolean which is true if the event produces a character; otherwise false.
...when this is the case, ischar returns false.
WebGL2RenderingContext.uniformMatrix[234]x[234]fv() - Web APIs
must be false.
... examples gl.uniformmatrix2x3fv(loc, false, [1, 2, 3, 4, 5, 6]); specifications specification status comment webgl 2.0the definition of 'uniformmatrix' in that specification.
WebGLRenderingContext.colorMask() - Web APIs
examples gl.colormask(true, true, true, false); to get the current color mask, query the color_writemask constant which returns an array.
... gl.getparameter(gl.color_writemask); // [true, true, true, false] specifications specification status comment webgl 1.0the definition of 'colormask' in that specification.
WebGLRenderingContext.depthMask() - Web APIs
examples gl.depthmask(false); to get the current depth mask, query the depth_writemask constant which returns a boolean.
... gl.getparameter(gl.depth_writemask); // false specifications specification status comment webgl 1.0the definition of 'depthmask' in that specification.
WebGLRenderingContext.isEnabled() - Web APIs
return value a glboolean indicating if the capability cap is enabled (true), or not (false).
... examples gl.isenabled(gl.stencil_test); // false to activate or deactivate a specific capability, use the webglrenderingcontext.enable() and webglrenderingcontext.disable() methods: gl.enable(gl.stencil_test); gl.disable(gl.stencil_test); specifications specification status comment webgl 1.0the definition of 'isenabled' in that specification.
WebGLRenderingContext.uniformMatrix[234]fv() - Web APIs
must be false.
... return value undefined examples gl.uniformmatrix2fv(loc, false, [2,1, 2,2]); specifications specification status comment webgl 1.0the definition of 'uniformmatrix' in that specification.
WebGLRenderingContext.vertexAttribPointer() - Web APIs
position, not normalized gl.vertexattribpointer(0, 3, gl.float, false, 20, 0); gl.enablevertexattribarray(0); //2.
... const locposition = gl.getattriblocation(shaderprogram, 'position'); gl.vertexattribpointer(locposition, 3, gl.float, false, 20, 0); gl.enablevertexattribarray(locposition); const locnormal = gl.getattriblocation(shaderprogram, 'normal'); gl.vertexattribpointer(locnormal, 4, gl.byte, true, 20, 12); gl.enablevertexattribarray(locnormal); const loctexuv = gl.getattriblocation(shaderprogram, 'texuv'); gl.vertexattribpointer(loctexuv, 2, gl.unsigned_short, true, 20, 16); gl.enablevertexattribarray(loctexuv); specifica...
WebGLRenderingContext - Web APIs
webglrenderingcontext.iscontextlost() returns true if the context is lost, otherwise returns false.
..." + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this example is also available on github.
A basic 2D WebGL animation example - Web APIs
let uscalingfactor; let uglobalcolor; let urotationvector; let avertexposition; // animation timing let previoustime = 0.0; let degreespersecond = 90.0; initializing the program is handled through a load event handler called startup(): window.addeventlistener("load", startup, false); function startup() { glcanvas = document.getelementbyid("glcanvas"); gl = glcanvas.getcontext("webgl"); const shaderset = [ { type: gl.vertex_shader, id: "vertex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspectratio = glcanvas.width/glcanvas.height; currentrotation = ...
...2fv(uscalingfactor, currentscale); gl.uniform2fv(urotationvector, currentrotation); gl.uniform4fv(uglobalcolor, [0.1, 0.7, 0.2, 1.0]); gl.bindbuffer(gl.array_buffer, vertexbuffer); avertexposition = gl.getattriblocation(shaderprogram, "avertexposition"); gl.enablevertexattribarray(avertexposition); gl.vertexattribpointer(avertexposition, vertexnumcomponents, gl.float, false, 0, 0); gl.drawarrays(gl.triangles, 0, vertexcount); window.requestanimationframe(function(currenttime) { let deltaangle = ((currenttime - previoustime) / 1000.0) * degreespersecond; currentangle = (currentangle + deltaangle) % 360; previoustime = currenttime; animatescene(); }); } the first thing that needs to be done in order to draw a frame of the animation...
Basic scissoring - Web APIs
of of scissoring.</p> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } window.addeventlistener("load", function setupwebgl (evt) { "use strict" window.removeeventlistener(evt.type, setupwebgl, false); var paragraph = document.queryselector("p"); var canvas = document.queryselector("canvas"); // the following two lines set the size (in css pixels) of // the drawing buffer to be identical to the size of the // canvas html element, as determined by css.
... gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github.
Clearing with colors - Web APIs
window.removeeventlistener(evt.type, setupwebgl, false); // references to the document elements.
... gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github.
Detect WebGL - Web APIs
button.addeventlistener("click", detectwebglcontext, false); function detectwebglcontext () { // create canvas element.
..." + "your browser or device may not support webgl."; } } }, false); the source code of this example is also available on github.
Hello GLSL - Web APIs
padding : 0.6em; } <script type="x-shader/x-vertex" id="vertex-shader"> #version 100 void main() { gl_position = vec4(0.0, 0.0, 0.0, 1.0); gl_pointsize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 void main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment...
..." + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); 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) { ...
Hello vertex attributes - Web APIs
on 100 precision highp float; attribute float position; void main() { gl_position = vec4(position, 0.0, 0.0, 1.0); gl_pointsize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment...
...ntlistener("click", function (evt) { var clickxrelativtocanvas = evt.pagex - evt.target.offsetleft; var clickxinwebglcoords = 2.0 * (clickxrelativtocanvas- gl.drawingbufferwidth/2) / gl.drawingbufferwidth; gl.bufferdata(gl.array_buffer, new float32array([clickxinwebglcoords]), gl.static_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 (buff...
Textures from code - Web APIs
r/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main() { vec2 fragmentposition = 2.0*gl_pointcoord - 1.0; float distance = length(fragmentposition); float distancesqrd = distance * distance; gl_fragcolor = vec4( 0.2/distancesqrd, 0.1/distancesqrd, 0.0, 1.0 ); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment...
...nkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0, 0.0]), gl.static_draw); gl.vertexattribpointer(0, 2, gl.float, false, 0, 0); } 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) { ...
Lighting in WebGL - Web APIs
{ const numcomponents = 3; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.normal); gl.vertexattribpointer( programinfo.attriblocations.vertexnormal, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexnormal); } finally, we need to update the code that build...
... gl.uniformmatrix4fv( programinfo.uniformlocations.normalmatrix, false, normalmatrix); update the shaders now that all the data the shaders need is available to them, we need to update the code in the shaders themselves.
WebGL model view projection - Web APIs
var gl = this.gl; // create a buffer and bind the data var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); // setup the pointer to our attribute data (the triangles) gl.enablevertexattribarray(this.positionlocation); gl.vertexattribpointer(this.positionlocation, 3, gl.float, false, 0, 0); // setup the color uniform that will be shared across all triangles gl.uniform4fv(this.colorlocation, settings.color); // draw the triangles to the screen gl.drawarrays(gl.triangles, 0, 6); } the shaders are the bits of code written in glsl that take our data points and ultimately render them to the screen.
... gl.uniformmatrix4fv(this.locations.model, false, new float32array(this.transforms.model)); in the shader, each position vertex is first transformed into a homogeneous coordinate (a vec4 object), and then multiplied against the model matrix.
Signaling and video calling - Web APIs
function handleuserlistmsg(msg) { var i; var listelem = document.queryselector(".userlistbox"); while (listelem.firstchild) { listelem.removechild(listelem.firstchild); } msg.users.foreach(function(username) { var item = document.createelement("li"); item.appendchild(document.createtextnode(username)); item.addeventlistener("click", invite, false); listelem.appendchild(item); }); } after getting a reference to the <ul> which contains the list of user names into the variable listelem, we empty the list by removing each of its child elements.
...in our example, we add the track's stream to the <video> element that displays the incoming video: function handletrackevent(event) { document.getelementbyid("received_video").srcobject = event.streams[0]; document.getelementbyid("hangup-button").disabled = false; } the incoming stream is attached to the "received_video" <video> element, and the "hang up" <button> element is enabled so the user can hang up the call.
WebXR permissions and security - Web APIs
specifically: if the requestsession() call isn't coming from within the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler.
... if the document making the request isn't trustworthy, the request is denied and false is returned through the promise's fulfillment routine.
Using the Web Animations API - Web APIs
nommingcake.play(); } when a user holds their mouse down or presses their finger on the cake on a touch screen, we can now call growalice to make all the animations play: cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growalice, false); other useful methods in addition to pausing and playing, we can use the following animation methods: animation.finish() skips to the end of the animation.
...this is because the bottle changes her animation’s playbackrate from 1 to -1: var shrinkalice = function() { alicechange.playbackrate = -1; alicechange.play(); } bottle.addeventlistener("mousedown", shrinkalice, false); bottle.addeventlistener("touchstart", shrinkalice, false); in through the looking-glass, alice travels to a world where she must run to stay in place — and run twice as fast to move forward!
Web Audio API best practices - Web APIs
here is a simple example of creating the context from inside a click event: const button = document.queryselector('button'); button.addeventlistener('click', function() { const audioctx = new audiocontext(); }, false); if however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction.
... const audioctx = new audiocontext(); const button = document.queryselector('button'); button.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } }, false); you might instead be working with an offlineaudiocontext, in which case you can resume the suspended audio context with the startrendering() method.
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 xhr = new xmlhttprequest(); xhr.open("get", "/path/to/audio.ogg", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = functi...
...var isfinished = (src.playbackstate == src.finished_state); // new audiocontext code: var src = context.createbuffersource(); function endedhandler(event) { isfinished = true; } var isfinished = false; src.onended = endedhandler; the exact same changes have been applied to both audiobuffersourcenode and oscillatornode, so you can apply the same techniques to both kinds of nodes.
Background audio processing using AudioWorklet - Web APIs
returning false from the process() method tells the api that it should follow its normal logic and shut down your processor node if it deems it appropriate to do so.
...instead, it keeps the node alive if you return true and shuts it down if you return 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).
...but it is not needed for this simple demo, so we are just specifying one (which is actually the default anyway.) recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; starting the speech recognition after grabbing references to the output <div> and the html element (so we can output diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will star...
Window.confirm() - Web APIs
WebAPIWindowconfirm
return value a boolean indicating whether ok (true) or cancel (false) was selected.
... if a browser is ignoring in-page dialogs, then the returned value is always false.
window.location - Web APIs
WebAPIWindowlocation
pellentesque porttitor facilisis ultricies.</p> <p id="mybookmark2">[&nbsp;<span class="intlink" onclick="showbookmark('#mybookmark1');">go to bookmark #1</span> | <span class="intlink" onclick="showbookmark('#mybookmark1', false);">go to bookmark #1 without using location.hash</span> | <span class="intlink" onclick="showbookmark('#mybookmark3');">go to bookmark #3</span>&nbsp;]</p> <p>phasellus tempus fringilla nunc, eget sagittis orci molestie vel.
...llid); _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) { clearinterval(_scrollid); _scrollid = -1; } } if (window.addeventlistener) { window.addeventlistener("scroll", _chkowner, false); } else if (window.attachevent) { window.attachevent("onscroll", _chkowner); } return function (sbookmark, busehash) { var onode = document.queryselector(sbookmark); _scrolly = document.documentelement.scrolltop; _scr...
Window - Web APIs
WebAPIWindow
windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false).
... connection events offline fired when the browser has lost access to the network and the value of navigator.online has switched to false.
WindowEventHandlers.onhashchange - Web APIs
syntax using an event handler: window.onhashchange = funcref; using an html event handler: <body onhashchange="funcref();"> using an event listener: to add an event listener, use addeventlistener(): window.addeventlistener("hashchange", funcref, false); parameters funcref a reference to a function.
... function hashhandler() { console.log('the hash has changed!'); } window.addeventlistener('hashchange', hashhandler, false); overriding the hash this function sets a new hash dynamically, setting it randomly to one of two values.
WorkerGlobalScope - Web APIs
windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false).
... offline fired when the browser has lost access to the network and the value of navigator.online switched to false.
XRSystem - Web APIs
WebAPIXRSystem
resolves to false if the specified mode isn't supported.
... 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
otherwise, this property's value is false.
...otherwise, this property is false.
XRWebGLLayerInit.antialias - Web APIs
if this property is missing or is false, anti-aliasing is not desired.
...if false, anti-aliasing is not desired.
msCachingEnabled - Web APIs
if false, it is not written to disk.
...if false, it is not written to disk.
msCapsLockWarningOff - Web APIs
syntax document.mscapslockwarningoff = true; value type: boolean false: default.
... 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 o...
ARIA: row role - Accessibility
aria-expanded="false": row is currently collapsed.
...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.
ARIA: textbox role - Accessibility
if false is set, or the the attribute is omitted and defaults to false, the user expectation is that the control is a single line text box, and enter or return submits the form.
... keyboard interactions in a single-line use (when aria-multiline is false or not used), the return or enter key submits the form.
Web applications and ARIA FAQ - Accessibility
.tab-panel[aria-hidden="true"] { display: none; } .tab-panel[aria-hidden="false"] { display: block; } what about validation?
... document.getelementbyid("update-button").addeventlistener("click", function (e) { updateprogress(75); e.preventdefault(); }, false); } initdemo(); how do assistive technologies work?
Alerts - Accessibility
sg = document.createtextnode(amsg); newalert.appendchild(msg); document.body.appendchild(newalert); } function checkvalidity(aid, asearchterm, amsg) { var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); addalert(amsg); } else { elem.setattribute("aria-invalid", "false"); removeoldalert(); } } </script> the checkvalidity function the primary method in javascript used for form validation is the checkvalidity function.
... if the search term is found, the aria-invalid attribute is reset to “false”.
An overview of accessible web applications and widgets - Accessibility
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.
...javascript to update the aria-checked attribute var showtip = function(el) { el.setattribute('aria-hidden', 'false'); } role changes aria allows developers to declare a semantic role for an element that otherwise offers incorrect or no semantics.
Keyboard-navigable JavaScript widgets - Accessibility
if your event handler returns false, the event will not be propagated beyond your handler.
... for example: <span tabindex="-1" onkeydown="return handlekeydown();"> if handlekeydown() returns false, the event will be consumed, preventing the browser from performing any action based on the keystroke.
CSS Animations tips and tricks - CSS: Cascading Style Sheets
of course, we also need to add an event handler to our "run" button so it'll actually do something: document.queryselector(".runbutton").addeventlistener("click", play, false); result stopping an animation simply removing the animation-name applied to an element will make it jump or cut to its next state.
...idein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { margin-left: 0%; } } <h1 id="watchme">click me to stop</h1> let watchme = document.getelementbyid('watchme') watchme.classname = 'slidein' const listener = (e) => { watchme.classname = 'slidein stopped' } watchme.addeventlistener('click', () => watchme.addeventlistener('animationiteration', listener, false) ) demo https://jsfiddle.net/morenoh149/5ty5a4oy/ ...
Creating a cross-browser video player - Developer guides
of variables pointing to html elements are required: var videocontainer = document.getelementbyid('videocontainer'); var video = document.getelementbyid('video'); var videocontrols = document.getelementbyid('video-controls'); as mentioned earlier, the browser's default controls now need to be disabled, and the custom controls need to be displayed: // hide the default controls video.controls = false; // display the user defined video controls videocontrols.style.display = 'block'; with that done, a variable pointing to each of the buttons is now required: var playpause = document.getelementbyid('playpause'); var stop = document.getelementbyid('stop'); var mute = document.getelementbyid('mute'); var volinc = document.getelementbyid('volinc'); var voldec = document.getelementbyid('voldec')...
... defined as follows: var handlefullscreen = function() { if (isfullscreen()) { if (document.exitfullscreen) document.exitfullscreen(); else if (document.mozcancelfullscreen) document.mozcancelfullscreen(); else if (document.webkitcancelfullscreen) document.webkitcancelfullscreen(); else if (document.msexitfullscreen) document.msexitfullscreen(); setfullscreendata(false); } 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(t...
Creating and triggering events - Developer guides
*/ }, false); // dispatch the event.
...elem.addeventlistener('build', function (e) { // e.target matches elem }, false); // target can be any element or other eventtarget.
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
here's an example that watches changes over time to the color value: colorpicker.addeventlistener("input", updatefirst, false); colorpicker.addeventlistener("change", watchcolorpicker, false); function watchcolorpicker(event) { document.queryselectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } selecting the value if the <input> element's implementation of the color type on the user's browser doesn't support a color well, but is instead a text field for entering the color string di...
... var colorwell; var defaultcolor = "#0000ff"; window.addeventlistener("load", startup, false); initialization once the page is loaded, our load event handler, startup(), is called: function startup() { colorwell = document.queryselector("#colorwell"); colorwell.value = defaultcolor; colorwell.addeventlistener("input", updatefirst, false); colorwell.addeventlistener("change", updateall, false); colorwell.select(); } this gets a reference to the color <input> element in a v...
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
to disable video autoplay, autoplay="false" will not work; the video will autoplay if the attribute is there in the <video> tag at all.
...its default value is false, meaning that the audio will be played when the video is played.
contenteditable - HTML: Hypertext Markup Language
false, which indicates that the element is not editable.
... note that although its allowed values include true and false, this attribute is an enumerated one and not a boolean one.
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.
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
to correct this problem on the client side, simply ensure that the credentials flag's value is false when issuing your cors request.
... if using server-sent events, make sure eventsource.withcredentials is false (it's the default value).
Iterators and generators - JavaScript
function makerangeiterator(start = 0, end = infinity, step = 1) { let nextindex = start; let iterationcount = 0; const rangeiterator = { next: function() { let result; if (nextindex < end) { result = { value: nextindex, done: false } nextindex += step; iterationcount++; return result; } return { value: iterationcount, done: true } } }; return rangeiterator; } using the iterator then looks like this: const it = makerangeiterator(1, 10, 2); let result = it.next(); while (!result.done) { console.log(result.value); // 1 3 5 7 9 result = it.n...
... for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" [...'abc']; // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } gen().next(); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); a; // "a" advanced generators generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above).
Regular expressions - JavaScript
it returns true or false.
...if the match fails, the exec() method returns null (which coerces to false).
Working with objects - JavaScript
delete myobj.a; console.log ('a' in myobj); // output: "false" you can also use delete to delete a global variable if the var keyword was not used to declare the variable: g = 17; delete g; comparing objects in javascript, objects are a reference type.
... // two variables, two 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.
Memory Management - JavaScript
this automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management.
...null }; // allocates memory for an object and contained values // (like object) allocates memory for the array and // contained values var a = [1, null, 'abra']; function f(a) { return a + 2; } // allocates a function (which is a callable object) // function expressions also allocate an object someelement.addeventlistener('click', function() { someelement.style.backgroundcolor = 'blue'; }, false); allocation via function calls some function calls result in object allocation.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
in non-strict code, the operation returns false.
... 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); delete obj.score; // typeerror 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // typeerror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray.pop(); // typeerror there are also a few non-configurable properties built into javascript.
SyntaxError: missing } after function body - JavaScript
(function() { if (true) { return false; } ); oftentimes, indenting differently or double checking indentation helps to spot these errors.
... (function() { if (true) { return false; } }); ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
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.find() - JavaScript
if iscallable(predicate) is false, throw a typeerror exception.
... name }) => name === 'cherries' ); console.log(result) // { name: 'cherries', quantity: 5 } find a prime number in an array the following example finds an element in the array that is a prime number (or returns undefined if there is no prime number): function isprime(element, index, array) { let start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isprime)); // undefined, not found console.log([4, 5, 8, 12].find(isprime)); // 5 the following examples show that nonexistent and deleted elements are visited, and that the value passed to the callback is their value when visited: // declare array with no elements at indexes 2, 3, and 4 const array = [0,1,,,,5,6]; // shows al...
Array.prototype.findIndex() - JavaScript
if iscallable(predicate) is false, throw a typeerror exception.
... function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log([4, 6, 8, 9, 12].findindex(isprime)); // -1, not found console.log([4, 6, 7, 9, 12].findindex(isprime)); // 2 (array[2] is 7) find index using arrow function the following example finds the index of a fruit using an arrow function: const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; const index = fruits.findindex(fruit =>...
Array.from() - JavaScript
if mapfn is undefined, then let mapping be false.
...a if iscallable(mapfn) is false, throw a typeerror exception.
Array.prototype.length - JavaScript
property attributes of array.prototype.length writable yes enumerable no configurable no writable: if this attribute set to false, the value of the property cannot be changed.
... configurable: if this attribute set to false, any attempts to delete the property or change its attributes (writable, configurable, or enumerable) will fail.
Array.prototype.map() - JavaScript
if iscallable(callback) is false, throw a typeerror exception.
...call the defineownproperty internal method of a with arguments // pk, property descriptor // { value: mappedvalue, // writable: true, // enumerable: true, // configurable: true }, // and false.
Array - JavaScript
array.isarray() returns true if the argument is an array, or false otherwise.
... array.prototype.includes() determines whether the array contains a value, returning true or false as appropriate.
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.
Date.prototype.toLocaleTimeString() - JavaScript
to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e​.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats.
...can be customized using the options argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // an application may want to use utc and make that visible var options = { timezone: 'utc', timezonename: 'short' }; console.log(date.tolocaletimestring('en-us', options)); // → "3:00:00 am gmt" // sometimes even the us needs 24-hour time console.log(date.tolocaletimestring('en-us', { hour12: false })); // → "19:00:00" // show only hours and minutes, use options with the default locale - use an empty array console.log(date.tolocaletimestring([], { hour: '2-digit', minute: '2-digit' })); // → "20:01" specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tolocaletimestring' in that specification.
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.
Generator.prototype.throw() - JavaScript
has the value false if the iterator was able to produce the next value in the sequence.
... 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.
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 valid ...
... 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.
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.stringify([new number(3), new string('false'), new boolean(false)]); // '[3,"false",false]' // string-keyed arra...
...object, z: symbol('') }); // '{}' json.stringify({ [symbol('foo')]: 'foo' }); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, [symbol.for('foo')]); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { 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.
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.
...mymap.has('bar'); // returns false.
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.hypot() - JavaScript
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 ?
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; index++) { v...
...console.log(obj); // { "0": "a", "1": "b", "2": "c" } exceptions will interrupt the ongoing copying task const target = object.defineproperty({}, 'foo', { value: 1, writable: false }); // target.foo is a read-only property object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); // typeerror: "foo" is read-only // the exception is thrown when assigning target.foo console.log(target.bar); // 2, the first source was copied successfully.
Object.getOwnPropertyDescriptor() - JavaScript
.getownpropertydescriptor(o, 'bar'); // d is { // configurable: true, // enumerable: true, // value: 42, // writable: true // } o = { [symbol.for('baz')]: 73 } d = object.getownpropertydescriptor(o, symbol.for('baz')); // d is { // configurable: true, // enumerable: true, // value: 73, // writable: true // } o = {}; object.defineproperty(o, 'qux', { value: 8675309, writable: false, enumerable: false }); d = object.getownpropertydescriptor(o, 'qux'); // d is { // value: 8675309, // writable: false, // enumerable: false, // configurable: false // } non-object coercion in es5, if the first argument to this method is not an object (a primitive), then it will cause a typeerror.
... object.getownpropertydescriptor('foo', 0); // typeerror: "foo" is not an object // es5 code object.getownpropertydescriptor('foo', 0); // object returned by es2015 code: { // configurable: false, // enumerable: true, // value: "f", // writable: false // } specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptor' in that specification.
Object.getOwnPropertyNames() - JavaScript
// logs ["0", "1", "2"] // logging property names and values using array.foreach object.getownpropertynames(obj).foreach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "getfoo"] if you want only the enumerable properties, see object.keys() or use a for...in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with hasownproperty()).
...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 - JavaScript
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.
... var mime = function(name) { person.call(this, name); this.cantalk = false; }; mime.prototype = object.create(person.prototype); mime.prototype.constructor = mime; //if you don't set object.prototype.constructor to mime, //it will take prototype.constructor of person (parent).
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.
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.
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.dotall' in that specification.
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.
... false source the text of the pattern.
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.
String.prototype.charAt() - JavaScript
var str = 'a \ud87e\udc04 z'; // we could also use a non-bmp character directly for (var i = 0, chr; i < str.length; i++) { if ((chr = getwholechar(str, i)) === false) { continue; } // adapt this line at the top of each loop, passing in the whole string and // the current iteration and returning a variable to represent the // individual character console.log(chr); } function getwholechar(str, i) { var code = str.charcodeat(i); if (number.isnan(code)) { return ''; // position not found } if (code < 0xd800 || code > 0xdfff) { ret...
... without preceding high surrogate'; } var prev = str.charcodeat(i - 1); // (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 > prev || prev > 0xdbff) { throw 'low surrogate without preceding high surrogate'; } // we can pass over low surrogates now as the second component // in a pair which we have already processed return false; } in an ecmascript 2016 environment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does increment for an incrementing variable automatically (if the character warrants it in being a surrogate pair).
String.prototype.charCodeAt() - JavaScript
fixedcharcodeat('\ud800\udc00', 1); // false idx = idx || 0; var code = str.charcodeat(idx); var hi, low; // high surrogate (could change last hex to 0xdb7f // to treat high private surrogates // as single characters) if (0xd800 <= code && code <= 0xdbff) { hi = code; low = str.charcodeat(idx + 1); if (isnan(low)) { throw 'high surrogate not followed by ' + 'low surrogate in fixedcharcodeat()'; }...
... return ( (hi - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000; } if (0xdc00 <= code && code <= 0xdfff) { // low surrogate // we return false to allow loops to skip // this iteration since should have already handled // high surrogate above in the previous iteration return false; // hi = str.charcodeat(idx - 1); // low = code; // return ((hi - 0xd800) * 0x400) + // (low - 0xdc00) + 0x10000; } return code; } fixing charcodeat() to handle non-basic-multilingual-plane characters if their presence earlier in the string is known function knowncharcodeat(str, idx) { str += ''; var code, end = str.length; var surrogatepairs = /[\ud800-\udbff][\udc00-\udfff]/g; while ((surrogatepairs.exec(str)) != null) { var li = surrogatepai...
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.normalize() - JavaScript
let string1 = '\u00f1'; // ñ let string2 = '\u006e\u0303'; // ñ console.log(string1 === string2); // false console.log(string1.length); // 1 console.log(string2.length); // 2 the normalize() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters.
... you can use normalize() using the "nfkd" or "nfkc" arguments to produce a form of the string that will be the same for all compatible strings: let string1 = '\ufb00'; let string2 = '\u0066\u0066'; console.log(string1); // 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 ...
Symbol.unscopables - JavaScript
setting a property to false will make it scopable and thus it will 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.
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 definition of 'typedarray.protot...
WeakMap.prototype.delete() - JavaScript
false if the key is not found in the weakmap or if the key is not an object.
... wm.has(window); // returns false.
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.
WeakMap - JavaScript
weakmap.prototype.has(key) will return false afterwards.
... 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 this._wm.delete(k); }...
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.
WeakSet - JavaScript
weakset.prototype.has(value) will return false afterwards.
... 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.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).
eval() - JavaScript
} , false); closures are also helpful as a way to create parameterized functions without concatenating strings.
... 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 specification ecmascript (ecma-262)the definition of 'eval' in...
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.
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 logical 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.
Nullish coalescing operator (??) - JavaScript
function a() { console.log('a was called'); return undefined;} function b() { console.log('b was called'); return false;} function c() { console.log('c was called'); return "foo";} console.log( a() ??
...c() ); // logs "b was called" then "false" // as b() returned false (and not null or undefined), the right // hand side expression was not evaluated no chaining with and or or operators it is not possible to combine both the and (&&) and or operators (||) directly with ??.
Object initializer - JavaScript
in json the values can only be strings, numbers, arrays, true, false, null, or another (json) object.
... 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.
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 types console.log("3" !== 3); // true console.log(true !== 1); // true con...
...sole.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.
yield - JavaScript
the value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed.
... 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.
continue - JavaScript
each time continue is encountered, checkj reiterates until its condition returns false.
... when false is returned, the remainder of the checkiandj statement is completed.
do...while - JavaScript
the do...while statement creates a loop that executes a specified statement until the test condition evaluates to false.
...when condition evaluates to false, control passes to the statement following the do...while.
Statements and declarations - JavaScript
if the condition is false, another statement can be executed.
... iterations do...while creates a loop that executes a specified statement until the test condition evaluates to false.
Strict mode - JavaScript
writable global or property, assignment to a getter-only property, assignment to a new property on a non-extensible object) will throw in strict mode: 'use strict'; // assignment to a non-writable global var undefined = 5; // throws a typeerror var infinity = 5; // throws a typeerror // assignment to a non-writable property var obj1 = {}; object.defineproperty(obj1, 'x', { value: 42, writable: false }); obj1.x = 9; // throws a typeerror // assignment to a getter-only property var obj2 = { get x() { return 17; } }; obj2.x = 5; // throws a typeerror // assignment to a new property on a non-extensible object var fixed = {}; object.preventextensions(fixed); fixed.newprop = 'ohai'; // throws a typeerror third, strict mode makes attempts to delete undeletable properties throw (where before the...
... (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.
<munderover> - MathML
if false (default value), the overscript is a limit over the base expression.
... if false (default value), the underscript is a limit under the base expression.
externalResourcesRequired - SVG: Scalable Vector Graphics
usage notes value false | true default value false animatable no true this value indicates that resources external to the current document are required.
... false this value indicates that resources external to the current document are optional.
systemLanguage - SVG: Scalable Vector Graphics
otherwise it evaluates to "false".
...if a null string or empty string value is given, the attribute evaluates to "false".
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.
...otherwise, false.
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.
...if the expanded-name has a null namespace uri, the element-available function will return false.
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.
...otherwise, false.
Communicating using "port" - Archive of obsolete content
var pagemodscript = "window.addeventlistener('click', function(event) {" + " self.port.emit('click', event.target.tostring());" + " event.stoppropagation();" + " event.preventdefault();" + "}, false);" + "self.port.on('warning', function(message) {" + "window.alert(message);" + "});" var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.port.on('click', function(html) { worker.port.emit('warning', 'do not click this again'); }); } }); ...
Content Scripts - Archive of obsolete content
ile: self.data.url("content-script.js"), onattach: startlistening }); function startlistening(worker) { worker.port.on('click', function(html) { worker.port.emit('warning', 'do not click this again'); }); } // content-script.js window.addeventlistener('click', function(event) { self.port.emit('click', event.target.tostring()); event.stoppropagation(); event.preventdefault(); }, false); self.port.on('warning', function(message) { window.alert(message); }); in the add-on above there are two messages: click is sent from the page-mod to the add-on, when the user clicks an element in the page warning sends a silly string back to the page-mod from tab.attach() the tab.attach() method returns the worker you can use to communicate with the content script(s) you attached.
Porting the Library Detector - Archive of obsolete content
e widget's context, which listens for icon mouseover events and sends a message to main.js containing the name of the corresponding library: function setlibraryinfo(element) { self.port.emit('setlibraryinfo', element.target.title); } var elements = document.getelementsbytagname('img'); for (var i = 0; i &lt; elements.length; i++) { elements[i].addeventlistener('mouseover', setlibraryinfo, false); } one in the panel, which updates the panel's content with the library information: self.on("message", function(libraryinfo) { window.document.body.innerhtml = libraryinfo; }); finally main.js relays the library information from the widget to the panel: widget.port.on('setlibraryinfo', function(libraryinfo) { widget.panel.postmessage(libraryinfo); }); ...
context-menu - Archive of obsolete content
const { getmostrecentbrowserwindow } = require("sdk/window/utils"); var cm = require("sdk/context-menu"); var uuid = require('sdk/util/uuid').uuid(); var uuidstr = uuid.number.substring(1,37); cm.item({ data: uuidstr+"this is a tooltip", label: "just a tigger, will never show up", contentscript: 'self.on("context", function(){self.postmessage(); return false;})', onmessage: function(){ var cmitems = getmostrecentbrowserwindow().document.queryselectorall(".addon-context-menu-item[value^='"+ uuidstr +"']"); for(var i=0; i < cmitems.length; i++) cmitems[i].tooltiptext = cmitems[i].value.substring(36); } }); globals constructors item(options) creates a labeled menu item that can perform an action when clicked.
indexed-db - Archive of obsolete content
llback; var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var items = new array(); trans.oncomplete = function() { cb(items); } var keyrange = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) return; items.push(result.value.name); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitems(itemlist) { console.log(itemlist); } open("1"); var add = require("sdk/ui/button/action").actionbutton({ id: "add", label: "add", icon: "./add.png", onclick: function() { additem(require("sdk/tabs").activetab.title); } }); var list =...
request - Archive of obsolete content
defaults to false.
selection - Archive of obsolete content
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.
simple-prefs - Archive of obsolete content
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.
tabs - Archive of obsolete content
defaults to false.
url - Archive of obsolete content
isvaliduri("http://mozilla.org") would return true, whereas isvaliduri("mozilla.org") would return false.
lang/functional - Archive of obsolete content
pass {leading : false} to stop the function being called at the leading edge, and {trailing : false} to stop it being called at the trailing edge.
net/url - Archive of obsolete content
defaults to false if not provided.
preferences/service - Archive of obsolete content
example: var name = "extensions.checkcompatibility.nightly"; require("sdk/preferences/service").set(name, false); get(name, defaultvalue) gets the application preference name.
stylesheet/utils - Archive of obsolete content
returns boolean : true if the type given is valid, otherwise false.
system/runtime - Archive of obsolete content
globals properties insafemode this value is true if firefox was started in safe mode, otherwise false.
ui/button/action - Archive of obsolete content
defaults to false.
ui/toolbar - Archive of obsolete content
defaults to false.
util/object - Archive of obsolete content
rge } = 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 that other properties are merged into.
Creating annotations - Archive of obsolete content
it is initially off: var matchedelement = null; var originalbgcolor = null; var active = false; function resetmatchedelement() { if (matchedelement) { (matchedelement).css('background-color', originalbgcolor); (matchedelement).unbind('click.annotator'); } } self.on('message', function onmessage(activation) { active = activation; if (!active) { resetmatchedelement(); } }); this selector listens for occurrences of the jquery mouseenter event.
Display a Popup - Archive of obsolete content
text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; } }, false); // listen for the "show" event being sent from the // main add-on code.
Getting Started (jpm) - Archive of obsolete content
during development, or if you don't plan to distribute, you can open about:config and set xpinstall.signatures.required to false to run it unsigned.
Using XPCOM without chrome - Archive of obsolete content
notice the small l var bmlistener = bmlistener(); placesutils.bookmarks.addobserver(bmlistener, false); ...
Bookmarks - Archive of obsolete content
); }, onitemvisited: function(abookmarkid, avisitid, time) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is called when my add-on is unloaded onunload: function() { bmsvc.removeobserver(myext_bookmarklistener); }, dosomething: function() { alert("did something."); } }; see also nsinavbookmarksservice nsinavbookmarkobserver places using xpcom without chrome - bookmark observer ...
Customizing the download progress bar - Archive of obsolete content
em = 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"].
Dialogs and Prompts - Archive of obsolete content
if they return anything but false, the dialog will be closed.
File I/O - Archive of obsolete content
createinstance(components.interfaces.nsifileinputstream); istream.init(pngfile, -1, -1, false); var bstream = components.classes["@mozilla.org/binaryinputstream;1"].
HTML in XUL for rich tooltips - Archive of obsolete content
ementbyid("myhtmltipdiv"); //clear the html div element of any prior shown custom html while(div.firstchild) div.removechild(div.firstchild); //safely convert html string to a simple dom object, stripping it of javascript and more complex tags var injecthtml = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(txt, false, null, div); //attach the dom object to the html div element div.appendchild(injecthtml); } } window.addeventlistener('load', htmltip.onload, false); in the xul overlay, xmlns:html is used to enable html tags to be used inside the xul.
JS XPCOM - Archive of obsolete content
determining which interfaces an xpcom component supports to display a list of all interfaces that an xpcom component supports, do the following: // |c| is the xpcom component instance for each (i in components.interfaces) { if (c instanceof i) { alert(i); } } in this context, instanceof is the same as queryinterface except that it returns false instead of throwing an exception when |c| doesn't support interface |i|.
Label and description - Archive of obsolete content
note: if running in a xulrunner application add the following preferences to your default preferences file: pref("network.protocol-handler.expose.http", false); pref("network.protocol-handler.warn-external.http", false); change or add additional protocols (https or ftp) as needed.
Progress Listeners - Archive of obsolete content
listener", "nsisupportsweakreference"]), onlocationchange: function(aprogress, arequest, auri) { this.processnewurl(auri); }, onstatechange: function() {}, onprogresschange: function() {}, onstatuschange: function() {}, onsecuritychange: function() {} }; window.addeventlistener("load", function() { myextension.init() }, false); window.addeventlistener("unload", function() { myextension.uninit() }, false); note: if you use the same listener for more than one tab/window, use awebprogress.domwindow in the callback methods to obtain the tab/window which triggers the state change or event.
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).
Toolbar - Archive of obsolete content
{ let elem = document.getelementbyid(afterid); if (elem && elem.parentnode == toolbar) before = elem.nextelementsibling; } toolbar.insertitem(id, before); toolbar.setattribute("currentset", toolbar.currentset); document.persist(toolbar.id, "currentset"); if (toolbarid == "addon-bar") toolbar.collapsed = false; } } if (firstrun) { installbutton("nav-bar", "my-extension-navbar-button"); // the "addon-bar" is available since firefox 4 installbutton("addon-bar", "my-extension-addon-bar-button"); } ...
Windows - Archive of obsolete content
example var startpos = null; function mousedown(event) { startpos = [event.clientx, event.clienty]; } function mousemove(event) { if (startpos) { var newx = event.screenx - startpos[0]; var newy = event.screeny - startpos[1]; window.moveto(newx, newy); } } function mouseup(event) { startpos = null; } window.addeventlistener("mousedown", mousedown, false); window.addeventlistener("mouseup", mouseup, false); window.addeventlistener("mousemove", mousemove, false); xul titlebar element xul applications can take advantage of the titlebar element to achieve a similar result without extra javascript code.
xml:base support in old browsers - Archive of obsolete content
// var ns = 'http://www.w3.org/xml/1998/namespace'; var att, protocolpos; var xmlbase = ''; var abs = false; // avoid loop if node is not present if (!thisitem || !thisitem.nodename) { return xmlbase; } // check present element and higher up for xml:base // now check for the next matching local name up in the hierarchy (until the document root) while (thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { att = thisitem.getattribute('xml:base'); // xml: namespaces...
getAttributeNS - Archive of obsolete content
function getattributenswrapper (thisitem, ns, nsatt) { if (thisitem === null) { return false; } if (thisitem.getattributens) { return thisitem.getattributens(ns, nsatt); } else if (ns === null) { return thisitem.getattribute(nsatt); } else if (ns === 'http://www.w3.org/xml/1998/namespace') { // this is assumed so don't try to get an xmlns for the 'xml' prefix return thisitem.getattribute('xml:'+nsatt); // prefix must be 'xml' per the specs ...
Communication between HTML and your extension - Archive of obsolete content
if (doc && doc.addeventlistener) doc.addeventlistener("my-custom-event", myextension.customreceived, false); since the event is dispatched after the element in the html is updated by the statuschanged function, the element that extension is looking for is there to find.
Extension Versioning, Update and Compatibility - Archive of obsolete content
simply create the boolean preference extensions.checkcompatibility and set it to false.
How to convert an overlay extension to restartless - Archive of obsolete content
instead of directly calling your tear down function, make your unloadfromwindow() something like this: function unloadfromwindow(window) { var event = window.document.createevent("event"); event.initevent("myaddonname-unload",false,false); window.dispatchevent(event); } in each window you can then register on startup to listen for your custom "myaddonname-unload" event and just tear down and clean up when that event or a regular "unload" event comes in.
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.
Adding sidebars - Archive of obsolete content
<menupopup id="viewsidebarmenu"> <menuitem id="xulschoolhello-sidebar" label="&xulschoolhello.sidebar.title;" accesskey="&xulschoolhello.sidebar.accesskey;" type="checkbox" autocheck="false" group="sidebar" sidebarurl="chrome://xulschoolhello/content/sidebar.xul" sidebartitle="&xulschoolhello.sidebar.title;" oncommand="togglesidebar('xulschoolhello-sidebar');" /> </menupopup> the example in the mdc page includes a shortcut key combination to toggle the new sidebar.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
// fake a command event var event = document.createevent("events"); event.initevent("command", true, true); document.getelementbyid("mymenu").dispatchevent(event); // fake a mouse click var mouseevent = document.createevent("mouseevents"); event.initmouseevent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.getelementbyid("mylabel").dispatchevent(mouseevent); please see the corresponding documentation on how to use and initialize particular event types.
Handling Preferences - Archive of obsolete content
preference listeners the xpcom way to add a listener was mentioned in the xpcom section when describing the queryinterface method: this._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.addobserver(prefname, this, false); this._prefservice.queryinterface(ci.nsiprefbranch); all the qi'ing is necessary because the addobserver method is in a different interface, and other than for adding and removing observers, we use the nsiprefbranch interface for everything related to preferences.
JavaScript Object Management - Archive of obsolete content
} // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs.
Security best practices in extensions - Archive of obsolete content
frame.docshell.allowimages = false; frame.docshell.allowjavascript = false; frame.docshell.allowplugins = false; there are more examples listed in the document listed above in this section.
Session store API - Archive of obsolete content
{ var tab = event.originaltarget; /* the tab being restored */ var uri = tab.linkedbrowser.contentdocument.location; /* the tab's uri */ components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice) .logstringmessage("restoring tab: " + uri); }; document.addeventlistener("sstabrestoring", myextensionhandlerestore, false); simply replace the contents of the function myextensionhandlerestore() with whatever you need to do when the tab is restored.
Setting up an extension development environment - Archive of obsolete content
devtools.debugger.prompt-connection = false.
XUL user interfaces - Archive of obsolete content
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 === false || 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.
Creating a dynamic status bar extension - Archive of obsolete content
we use the window.addeventlistener() dom function to tell firefox to call the stockwatcher.startup() function when a new browser window is opened: window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); our new extension has two primary functions: startup() and refreshinformation().
DOMSubtreeModified - Archive of obsolete content
document.body.addeventlistener('domsubtreemodified', function () { document.title = 'dom changed at ' + new date(); }, false); ...
MozOrientation - Archive of obsolete content
the two you can do something like this: function orientationhandler(evt){ // for ff3.6+ if (!evt.gamma && !evt.beta) { evt.gamma = -(evt.x * (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.
chargingchange - Archive of obsolete content
returns false if the battery is discharging.
Index - Archive of obsolete content
setting this property to false is the same as never having set the property.
Same-origin policy for file: URIs - Archive of obsolete content
the new security.fileuri.strict_origin_policy preference, which defaults to true, can be set to false if the user doesn't want to strictly enforce the same origin policy on file: uris.
Visualizing an audio spectrum - Archive of obsolete content
var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum = new float32array(buffersize/2); this.real = new float32array(buffersize); this.imag = new float32a...
Autodial for Windows NT - Archive of obsolete content
a pref to disable users can bypass the feature altogether by setting the pref network.autodial-helper.enabled to false.
Automated testing tips and tricks - Archive of obsolete content
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 use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Creating a Firefox sidebar extension - Archive of obsolete content
s="viewemptysidebar" /> </menupopup> <keyset id="mainkeyset"> <key id="key_openemptysidebar" command="viewemptysidebar" key="&openemptysidebar.commandkey;" modifiers="&openemptysidebar.modifierskey;" /> </keyset> <broadcasterset id="mainbroadcasterset"> <broadcaster id="viewemptysidebar" label="&emptysidebar.title;" autocheck="false" type="checkbox" group="sidebar" sidebarurl="chrome://emptysidebar/content/emptysidebar.xul" sidebartitle="&emptysidebar.title;" oncommand="togglesidebar('viewemptysidebar');" /> </broadcasterset> </overlay> the overlay file consists of three entries, the menu definition, shortcut keys and the broadcaster.
Using Dehydra - Archive of obsolete content
*/ 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 -fplug...
Drag and Drop - Archive of obsolete content
set the value to false if it doesn't make sense to drop the object on it.
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) { // this...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
if any of those steps fails, the function returns false so that another content listener will be looked for.
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.
Basics - Archive of obsolete content
titlethe head of the notification message.string bodythe messagestringfalse iconthe url of an .ico file.string jetpack.notifications.show("hello world");var mybody = " my first message body on jetpack";var myicon = "http://www.mozilla.com/favicon.ico";jetpack.notifications.show({title: "my first message on jetpack", body: mybody, icon: myicon}); class tabs in this class you can find information about the tabs in your firefox window.
Notifications - Archive of obsolete content
titlethe head of the notification message.string bodythe message itself.stringfalse iconthe url of an .ico file.string jetpack.notifications.show("hello world"); var mybody = " my first message body on jetpack"; var myicon = "http://www.mozilla.com/favicon.ico"; jetpack.notifications.show({title: "my first message on jetpack", body: mybody, icon: myicon}); ...
LIR - Archive of obsolete content
n 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 a lir_xbarrier cause no code to ...
New Security Model for Web Services - Archive of obsolete content
) return pr_true if access granted else pr_false void invalidatecache(in string atransporturi); invalidate cached entry for the given transport uri.
Scripting - Archive of obsolete content
returning false causes the application to terminate.
New Skin Notes - Archive of obsolete content
this is not what user expects (well, i don't expect sites to style visited and non-visited links the same), and it's false that other documentation sites do this (i just checked apple's and microsoft's sites).
Safely loading URIs - Archive of obsolete content
this boolean preference, which defaults to true, can be set to false if the user doesn't want to strictly enforce the same origin policy on file: uris.
The life of an HTML HTTP request - Archive of obsolete content
this argument is always pr_false when the content sink calls appendchild.
Treehydra Manual - Archive of obsolete content
it is also acceptable for meet to return a value that contains the intersection--this may cause the analysis to have more false positives but will not introduce false negatives.
Venkman Introduction - Archive of obsolete content
in the interactive session's input field, enter this.fpaused venkman evaluates the expression, giving you [boolean] false back.
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; ...
modDateChanged - Archive of obsolete content
example filesource1 = getfolder("program", "file1.txt"); filesource2 = getfolder("program", "file2.txt"); err1 = file.moddate(filesource1); // the baseline returned err2 = file.moddatechanged(filesource1, err1); logcomment("file.moddatechanged should return 'false' = " + err2); // the reason it expects false is we're comparing // the return 'time stamp' value for // file1.txt with the actual file1.txt itself.
confirm - Archive of obsolete content
var check = { value: false }; var button = confirm("are you sure you want to install foobar 0.1?", "confirm", std_yes_no_buttons, null, null, null, "install fluxcompensator 0.4 as well", check); returns the return value is an integer indicating which button the user selected: ...
execute - Archive of obsolete content
default is false.
Properties - Archive of obsolete content
note that due to branching (different versions of gecko with different feature sets might be built on the same day), using this property to "detect" the application version may produce false results.
writeString - Archive of obsolete content
returns true if successfully scheduled, otherwise, false.
Installer Script - Archive of obsolete content
return(false); 16.
Learn XPI Installer Scripting by Example - Archive of obsolete content
filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spacerequired + " k"); logcomment(" available: " + spaceavailable + " k"); return(false); } return(true); } in the verifydiskspace block, filegetdiskspaceavailable is called with dirpath as its expected input.
movetoclick - Archive of obsolete content
if false, clicking the slide area moves the thumb only one increment in that direction.
norestorefocus - Archive of obsolete content
« xul reference home norestorefocus type: boolean if false, the default value, then when the panel is hidden, the keyboard focus will be restored to whatever had the focus before the panel was opened.
alwaysopenpopup - Archive of obsolete content
if false, the default value, the popup will be hidden.
autocheck - Archive of obsolete content
if this attribute is false, the checked state must be adjusted manually.
autoFillAfterMatch - Archive of obsolete content
if false, only the text that hasn't been entered yet will be filled in.
autofill - Archive of obsolete content
if false, the default, the value will not be filled in until the user selects an item.
autoscroll - Archive of obsolete content
« xul reference home autoscroll type: boolean set to false to disable autoscroll for this browser.
buttons - Archive of obsolete content
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).
checkState - Archive of obsolete content
if you wish to have different behavior for how the states are adjusted, set the autocheck attribute to false and adjust the state with a script.
clicktoscroll - Archive of obsolete content
if false, the mouse must be hovered over the arrows to scroll automatically.
completedefaultindex - Archive of obsolete content
if set to false or omitted, the value must be selected from the list.
panel.consumeoutsideclicks - Archive of obsolete content
if set to false, the rollup event is not consumed.
disableautocomplete - Archive of obsolete content
if false, the default, autocomplete is enabled.
disableautoselect - Archive of obsolete content
if this attribute is false, the selection is never updated to match the text box.
disabled - 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.
fixed - Archive of obsolete content
if false or not specified, the user can adjust the size of the column, typically by dragging the column header with the mouse.
forcecomplete - Archive of obsolete content
if false, it will only be filled in when the user selects an item.
grippyhidden - Archive of obsolete content
when set to false, the default, the grippy will be shown.
handleCtrlTab - Archive of obsolete content
if this attribute is set to false, these keys do not navigate between tabs.
hidespinbuttons - Archive of obsolete content
the default value is false.
ignorecase - Archive of obsolete content
otherwise, the default value is false, to indicate that the value should match with the same case.
iscontainer - Archive of obsolete content
false: the rule will only match nodes that are not marked as containers.
isempty - Archive of obsolete content
false: the rule will only match nodes that contain one or more child elements.
lightweightthemes - Archive of obsolete content
« xul reference home lightweightthemes type: boolean true if the window supports lightweight themes, otherwise false.
multiline - Archive of obsolete content
if false, the textbox only allows entry of one line.
negate - Archive of obsolete content
the where clause matches if the condition is false, and does not match if the condition is true.
noautofocus - Archive of obsolete content
« xul reference home noautofocus type: boolean if false, the default value, the currently focused element will be unfocused whenever the popup is opened or closed.
noautohide - Archive of obsolete content
« xul reference home noautohide type: boolean if this attribute is set to false or omitted, the tooltip will automatically disappear after a few seconds.
noinitialfocus - Archive of obsolete content
« xul reference homenoinitialfocustype: booleanif false, the default value, the element is considered when determining which element should be initially focused in a dialog.
onbeforeaccept - Archive of obsolete content
returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527).
onpopupshowing - Archive of obsolete content
returning false from this event handler prevents the popup from appearing.
panel.ignorekeys - Archive of obsolete content
« xul reference home ignorekeys type: boolean if false, the default value, the escape key may be used to close the panel.
panel.noautohide - Archive of obsolete content
« xul reference home noautohide type: boolean if false, the default value, the panel will be hidden when the user clicks outside the panel or switches focus to another application.
persist - Archive of obsolete content
persistence will not remember the absence of an attribute, so for boolean attributes like checked where absence means false, you will need to explicitly set the attribute to false before the window closes (bug 15232).
preference.type - Archive of obsolete content
bool a boolean set to either true or false.
setfocus - Archive of obsolete content
if this attribute is false, the focus does not change during navigation.
showcaret - Archive of obsolete content
default is false.
smoothscroll - Archive of obsolete content
« xul reference home smoothscroll type: boolean true initially enables smooth scrolling for the corresponding arrowscrollbox, false disables it.
tabscrolling - Archive of obsolete content
if false, the default, the tab key moves the focus to the next element.
textbox.autoFill - Archive of obsolete content
if false, the default, the value will not be filled in until the user selects an item.
textbox.disableAutocomplete - Archive of obsolete content
if false, the default, autocomplete is enabled.
textbox.disablehistory - Archive of obsolete content
« xul reference home disablehistory obsolete since gecko 2.0 type: boolean note: applies to: thunderbird and seamonkeyif false, an arrow button will appear on the end of the textbox which will open a dropdown menu of all available results.
textbox.forceComplete - Archive of obsolete content
if false, it will only be filled in when the user selects an item.
textbox.tabScrolling - Archive of obsolete content
if false, the default, the tab key moves the focus to the next element.as of gecko 1.9.1, this attribute is now always specified in lower case.
treecol.editable - Archive of obsolete content
individual treecell elements in the column may be marked editable="false" in order to disable editing.
Building accessible custom components in XUL - Archive of obsolete content
r(e) { var textbox = e.target; settimeout(function() { done_edit(textbox, true); }, 0); } function editable_cell_keypress(e) { var textbox = e.target; switch (e.keycode) { case key_enter: settimeout(function() { var label = done_edit(textbox, true); label.focus(); }, 0); break; case key_escape: settimeout(function() { var label = done_edit(textbox, false); label.focus(); }, 0); break; } } </code> with this new code, we can now navigate to a specific cell within the spreadsheet and press enter to edit the value.
close - Archive of obsolete content
example window.addeventlistener("close", function( event ) { // make the close button ineffective event.preventdefault(); }, false); ...
Accessing Files - Archive of obsolete content
the exists method returns true if the file is present and false if it is not.
Working With Directories - Archive of obsolete content
this method returns true if a file object returned by nsiscriptableio.getfile() refers to a directory, and false otherwise.
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.
Reading from Files - Archive of obsolete content
the following methods are available: readboolean will read a single byte from a stream and return false if the byte is zero and true if the byte has a non-zero value.
Writing to Files - Archive of obsolete content
if the argument is false, 0 is written, and if the argument is true, 1 is written.
How to implement a custom XUL query processor component - Archive of obsolete content
sult function templateresult(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.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);"/> ...
List of commands - Archive of obsolete content
r cmd_newnavigatortab cmd_newtabwithtarget cmd_openhelp 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.
appendNotification - Archive of obsolete content
nction 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 = { isdefault: false, accesskey: "1", label: "button 1", callback: testnotificationbutton1callback, type: "", // if a popup, then must be: "menu-button" or "menu".
checkAdjacentElement - Archive of obsolete content
if it is false, the previous radio button is selected.
insertItem - Archive of obsolete content
otherwise, if the beforepermanent argument is false, the new item is added to the end of the toolbar.
loadOneTab - Archive of obsolete content
parameters inbackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab.
moveByOffset - Archive of obsolete content
if isselectingrange is false, any existing selection is cleared.
removeAllNotifications - Archive of obsolete content
if immediate is false, the notifications are removed using a slide transition.
ContextMenus - Archive of obsolete content
to show an item, set its hidden property to false.
Extensions - Archive of obsolete content
function init() { var contextmenu = document.getelementbyid("contentareacontextmenu"); if (contextmenu) contextmenu.addeventlistener("popupshowing", thumbnailsshowhideitems, false); } function thumbnailsshowhideitems(event) { var show = document.getelementbyid("thumbnail-show"); show.hidden = (document.popupnode.localname != "img"); } the init function should be called within the handler for the load event so that the popupshowing event handler is hooked up before it would be opened by the user.
MenuModification - Archive of obsolete content
the first time the function is called, the haschildnodes method will return false, however the second time, the method will return true as the items have already been added to the menu.
Panels - Archive of obsolete content
for example, the following would open a panel underneath a button: panel.openpopup(button, "after_start", 0, 0, false, false); likewise, the openpopupatscreen method will open a panel at a specific screen position.
PopupEvents - Archive of obsolete content
<script> function openfilemenu() { var filemenu = document.getelementbyid("file-menu"); filemenu.addeventlistener("popupshown", filemenuopened, false); filemenu.open = true; } function filemenuopened(event) { if (event.target != document.getelementbyid("file-menupopup")) return; var filemenu = document.getelementbyid("file-menu"); filemenu.removeeventlistener("popupshown", filemenuopened, false); var openmenu = document.getelementbyid("open-menu"); openmenu.open = true; } </script> <menu id="file-menu" label="file"> <menu...
colorpicker.open - Archive of obsolete content
set this property to true to open the popup or false to close the popup.
controllers - Archive of obsolete content
ler example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getelementbyid("thelist"); var listcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_delete"); }, iscommandenabled : function(cmd){ if (cmd == "cmd_delete") return (list.selecteditem != null); return false; }, docommand : function(cmd){ list.removeitemat(list.selectedindex); }, onevent : function(evt){ } }; list.controllers.appendcontroller(listcontroller); } </script> <listbox id="thelist"> <listitem label="ocean"/> <listitem label="desert"/> <listitem label="jungle"/> <listitem label="swamp"/> </listbox> </window> ...
datepicker.open - Archive of obsolete content
for non-popup datepickers, this property is always false.
isPM - Archive of obsolete content
ArchiveMozillaXULPropertyisPM
« xul reference ispm type: boolean if false, the hour is between 0 and 11, and if true, the hour is 12 or greater.
menu.open - Archive of obsolete content
the menu may be opened by setting the open property to true and closed by setting it to false.
selected - Archive of obsolete content
« xul reference selected type: boolean this property's value is true if this element is selected, or false if it is not.
Sorting and filtering a custom tree view - Archive of obsolete content
m tree view stuff function treeview(table) { this.rowcount = table.length; this.getcelltext = function(row, col) { return table[row][col.id]; }; this.getcellvalue = function(row, col) { return table[row][col.id]; }; this.settree = function(treebox) { this.treebox = treebox; }; this.iseditable = function(row, col) { return col.editable; }; this.iscontainer = function(row){ return false; }; this.isseparator = function(row){ return false; }; this.issorted = function(){ return false; }; this.getlevel = function(row){ return 0; }; this.getimagesrc = function(row,col){ return null; }; this.getrowproperties = function(row,props){}; this.getcellproperties = function(row,col,props){}; this.getcolumnproperties = function(colid,col,props){}; this.cycleheader = function(col, elem)...
Building Trees - Archive of obsolete content
the value attribute may also be used for checkbox columns by setting it to either true or false.
Rule Compilation - Archive of obsolete content
if you show the vbox by setting the hidden state to false, the template builder will be invoked and the content will be generated.
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.
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 id="row7" clas...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
let button = doc.createelement("toolbarbutton"); button.setattribute("id", button_id); button.setattribute("label", "replace bookmark"); button.setattribute("class", "toolbarbutton-1 chromeclass-toolbar-additional"); button.setattribute("tooltiptext", "replace an existing bookmark"); button.style.liststyleimage = "url(" + icon + ")"; button.addeventlistener("command", main.action, false); toolbox.palette.appendchild(button); this code is thanks to dgutov and is seen in full context at his repository here at github: dgutov / bmreplace / bootstrap.js.
Toolbar customization events - Archive of obsolete content
window.addeventlistener("beforecustomization", customizestart, false); window.addeventlistener("aftercustomization", customizeend, false); window.addeventlistener("customizationchange", customizechange, false); function customizestart(e) { let thetoolbox = e.target; /* now we know the user has started customizing */ } function customizeend(e) { let thetoolbox = e.target; /* the user has finished customizing */ } function customizechange(e) { let theto...
Adding Event Handlers - Archive of obsolete content
you can also listen during the bubbling phase by setting the last argument to false.
Box Objects - Archive of obsolete content
{ 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="thelabel" value="i am a label"/> note that if you hide and collapse the label, it will be treated ...
Creating Dialogs - Archive of obsolete content
if the dialog shouldn't be closed, false should be returned instead.
Manifest Files - Archive of obsolete content
if false, it will not appear.
More Event Handlers - Archive of obsolete content
example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem label="plastic"/> </menupopup> </button> alternatively, for attribute event listeners, you can just return false from the code.
Tree Selection - Archive of obsolete content
if false, all existing selected rows will be deselected first.
Using spell checking in XUL - Archive of obsolete content
this method returns true if the word is correctly spelled, or false if it's not.
XULBrowserWindow - Archive of obsolete content
return value true if chrome should be hidden while displaying the specified location; otherwise false.
XUL element attributes - Archive of obsolete content
persistence will not remember the absence of an attribute, so for boolean attributes like checked where absence means false, you will need to explicitly set the attribute to false before the window closes (bug 15232).
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.
Accessibility/XUL Accessibility Reference - Archive of obsolete content
items are read per line as in "pearl female gray" listitem see listbox menuitem see menulist and menubar menubar <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=...
XUL accessibility tool - Archive of obsolete content
possible false positives in some of the other tests processing is slower than we would like.
autohide - Archive of obsolete content
when set to false, the default, the toolbar is visible.
clicktoscroll - Archive of obsolete content
if false, the content will scroll automatically when the cursor hovers over either arrow.
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.
description - 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.
dialog - Archive of obsolete content
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).
editor - Archive of obsolete content
ent.designmode = 'on'; } </script> <editor id="myeditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> once editable, the document can have special formatting and other html pieces added to it using the document.execcommand method: var editor = document.getelementbyid("myeditor"); // toggle bold for the current selection editor.contentdocument.execcommand("bold", false, null); see the midas overview for more command strings.
iframe - Archive of obsolete content
default is false.
key - Archive of obsolete content
ArchiveMozillaXULkey
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.
keyset - 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.
label - Archive of obsolete content
ArchiveMozillaXULlabel
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.
listcell - 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.
listhead - 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.
listheader - 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.
menubar - Archive of obsolete content
when set to false, the default, the grippy will be shown.
notificationbox - Archive of obsolete content
if immediate is false, the notifications are removed using a slide transition.
prefpane - Archive of obsolete content
selected type: boolean this property's value is true if this element is selected, or false if it is not.
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) ?
tabbox - Archive of obsolete content
if this attribute is set to false, these keys do not navigate between tabs.
window - Archive of obsolete content
lightweightthemes type: boolean true if the window supports lightweight themes, otherwise false.
Building XULRunner with Python - Archive of obsolete content
for example def onload(): btntest = document.getelementbyid("btntest") btntest.addeventlistener('command', ontest, false) def ontest(): window.alert('button activated') window.addeventlistener('load', onload, false) one possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when xulrunner launches.
Getting started with XULRunner - Archive of obsolete content
main.js: function showmore() { document.getelementbyid("more-text").hidden = false; } for more information about xul see: xul.
MacFAQ - Archive of obsolete content
erface(components.interfaces.nsicommandline); for (var i = 0; i < cmdline.length; ++i) { debug(cmdline.getargument(i)) } } catch(ex) { debug(window.arguments[0]) // do something with window.arguments[0] //nspreferences.setunicharpref("myxul.cmdlinevalue", window.arguments[0]) } window.addeventlistener("load", checkotherwindows , false); } ]]></script> </window> ...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
req = new soaprequest(url, body); req.action = ns + '#' + method; soapclient.sendrequest(req, callback); diff between jqsoapclient.js and sasoapclient.js 42c42 < var jsout = $.xmltojson(xdata.responsexml); --- > var jsout = xmlobjectifier.xmltojson(xdata.responsexml); 46,60c46,62 < $.ajax({ < type: "post", < url: soapclient.proxy, < datatype: "xml", < processdata: false, < data: content, < complete: getresponse, < contenttype: soapclient.contenttype + "; charset=\"" + soapclient.charset + "\"", < beforesend: function(req) { < req.setrequestheader("method", "post"); < req.setrequestheader("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheader("s...
calICalendarView - Archive of obsolete content
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.
Mozprofile - Archive of obsolete content
= firefoxprofile(preferences=[("accessibility.typeaheadfind.flashbar", 0)]) using a json blob file: mozprofile --preferences myprefs.json using a .ini file: mozprofile --preferences myprefs.ini via the command line: mozprofile --pref key:value --pref key:value [...] when setting preferences from an .ini file or the --pref switch, the value will be interpolated as an integer or a boolean (true/false) if possible.
xbDesignMode.js - Archive of obsolete content
ordocument = this.miframeelement.contentwindow.document; this.meditordocument.designmode = "on"; // ie needs to reget the document element after designmode was set this.meditordocument = this.miframeelement.contentwindow.document; } } xbdesignmode.prototype.execcommand = function (acommandname, aparam){ if (this.meditordocument) this.meditordocument.execcommand(acommandname, false, aparam); else throw "no meditordocument found"; } xbdesignmode.prototype.setcsscreation = function (ausecss){ if (this.meditordocument) this.meditordocument.execcommand("usecss", false, ausecss); else throw "no meditordocument found"; } ...
2006-11-24 - Archive of obsolete content
a user questions if there is something broken in a nightly build since the user keeps getting this error from the trunk: "firefox.exe - application error: the application failed to initialize properly." removal of false positives in firefox 2 phishing a user inquires how to remove false positives from the firefox phising filters.
NPN_Enumerate - Archive of obsolete content
returns true if the names of the properties and methods were successfully retrieved, otherwise false.
NPN_Evaluate - Archive of obsolete content
returns true if the script was evaluated successfully, otherwise false.
NPN_GetProperty - Archive of obsolete content
returns true if the value was retrieved successfully, otherwise false.
NPN_GetValue - Archive of obsolete content
ntext: unix only: returns the application's xtappcontext npnvnetscapewindow: ms windows and unix/x11 only: ms windows: gets the native window on which plug-in drawing occurs; returns hwnd unix/x11: gets the browser toplevel window in which the plug-in is displayed; returns window npnvjavascriptenabledbool: tells whether javascript is enabled; true=javascript enabled, false=not enabled npnvasdenabledbool: tells whether smartupdate (former name: asd) is enabled; true=smartupdate enabled, false=not enabled npnvisofflinebool: tells whether offline mode is enabled; true=offline mode enabled, false=not enabled npnvtoolkit: npnvsupportsxembedbool: npnvwindownpobject: returns the npobject * pointer for the dom window object; see getting the page url in npapi...
NPN_HasMethod - Archive of obsolete content
returns true if the method exists on the specified object, otherwise false.
NPN_HasProperty - Archive of obsolete content
returns true if the property exists on the specified object, otherwise false.
NPN_IdentifierIsString - Archive of obsolete content
returns true if the identifier is a string identifier, or false otherwise.
NPN_PostURLNotify - Archive of obsolete content
false: post the raw data in buf.
NPN_RemoveProperty - Archive of obsolete content
returns true if the property was removed successfully, otherwise false.
NPN_SetProperty - Archive of obsolete content
returns true if the value was set successfully, otherwise false.
NPP_HandleEvent - Archive of obsolete content
if the plug-in ignores the event, the function returns false.
NPP_NewStream - Archive of obsolete content
false: not seekable.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
nperror np_initialize(npnetscapefuncs* nstable, nppluginfuncs* pluginfuncs) { nperror err = nperr_no_error; prbool supportsxembed = pr_false; npntoolkittype toolkit = 0; [ code that copies all of the function tables and does ] [ other standard checks ] /* * make sure that the browser supports functionality we care * about.
Introduction to Public-Key Cryptography - Archive of obsolete content
any attempt to modify data or substitute a false message for a legitimate one will be detected.
Vulnerabilities - Archive of obsolete content
however, an attacker could generate false arp messages to poison a system’s arp table and thereby launch a denial-of-service or a man-in-the-middle attack.
Sunbird Theme Tutorial - Archive of obsolete content
add the line: pref("extensions.dss.enabled", false); save the file.
Common Firefox theme issues and solutions - Archive of obsolete content
to accomplish this copy the file chrome://mozapps/skin/extensions/extensions.svg from the default theme into the mozapps/extensions/ folder of your theme and add the following style rule to the css file extensions.css: .addon[active="false"] .icon { filter: url("chrome://mozapps/skin/extensions/extensions.svg#greyscale"); opacity:0.3; } about:memory about:memory nodes do not collapse the styling of about:memory is a little messed up in that nodes do not collapse as they should when clicked on.
Theme changes in Firefox 2 - Archive of obsolete content
menulist#name[droppable="false"] menulist#name[droppable="false"] > .menulist-editable-box menulist#name[droppable="false"] > .menulist-editable-box > html|*.textbox-input menulist#name[droppable="false"] > .menulist-dropmarker menulist#name[droppable="false"] > menupopup this file styles addbookmark2.xul.
Theme changes in Firefox 4 - Archive of obsolete content
note: when extracting omni.jar, you may incorrectly get false warnings from some virus protection software.
Using workers in extensions - Archive of obsolete content
let's take a look: startup: function() { // register to receive notifications of preference changes this.prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice) .getbranch("stockwatcher2."); this.prefs.queryinterface(components.interfaces.nsiprefbranch2); this.prefs.addobserver("", this, false); this.tickersymbol = this.prefs.getcharpref("symbol").touppercase(); this.worker = new worker("chrome://stockwatcher2/content/ticker_worker.js"); // small little dance to get 'this' to refer to stockwatcher, not the // worker, when a message is received.
Browser Detection and Cross Browser Support - Archive of obsolete content
= ua.substring(rvstart+3, rvend); var rvparts = rv.split('.'); var exp = 1; for (var i = 0; i < rvparts.length; i++) { 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 tech...
-ms-filter - Archive of obsolete content
.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.
Processing XML with E4X - Archive of obsolete content
function xmlchildwalker (xml) { var i = 0; var child = xml.*[0]; while (child != undefined) { yield child; child = xml.*[++i]; } yield false; } var a = <a><b/><c/></a>; var xcw = xmlchildwalker(a); var child; while ((child = xcw.next()) !== false) { alert(child.toxmlstring()); // "<b/>" then "<c/>" } see also e4x e4x tutorial ...
Accessing XML children - Archive of obsolete content
var a = <foo> some text <bar>not text</bar> more text </foo>; var list = a.text(); list.length(); // returns 2 list[0]; // returns " some text " list[1]; // returns " more text " you can similarly access comment nodes: xml.ignorecomments = false; var a = <foo> some <!-- abc --> text </foo>; var comments = a.comments(); alert(comments[0]); // returns <!-- abc --> the * selector will return all child nodes in an xml list.
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.setNonUserCodeExceptions - Archive of obsolete content
setting this property to false is the same as never having set the property.
Enumerator.item - Archive of obsolete content
example function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<b...
Enumerator.moveFirst - Archive of obsolete content
example in following example, the movefirst method is used to evaluate members of the drivescollection from the beginning of the list: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<b...
Enumerator.moveNext - Archive of obsolete content
example in following example, the movenext method is used to move to the next drive in the drives collection: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<b...
Enumerator - Archive of obsolete content
example the following code shows the usage of the enumerator object: var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); document.write(fso.drives); var e = new enumerator(fso.drives); var drivestring = ""; e.movefirst(); while (e.atend() == false) { var drv = e.item(); drivestring += drv.path + " - "; if (drv.isready){ var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; drivestring += freegb.tofixed(3) + " gb free of "; drivestring += totalgb.tofixed(3) + " gb"; } else{ drivestring += "not ready"; } drivestring += "<br />";; e.moven...
Number.toInteger() - Archive of obsolete content
if the target value is false, 0 is returned and if true, 1 is returned.
Object.observe() - Archive of obsolete content
g all six different types var obj = { foo: 0, bar: 1 }; object.observe(obj, function(changes) { console.log(changes); }); obj.baz = 2; // [{name: 'baz', object: <obj>, type: 'add'}] obj.foo = 'hello'; // [{name: 'foo', object: <obj>, type: 'update', oldvalue: 0}] delete obj.baz; // [{name: 'baz', object: <obj>, type: 'delete', oldvalue: 2}] object.defineproperty(obj, 'foo', {writable: false}); // [{name: 'foo', object: <obj>, type: 'reconfigure'}] object.setprototypeof(obj, {}); // [{name: '__proto__', object: <obj>, type: 'setprototype', oldvalue: <prototype>}] object.seal(obj); // [ // {name: 'foo', object: <obj>, type: 'reconfigure'}, // {name: 'bar', object: <obj>, type: 'reconfigure'}, // {object: <obj>, type: 'preventextensions'} // ] data binding // a user model va...
Sharp variables in JavaScript - Archive of obsolete content
t.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 ...
forEach - Archive of obsolete content
if (value>1){ return false;//we could have some way to break when we return false } }); //woulld print 1 2 --porfirio 11:17, 22-06-2008 another option would be to throw stopiteration and catch it within foreach().
XForms Custom Controls - Archive of obsolete content
the current value of a control could differ from the value of the bound node in cases where @incremental='false'.
XForms Range Element - Archive of obsolete content
single-node binding special incremental - supported, default value is false start - lower bound of possible values end - upper bound of possible values step - is used for incrementing/decrementing values start/end/step attributes if the value of the bound instance node is outside the range of values specified by the start and end attributes, then the range element receives a xforms-out-of-range event.
XForms Secret Element - Archive of obsolete content
the default value is false.
XForms Switch Module - Archive of obsolete content
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> ...
XForms Textarea Element - Archive of obsolete content
the default value is false.
XForms Config Variables - Archive of obsolete content
preference default description xforms.disablepopup false disables xforms engine popup error messages xforms.enableexperimentalfeatures false enable experimental features.
Displaying a graphic with audio samples - Archive of obsolete content
magnitude = signal[i] * 1000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } ctx.drawimage(document.getelementbyid('mozlogo'),0,0, canvas.width, canvas.height); } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> ...
RDF in Mozilla FAQ - Archive of obsolete content
remote.refresh(false); // note that ds will load asynchronously, so assertions will not // be immediately available you may decide that you need to "manually" create an rdf/xml datasource if you want to force it to load synchronously.
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).
3D collision detection - Game development
wrapping a person with a bounding sphere will cause a lot of false positives, whereas an aabb would be a better match).
Mouse controls - Game development
add the following line in the same place as the other event listeners, just below the keyup event: document.addeventlistener("mousemove", mousemovehandler, false); anchoring the paddle movement to the mouse movement we can update the paddle position based on the pointer coordinates — the following handler function will do exactly that.
Buttons - Game development
add these lines below your other variable definitions: var playing = false; var startbutton; loading the button spritesheet we can load the button spritesheet the same way we loaded the ball's wobble animation.
Game over - Game development
add the code below inside the create() function; just after you define the ball's attributes is fine: game.physics.arcade.checkcollision.down = false; this will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it.
Block (scripting) - 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.
Block - 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.
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression — for example making a true statement return false.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
for example: // here are two symbols with the same description: let sym1 = symbol("sym") let sym2 = symbol("sym") console.log(sym1 === sym2) // returns "false" // symbols are guaranteed to be unique.
Type - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a boolean data type can hold only a true or false value at any given time, whereas a string has the ability to hold a string or a sequence of characters, a number can hold numerical values of any kind, and so on.
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
example: var i = 0; while(i < 5){ console.log(i) i++ } //this loop will print number 0-4, will stop when condition becomes false (i >=5) for the above example, the syntax is as follows: the code block will continue to run as long as the variable (i) is less than 5.
Example 3 - Learn web development
ctlist = document.queryselectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (option) { option.addeventlistener('mouseover', function () { highlightoption(select, option); }); }); select.addeventlistener('click', function (event) { toggleoptlist(select); }, false); select.addeventlistener('focus', function (event) { activeselect(select, selectlist); }); select.addeventlistener('blur', function (event) { deactivateselect(select); }); select.addeventlistener('keyup', function (event) { if (event.keycode === 27) { deactivateselect(select); } }); }); }); result ...
Example 5 - Learn web development
optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); 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.ad...
How to build custom form controls - Learn web development
to that end, we need to revise our updatevalue() function: function updatevalue(select, index) { var nativewidget = 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 so...
UI pseudo-classes - Learn web development
now finally, we've used some javascript to toggle the disabling of the billing address fields: // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').addeventlistener('change', togglebilling); }, false); function togglebilling() { // select the billing text fields let billingitems = document.queryselectorall('#billing input[type="text"]'); // select the billing text labels let billinglabels = document.queryselectorall('.billing-label'); // toggle the billing text fields and labels for (let i = 0; i < billingitems.length; i++) { billingitems[i].disabled = !billingitems[i].disab...
From object to iframe — other embedding technologies - Learn web development
here's an example that uses the <embed> element to embed a flash movie (see this live on github, and check the source code too): <embed src="whoosh.swf" quality="medium" bgcolor="#ffffff" width="550" height="400" name="whoosh" align="middle" allowscriptaccess="samedomain" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> pretty horrible, isn't it?
General asynchronous programming concepts - Learn web development
function expensiveoperation() { for(let i = 0; i < 1000000; i++) { ctx.fillstyle = 'rgba(0,0,255, 0.2)'; ctx.beginpath(); ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degtorad(0), degtorad(360), false); ctx.fill() } } fillbtn.addeventlistener('click', expensiveoperation); alertbtn.addeventlistener('click', () => alert('you clicked me!') ); if you click the first button and then quickly click the second one, you'll see that the alert does not appear until the circles have finished being rendered.
Test your skills: Loops - Learn web development
isprime() — a function that, when passed a number, returns true if the number is a prime number, and false if not.
Video and Audio APIs - Learn web development
this returns a boolean true/false result.
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.
Solve common problems in your JavaScript code - Learn web development
how do you use a ternary operator to make a quick choice between two options based on a true or false test?
Adding features to our bouncing balls demo - Learn web development
this should be a boolean (true/false).
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()!
Test your skills: Object basics - Learn web development
split: a number representing the year the band split up, or false if they are still together.
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
in todo-data.js, add the following getter underneath the existing all() getter to define what the incomplete todos actually are: get incomplete() { return this.todos.filter(todo => { return todo.iscompleted === false; }); } using array.filter(), we declare that "incomplete" todos are ones that have iscompleted equal to false.
Ember resources and troubleshooting - Learn web development
only settings functions to be declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends component { @tracked somedata = false; @action setdata(newvalue) { this.somedata = newvalue; } } which would then be called in the template like so: <checkbox @data={{this.somedata}} @onchange={{this.setdata}} /> due to the conciseness of using mut, it may be desireable to reach for it.
Starting our Svelte Todo list app - Learn web development
pe="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 class="visually-hidden">show</span> <span>completed</span> <span class="visually-hidden">tasks</span> </button> </div> <!-- todosstatus --> <h2 id="list-heading">2 out ...
Handling common accessibility problems - Learn web development
here's an example: <p><span id="liveregion1" aria-live="polite" aria-atomic="false"></span></p> you can see an example in action at freedom scientific's aria (accessible rich internet applications) live regions example — the highlighted paragraph should update its content every 10 seconds, and a screenreader should read this out to the user.
Introduction to automated testing - Learn web development
dependencies to gulpfile.js: const autoprefixer = require('gulp-autoprefixer'); const csslint = require('gulp-csslint'); add the following test to the bottom of gulpfile.js: function css(cb) { return gulp.src('src/style.css') .pipe(csslint()) .pipe(csslint.formatter('compact')) .pipe(autoprefixer({ browsers: ['last 5 versions'], cascade: false })) .pipe(gulp.dest('build')); cb(); } here we grab our style.css file, run csslint on it (which outputs a list of any errors in your css to the terminal), then runs it through autoprefixer to add any prefixes needed to make nascent css features run in older browsers.
Handling common JavaScript problems - Learn web development
if the function returns false, then we run the code inside the second part of the conditional — this runs a function called loadscript(), which loads the polyfills into the page, then runs main() after the loading has finished.
Setting up your own test automation environment - Learn web development
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 details.
omni.ja (formerly omni.jar)
inspecting and repacking omni.ja note: when extracting omni.ja, you may incorrectly get false warnings from some virus protection software.
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 accessibility: ...
Gecko info for Windows accessibility vendors
if placetopleft is false, the document will only be scrolled if the element is not already visible, or the document will be scrolled the minimum amount to make the element visible anywhere within the current window.
Adding a new CSS property
in any case where the computation you do might vary between elements that match the same list of style rules, you need to set the canstoreinruletree variable to false.
Application cache implementation overview
this flag is by default true, but it is dropped by nsdocshell::douriload() to false only for top level document loading channels.
Benchmarking
set it to false to match a release build.
Creating JavaScript callbacks in components
fined as such: void addeventlistener(in domstring type, in nsidomeventlistener listener, in boolean usecapture); however, it is extremely common to see developers pass a normal javascript function for the listener instead of an nsidomeventlistener implementation: function doload(event) { // do something here } window.addeventlistener("load", doload, false); revealing the magic how is this possible?
Creating reftest-based unit tests
if a regression test harness has false failures, it makes the harness not trustworthy and the harness will not be used.
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.
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.
Error codes returned by Mozilla APIs
ns_error_file_dir_not_empty (0x80520014) when calling nsifile.remove() on a directory and the 'recursive' argument to this method is false, this error will occur if the directory is not empty.
Performance
oader.messagemanager; let button = event.target; let callback = (message) => { tabmm.removemessagelistener("my-addon:paragraph-count", callback) decoratebutton(button, message.data.num) } tabmm.addmessagelistener("my-addon:paragraph-count", callback); tabmm.loadframescript("data:,sendasyncmessage('my-addon:paragraph-count', {num: content.document.queryselectorall('p').length})", false) } function decoratebutton(button, count) { // do stuff with result } this executes the script only when it is needed and only in one tab and allows it to be garbage-collected immediately after execution.
Performance best practices for Firefox front-end engineers
if you ever go back to the event loop (by yielding, waiting for an event, etc), style flushes unrelated to your code are likely to run, and your test will give you a false positive.
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.
HTMLIFrameElement.getVisible()
'true' : 'false'); } specification not part of any specification.
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.
mozbrowserusernameandpasswordrequired
isproxy a boolean indicating whether the server dealing with the authentication is a proxy server (true) or not (false).
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).
HTMLIFrameElement.setActive()
parameters boolean a boolean that indicates whether the iframe is to be the active frame (true) or not (false).
CSS -moz-bool-pref() @supports function
syntax -moz-bool-pref( <string> ) parameters <string> the preference name returns evaluates to true if the preference is enabled, false otherwise.
overflow-clip-box-block
width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-block: padding-box; } javascript function scrollsomeelements() { var elms = document.queryselectorall('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollleft=80; } } var elt = document.queryelementsbytagname('body')[0]; elt.addeventlistener("load", scrollsomeelements, false); result specifications this property has been proposed to the w3c csswg; it is not yet on the standard track but, if accepted, should appear in css overflow module level 3.
overflow-clip-box-inline
idth: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-inline: padding-box; } javascript function scrollsomeelements() { var elms = document.queryselectorall('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollleft=80; } } var elt = document.queryelementsbytagname('body')[0]; elt.addeventlistener("load", scrollsomeelements, false); result specifications this property has been proposed to the w3c csswg; it is not yet on the standard track but, if accepted, should appear in css overflow module level 3.
overflow-clip-box
ng: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box: padding-box; } js function scrollsomeelements() { var elms = document.queryselectorall('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollleft=80; } } var elt = document.queryelementsbytagname('body')[0]; elt.addeventlistener("load", scrollsomeelements, false); result specifications this property has been proposed to the w3c csswg; it is not yet on the standard track but, if accepted, should appear in css overflow module level 3.
MozBeforePaint
00px; height:100px; background:lime; position:relative;"></div> <script> var d = document.getelementbyid("d"); var start = window.mozanimationstarttime; function step(event) { var progress = event.timestamp - start; d.style.left = math.min(progress/10, 200) + "px"; if (progress < 2000) { window.mozrequestanimationframe(); } else { window.removeeventlistener("mozbeforepaint", step, false); } } window.addeventlistener("mozbeforepaint", step, false); window.mozrequestanimationframe(); </script> </body> </html> as you can see, each time the mozbeforepaint event fires, our step() method is called.
MozScrolledAreaChanged
example document.addeventlistener("mozscrolledareachanged", event => { // find something useful to do with those values event.width; event.height; event.x; event.y; }, false); ...
Geckoview-Junit Tests
assumethat(sessionrule.env.isdebugbuild && sessionrule.env.cpuarch == "x86", equalto(false)) running tests on try to run these tests on try, use something like: mach try fuzzy -q geckoview-junit --artifact or mach try -b do -p android-x86_64 -u geckoview-junit --artifact currently, geckoview-junit is only run on android-x86_64.
HTTP Cache
used result == entry_needs_revalidation: state = revalidating, this prevents invocation of any callback until cacheentry::setvalid is called continue as in state entry_wanted (just bellow) result == entry_wanted: consumer reference ++ (dropped back when the consumer releases the entry) oncacheentryavailable is invoked on the opener with anew = false and the entry opener is removed from the fifo result == entry_not_wanted: oncacheentryavailable is invoked on the opener with null for the entry opener is removed from the fifo state == writing or revalidating: do nothing and exit any other value of state is unexpected here (assertion failure) loop this process while there are openers in...
Add-on Repository
issearching boolean true if a search is currently in progress; otherwise false.
API-provided widgets
nb: if you specify false here, you must provide a defaultarea, too.
DeferredTask.jsm
bool ispending(); return value returns true if pending, 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
otherwise, it returns false.
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.
XPCOMUtils.jsm
category: "some-category", // optional, defaults to the object's classdescription entry: "entry name", // optional, defaults to the object's contractid (unless // 'service' is specified) value: "...", // optional, defaults to false.
gettext
in the rule above, if n equals 1, the expression is evaluated to false, or 0, so msgstr[0] will be used.
Basics
ock"> <mrow> <msub> <mi>z</mi> <mi>&alpha;</mi> </msub> <mrow> <mo>(</mo> <mi>f</mi> <mo>)</mo> </mrow> <mo>=</mo> <mfrac> <mn>1</mn> <mrow> <mn>2</mn> <mi>i</mi> <mo>&thinspace;</mo> <mi>cos</mi> <mo>(</mo> <mfrac> <mrow> <mi>&alpha;</mi> <mi>&pi;</mi> </mrow> <mn>2</mn> </mfrac> <mo>)</mo> </mrow> </mfrac> <mrow> <msub> <mo>&int;</mo> <mi>c</mi> </msub> <mfrac> <mrow> <mi>f</mi> <mo stretchy='false'>(</mo> <mi>i</mi> <mi>z</mi> <mo stretchy='false'>)</mo> <msup> <mrow> <mo>(</mo> <mo>-</mo> <mi>z</mi> <mo>)</mo> </mrow> <mi>&alpha;</mi> </msup> </mrow> <mrow> <msup> <mi>e</mi> <mrow> <mn>2</mn> <mi>&pi;</mi> <mi>z</mi> </mrow> </msup> <mo>-</mo> <mn>1</mn> </mrow> </mfrac> </mrow> <mi>d</mi> <mi>z</mi> </mrow> </math> css content [class="background"] { background-image: url(http://www...
MathML In Action
addeventlistener("click", zoomtoggle, false); } window.addeventlistener("load", load, false); consider an interesting markup like this { u t + f ( u ) x = 0 u ( 0 , x ) = { u - if x < 0 u + if x > 0 or other complex markups like these ell ^ y ( z ; z , τ ) := ∫ y ( ∏ l ( y l 2 π i ) θ ( y l 2 π i - z ) θ ′ ( 0 ) θ ( - z ) θ ( ...
MathML Demo: <mfrac> - fractions
ock"> <mrow> <msub> <mi>z</mi> <mi>&alpha;</mi> </msub> <mrow> <mo>(</mo> <mi>f</mi> <mo>)</mo> </mrow> <mo>=</mo> <mfrac> <mn>1</mn> <mrow> <mn>2</mn> <mi>i</mi> <mo>&thinspace;</mo> <mi>cos</mi> <mo>(</mo> <mfrac> <mrow> <mi>&alpha;</mi> <mi>&pi;</mi> </mrow> <mn>2</mn> </mfrac> <mo>)</mo> </mrow> </mfrac> <mrow> <msub> <mo>&int;</mo> <mi>c</mi> </msub> <mfrac> <mrow> <mi>f</mi> <mo stretchy='false'>(</mo> <mi>i</mi> <mi>z</mi> <mo stretchy='false'>)</mo> <msup> <mrow> <mo>(</mo> <mo>-</mo> <mi>z</mi> <mo>)</mo> </mrow> <mi>&alpha;</mi> </msup> </mrow> <mrow> <msup> <mi>e</mi> <mrow> <mn>2</mn> <mi>&pi;</mi> <mi>z</mi> </mrow> </msup> <mo>-</mo> <mn>1</mn> </mrow> </mfrac> </mrow> <mi>d</mi> <mi>z</mi> </mrow> </math> css content [class="background"] { background-image: ur...
JS::PerfMeasurement
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.
Memory Profiler
you may need to set the "xpinstall.signatures.required" pref to false in order to install it, since the xpi is not yet signed.
TraceMalloc
some of these are false positives, allocations that are truly needed until shutdown.
browser.dom.window.dump.enabled
set it to true to enable it, or false to disable it.
browser.download.lastDir.savePerSite
false the last used directory for any download (stored in browser.download.lastdir) will be the preselected directory 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.
browser.urlbar.formatting.enabled
false all parts of the url are given the same color: black.
browser.urlbar.trimURLs
false all parts of the url are shown.
dom.event.clipboardevents.enabled
false the oncopy, oncut and onpaste events are disabled for web content.
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.
javascript.options.strict
false: show javascript errors only.
nglayout.debug.disable_xul_cache
false: cache xul documents in memory and save the cache to disk on exit to improve performance.
view_source.syntax_highlight
false syntax hightlighting is disabled.
Introduction to NSPR
the expression may be false only when a thread is in the monitor (holding the monitor's mutex).
PL_HashTableRemove
description if there is no entry in the table with the specified key, pl_hashtableremove returns pr_false.
PR_Initialized
if pr_init has not already been called, pr_false.
PR_LOG_TEST
possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug returns pr_true when logging is enabled for the given module and level, otherwise pr_false.
PR_QueueJob
if pr_false, the job is not joinable.
PR_QueueJob_Accept
if pr_false, the job is not joinable.
PR_QueueJob_Connect
if pr_false, the job is not joinable.
PR_QueueJob_Read
if pr_false, the job is not joinable.
PR_QueueJob_Timer
if pr_false, the job is not joinable.
PR_QueueJob_Write
if pr_false, the job is not joinable.
PR_SetLogFile
otherwise, pr_false.
PR_VersionCheck
if the versions are not compatible, pr_false.
PR_Wait
while the boolean expression is false, the thread should wait.
Encrypt Decrypt MAC Keys As Session Objects
*/ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ploptstatus status; char headerfilename[50]; char encryptedfilename[50]; prfiledesc *infile; prfiledesc *outfile; prbool ascii = pr_false; commandtype cmd = unknown; const char *command = null; const char *dbdir = null; const char *infilename = null; const char *outfilename = null; const char *noisefilename = null; secupwdata pwdata = { pw_none, 0 }; char * progname = strrchr(argv[0...
Encrypt and decrypt MAC using token
*/ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ploptstatus status; char headerfilename[50]; char encryptedfilename[50]; prfiledesc *infile; prfiledesc *outfile; prbool ascii = pr_false; commandtype cmd = unknown; const char *command = null; const char *dbdir = null; const char *infilename = null; const char *outfilename = null; const char *noisefilename = null; secupwdata pwdata = { pw_none, 0 }; char * progname = strrchr(argv[0...
JSS Provider Notes
if you do not wish the provider to be installed, create a cryptomanager.initializationvalues object, set its installjssprovider field to false, and pass the initializationvalues object to cryptomanager.initialize().
Mozilla-JSS JCA Provider notes
if you do not wish the provider to be installed, create a cryptomanager.initializationvalues object, set its installjssprovider field to false, and pass the initializationvalues object to cryptomanager.initialize().
NSS 3.17 release notes
.17 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_17_rtm/src/ new in nss 3.17 new functionality when using ecdhe, the tls server code may be configured to generate a fresh ephemeral ecdh key for each handshake, by setting the ssl_reuse_server_ecdhe_key socket option to pr_false.
NSS 3.34 release notes
prbool resumed is pr_true when the session is resumed, and pr_false otherwise.
Encrypt Decrypt_MAC_Using Token
*/ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ploptstatus status; char headerfilename[50]; char encryptedfilename[50]; prfiledesc *infile; prfiledesc *outfile; prbool ascii = pr_false; commandtype cmd = unknown; const char *command = null; const char *dbdir = null; const char *infilename = null; const char *outfilename = null; const char *noisefilename = null; secupwdata pwdata = { pw_none, 0 }; char * progname = strrchr(argv[0...
NSS Sample Code Sample_3_Basic Encryption and MACing
*/ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ploptstatus status; char headerfilename[50]; char encryptedfilename[50]; prfiledesc *infile; prfiledesc *outfile; prbool ascii = pr_false; commandtype cmd = unknown; const char *command = null; const char *dbdir = null; const char *infilename = null; const char *outfilename = null; const char *noisefilename = null; secupwdata pwdata = { pw_none, 0 }; char * progname = strrchr(argv[0...
EncDecMAC using token object - sample 3
*/ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ploptstatus status; char headerfilename[50]; char encryptedfilename[50]; prfiledesc *infile; prfiledesc *outfile; prbool ascii = pr_false; commandtype cmd = unknown; const char *command = null; const char *dbdir = null; const char *infilename = null; const char *outfilename = null; const char *noisefilename = null; secupwdata pwdata = { pw_none, 0 }; char * progname = strrchr(argv[0], '/'); progname = progname ?
nss tech note5
*/; prbool token = /* pr_true or pr_false depending on??
nss tech note7
*/ inpubkey.m_modulus.type = siunsignedinteger; inpubkey.m_exponent.type = siunsignedinteger; arena = port_newarena(der_default_chunksize); sec_asn1encodeitem(arena, &derpubkey, &inpubkey, myrsapublickeytemplate); pubkey = seckey_importderpublickey(&derpubkey, ckk_rsa); port_freearena(arena, pr_false); public keys may be extracted from certificates.
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.
NSS environment variables
the default setting for this option is false.
sslcrt.html
pr_false means certificate signatures will not be checked.
Rhino overview
toboolean boolean(new boolean(false)) is false for all versions before 1.3.
Scripting Java
js> f.name test.txt js> f.directory false calling overloaded methods the process of choosing a method to call based upon the types of the arguments is called overload resolution.
Shumway
it is currently available as an extension and as a component in firefox's nightly builds that can be enabled through about:config (you need to find the shumway.disabled preference and set it to false).
Creating JavaScript jstest reftests
for example, reportcompare sometimes considers numbers to be the same if they are "close enough" to each other, even if the == operator would return false.
How to embed the JavaScript engine
*/ if (rval.isboolean() && !rval.toboolean()) cancelevent(event); again, i've elided error checking (such as testing for !ok after the call), and i've faked up some c event management routines that emulate the dom's convention of canceling an event if its handler returns false.
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.
Introduction to the JavaScript shell
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.
INT_FITS_IN_JSVAL
otherwise, int_fits_in_jsval returns false.
JS::Add*Root
otherwise they report an out of memory error and return false.
JS::AutoIdArray
examples { js::autoidarray ids(cx, js_enumerate(cx, obj)); if (!ids) // check the returned value from js_enumerate return false; for (int32_t i = 0, len = ids.length(); i < len; i++) { somefunc(cx, ids[i]); } /* when leaving this scope, the jsidarray returned by js_enumerate is freed.
JS::BooleanValue
see also mxr id search for js::booleanvalue js::value js::truevalue js::falsevalue ...
JS::CallArgs
if false, it reports an error message on the context.
JS::Compile
otherwise, it returns false and the value left in script is undefined.
JS::CompileFunction
otherwise, it returns false and the value left in fun is undefined.
JS::CreateError
if successful, js::createerror stores the created error object to *rval and returns true, otherwise returns false and the value of *rval is undefined.
JS::DeflateStringToUTF8Buffer
examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx, js_newucstringcopyn(cx, uchars, 2)); if (!str) return false; js::rooted<jsflatstring*> flatstr(cx, js_flattenstring(cx, str)); if (!flatstr) return false; size_t length = js::getdeflatedutf8stringlength(flatstr); char* buffer = static_cast<char*>(js_malloc(cx, length + 1)); if (!buffer) return false; js::deflatestringtoutf8buffer(flatstr, mozilla::rangedptr<char>(buffer, length)); buffer[length] = '\0'; printf("utf8: [%s]\n", buffer); js_free(cx, bu...
JS::Evaluate
otherwise it returns false and the value left in *rval is undefined.
JS::GetFirstArgumentAsTypeHint
otherwise, return false with a typeerror pending.
JS::NullHandleValue
see also mxr id search for js::nullhandlevalue js::undefinedhandlevalue js::truehandlevalue js::falsehandlevalue bug 865969 ...
JS::OrdinaryToPrimitive
on error or exception, it returns false, and the value left in *vp is undefined.
JS::ToInt32
on error or exception, it returns false, and the value left in *out is undefined.
JS::ToInt64
on error or exception, it returns false, and the value left in *out is undefined.
JS::ToNumber
on error or exception, it returns false, and the value left in *out is undefined.
JS::ToPrimitive
on error or exception, it returns false, and the value left in *vp is undefined.
JS::ToUint16
on error or exception, it returns false, and the value left in *out is undefined.
JS::ToUint32
on error or exception, it returns false, and the value left in *out is undefined.
JS::ToUint64
on error or exception, it returns false, and the value left in *out is undefined.
JS::TrueValue
see also mxr id search for js::truevalue js::value js::booleanvalue js::falsevalue ...
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 (includ...
JSClass
inter_finalize, * jsclass_no_optional_members * }; */ bool printer_construct(jscontext *cx, unsigned argc, jsval *vp) { js::callargs args = js::callargsfromvp(argc, vp); jsobject *obj = js_newobjectforconstructor(cx, &printer_class, args); /* spidermonkey 31 or older * jsobject *obj = js_newobjectforconstructor(cx, &printer_class, vp); */ if (!obj) return false; myprinter *p = new myprinter; if (p == null) { js_reportoutofmemory(cx); return false; } js_setprivate(cx, obj, p); args.rval().setobject(*obj); /* spidermonkey 31 or older * js_set_rval(cx, vp, object_to_jsval(obj)); */ return true; } { js_initclass(cx, global, js::null(), &printer_class, printer_construct, 1, null, null,...
JSConvertOp
(support for the other types may eventually be removed.) the callback returns true to indicate success or false to indicate failure.
JSFastNative
on error or exception, it must return js_false.
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.
JSNewEnumerateOp
the return value is used to indicate success, with a value of false indicating failure.
JSNewResolveOp
on failure, it must return js_false.
JSObjectOps.defaultValue
the jsclass.convert callback should convert obj to the given type, returning js_true with the resulting value in *vp on success, and returning js_false on error or exception.
JSObjectOps.getAttributes
returns js_false on error or exception, else js_true with current attributes in *attrsp.
JSObjectOps.lookupProperty
description look for id in obj and its prototype chain, returning js_false on error or exception, js_true on success.
JSPrincipalsTranscoder
return js_true on success, js_false on any error, which the implementation must have reported.
JSPropertyOp
each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false.
JSType
jstype_boolean boolean values, true and false.
JSVAL_IS_BOOLEAN
syntax jsval_is_boolean(v) description jsval_is_boolean(v) is true if the given javascript value, v, is a boolean value (that is, it is either jsval_true or jsval_false).
JSVAL_IS_OBJECT
if v is a string, number, boolean, or undefined, the result is false.
JSVAL_IS_PRIMITIVE
otherwise it is false, and v is an object.
JSVAL_LOCK
otherwise, it evaluates to false.
JSVAL_NULL
see also mxr id search for jsval_null jsval_void jsval_true jsval_false jsval_zero jsval_one bug 1177825 -- removed ...
JSVAL_ONE
see also mxr id search for jsval_one int_to_jsval js_newcontext jsval_null jsval_void jsval_true jsval_false jsval_zero bug 1177825 -- removed ...
JSVAL_UNLOCK
otherwise, it evaluates to false.
JSVAL_VOID
see also mxr id search for jsval_void jsval_null jsval_true jsval_false jsval_zero jsval_one bug 1177825 -- removed ...
JSVAL_ZERO
see also mxr id search for jsval_zero int_to_jsval js_newcontext jsval_null jsval_void jsval_true jsval_false jsval_one bug 1177825 -- removed ...
JS_AddFinalizeCallback
iscompartment bool false if all compartments are being collected, true if a compartment is being collected.
JS_Add*Root
otherwise they report an out of memory error and return js_false.
JS_BufferIsCompilableUnit
description given a buffer, return false if the buffer might become a valid javascript statement with the addition of more lines.
JS_CheckAccess
on error or exception, including if access is denied, js_checkaccess returns js_false, and the values left in *vp and *attrsp are undefined.
JS_CheckForInterrupt
js_checkforinterrupt returns false if interrupt callback returns false.
JS_ClearRegExpStatics
on successful, js_clearregexpstatics returns true, otherwise returns false.
JS_CompareStrings
on error, it returns js_false and the value in result is unchanged.
JS_CompileScript
otherwise, they report an error, stores null to *script, and return false.
JS_ConvertArgumentsVA
otherwise it returns false.
JS_DefaultValue
on error or exception, it returns false, and the value left in *vp is undefined.
JS_DefineConstDoubles
otherwise it returns false.
JS_DefineElement
otherwise it returns false.
JS_DefineFunctions
on error or exception, it stops defining functions and returns false.
JS_DefineProperties
otherwise it returns false.
JS_DefineProperty
on error or exception, it returns false.
JS_DefinePropertyWithTinyId
if the property already exists or cannot be created, they return js_false.
JS_EncodeString
note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can return a corrupted copy of the contents of the string.
JS_EnterLocalRootScope
for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx.
JS_EvaluateScript
otherwise it returns js_false and the value left in *rval is undefined.
JS_EvaluateScriptForPrincipals
otherwise it returns js_false, and the value left in *rval is undefined.
JS_ExecuteScript
otherwise it returns false, and the value left in rval is unspecified.
JS_ExecuteScriptPart
otherwise it returns js_false, and the value left in *rval is undefined.
JS_ExecuteScriptVersion
otherwise it returns false, and the value left in *rval is unspecified.
JS_FileEscapedString
if successful, js_fileescapedstring returns true, otherwise false.
JS_FlattenString
example: // in a fallible situation jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) return false; js_assert(fstr == js_assert_string_is_flat(str)); // in an infallible situation, for the same 'str' const jschar *chars = js_getflatstringchars(fstr) js_assert(chars); see also mxr id search for js_flattenstring js_assert_string_is_flat js_forget_string_flatness bug 609440 ...
JS_ForwardGetPropertyTo
on an error or exception, these functions return false, and the value left in *vp is undefined.
JS_GetArrayLength
on failure, it reports an error and returns false, and the value left in *lengthp is undefined.
JS_GetClassObject
if successful, js_getclassobject stores the class constructor to *objp and returns true, otherwise returns false and the value of *objp is undefined.
JS_GetClassPrototype
if successful, js_getclassprototype stores the class prototype object to *objp and returns true, otherwise returns false and the value of *objp is undefined.
JS_GetElement
if the search fails with an error or exception, js_getelement returns false, and the value left in *vp is undefined.
JS_GetFlatStringChars
description jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) return js_false; const jschar *chars = js_getflatstringchars(fstr) js_assert(chars); see also js_flattenstring bug 1037869 ...
JS_GetGCParameter
jsgc_dynamic_heap_growth / "dynamicheapgrowth" if false, the heap growth percentage is fixed at 300%.
JS_GetPendingException
otherwise, it returns false, and the value left in *vp is undefined.
JS_GetProperty
on an error or exception, these functions return false, and the value left in *vp is undefined.
JS_GetPropertyDefault
on an error or exception, these functions return false, and the value left in *vp is undefined.
JS_GetPrototype
if js_getprototype returns false, that signals an exception, which should be handled as usual.
JS_GetRegExpFlags
if successful, js_getregexpflags returns the flags, otherwise returns false.
JS_GetStringBytes
note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can return a corrupted copy of the contents of the string.
JS_GetStringCharAt
on successful, js_getstringcharat returns true and stores the character code into *res, otherwise returns false.
JS_IdToValue
otherwise it returns false.
JS_InitStandardClasses
js_initstandardclasses returns js_true on success, and js_false if an error occurs.
JS_IsArrayObject
otherwise returns false on failure.
JS_IsConstructor
otherwise it returns false.
JS_IsExternalString
description js_isexternalstring returns true if the string is an external string; otherwise it's false.
JS_IsGlobalObject
description js_isglobalobject returns true if obj is a global object, false otherwise.
JS_IsIdentifier
on successful, js_isidentifier stores the test result to *isidentifier and returns true, otherwise returns false and the value of *isidentifier is undefined.
JS_IsNativeFunction
otherwise it returns false.
JS_IsRunning
otherwise it returns false.
JS_IsStopIteration
description js_isstopiteration returns true if v is stopiteration, otherwise false.
JS_LookupElement
on error or exception, js_lookupelement returns false, and the value left in *vp is undefined.
JS_LookupProperty
on error or exception (such as running out of memory during the search), the return value is false, and the value left in *vp is undefined.
JS_LooselyEqual
if the comparison attempt was successful, the method returns js_true and stores the result in *equal; otherwise it returns js_false.
JS_NewDoubleValue
otherwise it returns js_false and the value left in *rval is unspecified.
JS_NewNumberValue
otherwise it returns js_false and the value left in *rval is unspecified.
JS_NextProperty
on error, it returns false, and the value left in *idp is undefined.
JS_ObjectIsRegExp
otherwise it returns false.
JS_ReportError
the callback must then return js_false to cause the exception to be propagated to the calling script.
JS_ReportPendingException
if no exception is pending, or if a second error occurs while trying to report the first one, it returns false.
JS_SameValue
description js_samevalue determines whether two values are the same, returning true or false accordingly.
JS_SetArrayLength
otherwise it returns false.
JS_SetFunctionCallback
entering int true if the callback is being called because the specified function is being invoked or false if the function is exiting.
JS_SetGCCallback
the callback may prevent gc from starting by returning false.
JS_SetInterruptCallback
(in this case, the callback may terminate the script by returning false.) js_getinterruptcallback returns the currently installed interrupt callback, or null if none is currently installed.
JS_SetOperationCallback
(in this case, the callback may terminate the script by returning js_false.) js_getoperationcallback returns the currently installed operation callback, or null if none is currently installed.
JS_SetParent
otherwise, it reports an error or sets an exception and returns js_false.
JS_SetPendingException
a native function or hook using this to throw an exception must also return false to ensure the exception is thrown.
JS_SetPrototype
otherwise it returns false.
JS_SetRegExpInput
on successful, js_setregexpinput returns true, otherwise returns false.
JS_StrictlyEqual
if the comparison attempt was successful, the method returns true and stores the result in *equal; otherwise it returns false.
JS_StringEqualsAscii
on successful, js_stringequalsascii stores the comparison result into *match and returns true, otherwise returns false.
JS_ValueToECMAInt32
on error or exception, it returns js_false, and the value left in *ip is undefined.
JS_ValueToId
otherwise it returns false.
JS_ValueToInt32
on error or exception, it returns js_false, and the value left in *ip is undefined.
JS_ValueToObject
otherwise it returns false and the value left in *objp is unspecified.
JS_ValueToString
if v is true, false, null, or undefined, conversion succeeds, and the result is the string "true", "false", "null", or "undefined", accordingly.
Parser API
if computed === false, the node corresponds to a static e1.x expression and property is an identifier.
Thread Sanitizer
unlike other tools, it understands compiler-builtin atomics and synchronization and therefore provides very accurate results with no real false positives.
WebReplayRoadmap
using a corpus of several normal recordings (or buggy recordings) would reduce false positives due to incidental differences between the recordings.
Mozinfo
unknown will evaluate as false in python: if not mozinfo.os: ...
Mozilla Projects
unlike other tools, it understands compiler-builtin atomics and synchronization and therefore provides very accurate results with no real false positives.
Security and the jar protocol
you may re-enable the feature if necessary by setting the network.jar.block-remote-files preference to false.
Setting up an update server
you can use this command with firefox's browser console to determine the update directory: const {fileutils} = chromeutils.import("resource://gre/modules/fileutils.jsm"); fileutils.getdir("updrootd", [], false).path once you have determined the update directory, close firefox, browse to the directory and remove the subdirectory called updates.
Manipulating bookmarks using Places
); }, onitemvisited: function(abookmarkid, avisitid, time) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is called when my add-on is unloaded onunload: function() { bmsvc.removeobserver(myext_bookmarklistener); }, dosomething: function() { alert("did something."); } }; see also nsinavbookmarksservice nsinavbookmarkobserver places using xpcom without chrome - bookmark observer ...
Querying Places
uri, title, time, icon...) // see : https://developer.mozilla.org/en/nsinavhistoryresultnode dump(node.title+ "\n"); } // close container when done // see : https://developer.mozilla.org/en/nsinavhistorycontainerresultnode cont.containeropen = false; see also places query uris displaying places information using views ...
extIExtension
extensions.your_extension_id.install-event-fired) will be set to false after your extension has been installed.
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.
Accessing the Windows Registry Using XPCOM
e) { return cache[value]; } cache[value] = readregistryvaluenocache(wrk, value); return cache[value]; } var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft\\windows\\currentversion", wrk.access_read); wrk.startwatching(false); // only watch the values on this key, not child keys var id = readregistryvalue(wrk, "productid"); /* later you can read this again, and it should come from the cache unless there have been changes to the registry.
Avoiding leaks in JavaScript XPCOM components
obal variable, fixed later in bug 231266): const observer = { observe: function(subject, topic, data) { if (topic != "open-new-tab-request" || subject != window) return; delayedopentab(data); } }; const service = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); service.addobserver(observer, "open-new-tab-request", false); in this example, there is a similar cycle between observe and service.
How to build an XPCOM component in JavaScript
category: "some-category", // optional, defaults to the object's classdescription entry: "entry name", // optional, defaults to the object's contractid (unless 'service' is specified) value: "...", // optional, defaults to false.
An Overview of XPCOM
e, the construction and initialization of someclass, which implements the someinterface abstract class, is contained within the new_someinterface function, which follows the factory design pattern: encapsulating the constructor int new_someinterface(someinterface** ret) { // create the object someclass* out = new someclass(); if (!out) return -1; // init the object if (out->init() == false) { delete out; return -1; } // cast to the interface *ret = static_cast<someinterface*>(out); return 0; } the factory is the class that actually manages the creation of separate instances of a component for use.
Creating the Component Code
registrylocation) { nsicomponentregistrar* compreg = nsnull; nsresult rv = acompmgr->queryinterface(kicomponentregistrariid, (void**)&compreg); if (ns_failed(rv)) return rv; rv = compreg->unregisterfactorylocation(ksamplecid, apath); compreg->release(); return rv; } ns_imethodimp samplemodule::canunload(nsicomponentmanager *acompmgr, prbool *oktounload) { *oktounload = pr_false; // we do not know how to unload.
Introduction to XPCOM for the DOM
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.import
omutils === 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.setGCZeal
this method calls through to that thusly: js_setgczeal(<current context>, zeal, js_default_zeal_freq, false); syntax components.utils.setgczeal(zeal); where zeal is the zeal value you wish to use.
Components.utils.unwaiveXrays
window 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; ...
Components.utils.waiveXrays
window 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 ...
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.
Language bindings
ijsid 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.
NS_NewLocalFile
example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newlocalfile(nsembedstring(l"c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
NS_NewNativeLocalFile
example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newnativelocalfile(nsembedcstring("c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; here, nsembedcstring is used to convert the ascii string literal to an object that can be passed as a const nsacstring& parameter.
HeapMinimize
if false, the flush will be scheduled to happen when the app is idle.
IAccessibleHypertext
s_false if there is nothing to return, [out] value is -1.
IAccessibleImage
return value s_false if there is nothing to return, [out] value is null.
IAccessibleValue
return value s_false if there is nothing to return, [out] value is null.
imgICache
if false, evict everything except chrome images.
imgILoader
return value true if a decoder is available, false otherwise.
jsdIStackFrame
|true| if this context should be allowed to run scripts, |false| otherwise.
mozIAsyncFavicons
aforcereload if false, we try to reload the favicon only if we do not have it or it has expired from the cache.
mozIPersonalDictionary
return value true if the word is in either the dictionary or the ignore list, false if it is not in either list.
mozISpellCheckingEngine
return value returns true if word is spelled correctly according to the dictionary attribute, and returns false if word is misspelled.
mozIStoragePendingStatement
return value in versions of gecko prior to gecko 1.9.2, this returned a boolean value that was true if the query was canceled successfully or false if not.
mozIStorageProgressHandler
return value return true to abort the request or false to allow it to continue.
mozIStorageService
if this value is false, it is strongly recommended that the database be backed up with mozistorageconnection.backupdb() so user data is not lost.
mozIStorageStatement
boolean step() return value true if there are more rows left in the results, otherwise false.
mozIStorageStatementWrapper
return value returns true if the stepping the wrapped statement was successful, otherwise returns false.
mozIStorageValueArray
return value returns true if the column specified by aindex is null, or false otherwise.
mozIVisitStatusCallback
avisitedstatus true if the specified uri has been visited; otherwise false.
nsIAccessibleDocument
false if the document is being displayed but not edited.
nsIAccessibleTextChangeEvent
return value true if text was inserted, otherwise false.
nsIAccessibleValue
return value true if the value is within the range of minimumvalue - maximumvalue, false if it is not.
nsIAlertsService
getservice(components.interfaces.nsialertsservice); try { alertsservice.showalertnotification("chrome://mozapps/skin/downloads/downloadicon.png", "alert title", "alert text goes here.", false, "", null, ""); } catch (e) { // this can fail on mac os x } listening for callbacks you can be notified when the notification window disappears or the user clicks on the message by passing an object implementing nsiobserver as the alertlistener parameter: var listener = { observe: function(subject, topic, data) { alert("subject=" + subject + ", topic=" + topic + ", data=" + data); ...
nsIAppStartup
caninteract if false and ui is needed, will fail.
nsIApplicationCache
e getmatchingnamespace(in acstring key); unsigned long gettypes(in acstring key); void initashandle(in acstring groupid, in acstring clientid); void markentry(in acstring key, in unsigned long typebits); void unmarkentry(in acstring key, in unsigned long typebits); attributes attribute type description active boolean true if the cache is the active cache for this group, otherwise false.
nsIAuthPromptCallback
usercancel if false, this prompt was cancelled by calling the the cancel method on the nsicancelable; otherwise, it was cancelled by the user.
nsIBidiKeyboard
return value true if the current keyboard is right-to-left, false if it is not.
nsIBlocklistPrompt
these are javascript objects with properties: name - the plugin or extension name version - the version of the extension or plugin icon - the plugin or extension icon disable - can be used by the nsiblocklistprompt to allows users to decide whether a soft-blocked add-on should be disabled blocked - true if the item is hard-blocked, false otherwise item - the nsiplugintag or addon object acount optional the number of addons.
nsIBlocklistService
return value true if the item is blocklisted, otherwise false.
nsIBrowserHistory
set to false otherwise.
nsICacheEntryInfo
return value returns true if the cache entry is stream based, otherwise returns false.
nsICacheMetaDataVisitor
return value returns true if the provided key/value finds a cache entry, otherwise returns false.
nsIChromeRegistry
return value true if xpcnativewrappers are enabled for the specified uri; otherwise false.
nsICommandLine
return value true if the flag was found, otherwise false.
nsICompositionStringSynthesizer
however, this must always return false since all dispatching dom events are not cancelable.
nsIContentPrefService
return value true if the preference exists; otherwise false.
nsIContentViewer
return value true if the document will allow unloading; otherwise false.
nsICookieManager2
only relevant if aissession is false.
nsICryptoHMAC
if false, then the returned value is binary data.
nsIDOMEventGroup
return value returns true if the two objects are the same, otherwise false.
nsIDOMMozNetworkStatsManager
if false or not set, the total traffic, which is generated from both the mozapp and mozbrowser iframe elements, is returned.
nsIDOMOfflineResourceList
return value true if the resource is in the list, otherwise false.
nsIDataSignatureVerifier
return value true if the signature matches the data, false if not.
nsIDictionary
return value true if present, false if absent.
getFile
if false, then the directory service will not cache the results of this method.
nsIDirectoryServiceProvider
false if the provider will be asked for this prop each time it is requested.
nsIDownloadManagerUI
9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void getattention(); void show([optional] in nsiinterfacerequestor awindowcontext, [optional] in unsigned long aid, [optional] in short areason); attributes attribute type description visible boolean true if the download manager ui is visible; otherwise false.
nsIDragSession
return value true if the specified flavor matches any of the native data on the clipboard, otherwise false.
nsIDroppedLinkHandler
aallowsamedocument if false, drops are only allowed if the document of the source of the drag is different from the destination.
nsIEditor
true if the current selection anchor is editable; otherwise false.
nsIEnvironment
if the variable was not defined in the environment pr_false will be returned.
nsIEventTarget
if events dispatched to this target will be processed on another thread, returns false.
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.
nsIFactory
void lockfactory( in prbool lock ); parameters lock true to lock the factory, and false to unlock the factory.
nsIFileView
/fileview;1"] .createinstance(components.interfaces.nsifileview); //create an instance of the component tview = fview.queryinterface(components.interfaces.nsitreeview); //get the nsitreeview interface fview.setdirectory(lfile.queryinterface(components.interfaces.nsifile)); //set the directory fview.setfilter("*"); //add an appropriate file filter fview.sort(fview.sortname, false); //set the sort type ftree.view = tview; //set the view on the tree object </script> </window> ...
nsIFrameMessageListener
objects unimplemented an array of cpow, or null if sync is false.
nsIFrameMessageManager
listenwhenclosed default is false.
nsIGeolocationProvider
return value true if the device is ready and has a position available to return; otherwise false.
nsIGlobalHistory3
if false, the load is in a subframe.
nsIHTMLEditor
adeleteselection delete the selection before inserting if adeleteselection is pr_false, then the element is inserted after the end of the selection for all element except named anchors, which insert before the selection.
nsIIOService
return value true if the port is allowed, false otherwise.
nsIInstallLocation
return value true if the item's resources are managed independently of the extension system, false otherwise.
nsIJSID
return value true if the nsijsid's are valid and have the same nsid, otherwise false.
nsIJSON
writebom specify true if you wish to write a byte-order mark (bom) into the stream, otherwise specify false.
nsIJumpListItem
return value true if items are the same, otherwise false ...
nsILivemarkService
return value true if the given folder is a livemark folder, otherwise it returns false.
nsILocalFile
by default, this value is false on all non-unix systems.
nsIMacDockSupport
if false, the application is only activated if other applications are not currently active.
nsIMessageListener
sync true if the message was sent using sendsyncmessage, false otherwise.
nsIMessageListenerManager
listenwhenclosed specify true to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading; this is false by default.
nsIMessenger
if false, the message is saved as a template aidentity the identity to use if saving as a template.
nsIModule
returning false guaratees that the module will not be unloaded.
Building an Account Manager Extension
if (server.type == \"imap\") return true; return false; }, queryinterface: xpcomutils.generateqi([ components.interfaces.nsimsgaccountmanagerextension ]) } step 2: building a component we convert the interface to a xpcom component and register it in the component manager as account manager extension.
nsIMsgAccountManagerExtension
return value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded.
nsIMsgCompFields
it should be initialized to true and set to false when 'send anyway' is selected by a user.
nsIMsgDatabase
exceptions thrown ns_error_file_target_does_not_exist afoldername doesn't exist and acreate was false.
nsIMsgIdentity
bccothers boolean bcclist astring dobcc boolean dobcclist astring draftfolder astring stationeryfolder astring showsavemsgdlg boolean directoryserver astring overrideglobalpref boolean autocompletetomydomain boolean if this is false, don't append the user's domain to an autocomplete address with no matches.
nsIMsgSearchCustomTerm
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); ...
nsIMsgSearchSession
searchsession.addscopeterm(components.interfaces.nsmsgsearchscope.offlinemail, afolder); var searchterm = searchsession.createterm(); var value = searchterm.value; value.str = avalue; searchterm.value = value; searchterm.op = searchsession.booleanor; searchterm.booleanand = false; searchsession.appendterm(searchterm); searchsession.search(null); inherits from: nsisupports method overview void addsearchterm(in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value, in boolean booleanand, in string arbitraryheader); nsimsgsearchterm createterm(); void appendterm(in nsimsgsearchterm term); void registerlist...
nsIMsgThread
false if unread.
nsINavHistoryObserver
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.
nsINavHistoryResult
aownsweak if false, the result will keep an owning reference to the observer, which must be removed by calling removeobserver().
nsINavHistoryResultObserver
void batching( in boolean atogglemode ); parameters atogglemode specify true to start batch mode or false to finish the batch.
nsIObserver
}, register: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(this, "mytopicid", false); }, unregister: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "mytopicid"); } } instantiation - this should be fired once you're ready to start observing (for example a window's load event).
nsIParserUtils
isxml true if |fragment| is xml and false if html.
nsIPrefBranch2
false holds a strong reference to aobserver.
nsIProperties
return value true if the property exists, false if the property does not exist.
nsIPropertyBag
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.
nsIPropertyBag2
return value true if a key for the property exists, false if it does not.
nsIProtocolHandler
return value return true if the override is approved; otherwise, return false.
nsIRadioInterfaceLayer
void dial( in domstring number ); parameters number missing description exceptions thrown missing exception missing description enumeratecalls() will continue calling callback.enumeratecallstate until the callback returns false.
nsISearchEngine
return value returns true if the engine spec has a url with the given responsetype, false otherwise.
nsISelection2
if false, posts a request which is processed at some point after the method returns.
nsISelectionPrivate
if false, posts a request which is processed at some point after the method returns.
nsISessionStartup
return value true if the session should be restored, otherwise false.
nsISimpleEnumerator
pr_false if there are no more elements in the enumerator.
nsISocketTransport
otherwise false.
nsIStringEnumerator
false if there are no more strings in the enumerator.
nsITaskbarPreview
visible boolean indicates whether or not the preview is visible; by default, this is false.
nsITaskbarWindowPreview
if false, the operating system draws these for you.
nsIThreadEventFilter
return value implement this method to return true if the event is accepted, or false to reject it.
nsIThreadObserver
this parameter will be false during thread shutdown.
nsITraceableChannel
', newlistener.responsebody); }, function(areason) { // promise was rejected, right now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(acatch) { console.error('something went wrong, a typo by dev probably:', acatch); } ); } }; services.obs.addobserver(httpresponseobserver, 'http-on-examine-response', false); // services.obs.removeobserver(httpresponseobserver, 'http-on-examine-response'); // call this when you dont want to listen anymore ...
nsITransactionListener
adidmerge true if transaction was merged, else false.
nsITransferable
return value true if the data is large; otherwise, the result is false.
nsIUTF8StringEnumerator
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.
nsIUpdatePatch
false if another update is selected.
nsIUpdatePrompt
if the app.update.silent preference is true, the app.update.showinstalledui preference is false, or the user interface is already displayed the call will be a no-op.
nsIWebBrowser
for optimal performance, set it to false when appropriate.
nsIWebappsSupport
return value true if the web application is installed, false if it's not installed.
nsIWinAppHelper
returns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the application is not already running with elevated permissions otherwise it returns false.
nsIXPConnect
false by default, although any value set in the moz_report_all_js_exceptions environment variable will override the value passed here.
nsIXULTemplateResult
if false, child content is not processed.
nsIXULWindow
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.
NS_ENSURE_ARG_POINTER
summary macro returns ns_error_invalid_pointer if the macro argument evaluates to false and shows a warning (ns_warning) in this case.
NS ENSURE TRUE
summary macro returns return-value if expr evaluates to false.
nsIAbCard/Thunderbird3
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>.
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).
XPIDL Syntax
MozillaTechXPIDLSyntax
literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= string_literal / char_literal literal /= "true" / "false" ; in regex: /"[^"\n]*["\n]/.
nsIMsgCloudFileProvider
if awithui is false, and the credentials are stale, the onstoprequest of the acallback nsirequestlistener will get the autherr status code passed to it.
Mail composition back end
(it's a minor difference.) prbool dont_deliver_p, - if "dont_deliver_p" is false, then we actually deliver the message to the smtp and/or nntp server nsmsgdelivermode mode, - mode is the delivery mode.
Mail event system
notifyitempropertyflagchanged onitempropertyflagchanged notifyitemevent onitemevent notifyfolderloaded onfolderloaded notifydeleteormovemessages ondeleteormovemessages 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") { totalmessageslistenerh...
Building a Thunderbird extension 6: Adding JavaScript
window.addeventlistener("load", function(e) { startup(); }, false); window.setinterval( function() { startup(); }, 60000); //update date every minute function startup() { var mypanel = document.getelementbyid("my-panel"); var date = new date(); var day = date.getday(); var datestring = date.getfullyear() + "." + (date.getmonth()+1) + "." + date.getdate(); mypanel.label = "date: " + datestring; } the first part registers a new event listener that wil...
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.
Detect Opening Folder
to do this you need to capture the select event of the folder [[xul:tree|tree]] whose id is (conveniently) foldertree like so: window.document.getelementbyid('foldertree').addeventlistener("select", testcolumns, false); ...
Use SQLite
eate: function(adbservice, adbfile) { var dbconnection = adbservice.opendatabase(adbfile); this._dbcreatetables(dbconnection); return dbconnection; }, _dbcreatetables: function(adbconnection) { for(var name in this.dbschema.tables) adbconnection.createtable(name, this.dbschema.tables[name]); }, }; window.addeventlistener("load", function(e) { tbirdsqlite.onload(e); }, false); this is another practical sample on how to handle opendatabase and sql queries on the client side, using in-memory (blob) storage of 2mb: var db = opendatabase('mydb', '1.0', 'test db', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executesql('create table if not exists logs (id unique, log)'); tx.executesql('insert into logs (id, log) values (1, "foobar")'); tx.executesq...
customDBHeaders Preference
tedbobserver = { // components.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { dump("here here!"); addcustomcolumnhandler(); } } function doonceloaded(){ var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", false); window.document.getelementbyid('foldertree').addeventlistener("select",addcustomcolumnhandler,false); } window.addeventlistener("load",doonceloaded,false); dump(" ~ ~ ~ ~ end superfluous ~ ~ ~ ~ \n"); important be aware that only messages that are added to the .msf database after the customdbheaders pref is set will have the corresponding string property set on the msghdr.
Working with windows in chrome code
ses["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); for (var i = 4; i < arguments.length; i++) { var variant = components.classes["@mozilla.org/variant;1"] .createinstance(components.interfaces.nsiwritablevariant); variant.setfromvariant(arguments[i]); array.appendelement(variant, false); } var watcher = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); return watcher.openwindow(parentwindow, url, windowname, features, array); } the function almost works the same as window.opendialog but accepts an optional parent window as first parameter.
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 ?
Working with data
in particular, comparing two different objects that are represented under-the-hood as javascript objects using the == or === operators will always return false.
ctypes.open
if addon is packed, this will be addon xpi } this can then be joined with your file name to obtain it's path like this: function startup(adata, areason) { var jarpath_folder = 'jar:' + os.path.tofileuri(adata.installpath.path) + '!/'; // if unpacked is false in install.rdf this will look like: "jar:file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aksozfjt.unnamed%20profile%2010/extensions/asynczip@jetpack!/" var filepath_folder = adata.installpath.path; // if unpacked is set to false in install.rdf this will look like: "c:\users\vayeate\appdata\roaming\mozilla\firefox\profiles\aksozfjt.unnamed profile 10\extensions\asynczip@jetpa...
PointerType
return value true if the pointer's value is null, otherwise false.
Mozilla
unlike most other sanitizers, msan can easily cause false positives if not all libraries are instrumented.
Plug-in Basics - Plugins
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" > ...
Streams - Plugins
the seekable parameter specifies whether the stream is seekable (true) or not (false).
Browser Console - Firefox Developer Tools
t 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.
Browser Toolbox - Firefox Developer Tools
you will be presented with a dialog like this (it can be removed by setting the devtools.debugger.prompt-connection property to false): click ok, and the browser toolbox will open in its own window: you'll be able to inspect the browser's chrome windows and see, and be able to debug, all the javascript files loaded by the browser itself and by any add-ons that are running.
Debug eval sources - Firefox Developer Tools
in the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceurl=my-foo.js`; eval(script); var button = document.getelementbyid("foo"); button.addeventlistener("click", foo, false); the evaluated string is given the name "my-foo.js" using the //# sourceurl directive.
Examine, modify, and watch variables - Firefox Developer Tools
if you need to use it, you can, for now, switch back to the old debugger by visiting about:config and setting the "devtools.debugger.new-debugger-frontend" preference to false.
Step through code - Firefox Developer Tools
if you want to turn this feature off, since firefox 71 you can do so by going to about:config in a new tab, setting the devtools.debugger.features.overlay pref to false, and restarting the browser.
Examine and edit CSS - Firefox Developer Tools
in order to use this simulator, you must set privacy.resistfingerprinting to false.
Animation inspector example: Web Animations API - Firefox Developer Tools
= 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); ...
about:debugging - Firefox Developer Tools
service workers can be unavailable if the dom.serviceworkers.enable preference is set to false in about:config.
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).
AddressErrors - Web APIs
window.addeventlistener("load", function(ev) { document.getelementbyid("pay").addeventlistener("click", process, false); }, false); see addeventlistener() for information about event handlers and how they work.
Animation.pause() - Web APIs
WebAPIAnimationpause
cake.addeventlistener("mouseup", stopplayingalice, false); bottle.addeventlistener("mouseup", stopplayingalice, false); specifications specification status comment web animationsthe definition of 'play()' in that specification.
Animation.pending - Web APIs
WebAPIAnimationpending
syntax var pending = animation.pending; value true if the animation is pending, false otherwise.
Animation.play() - Web APIs
WebAPIAnimationplay
cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growalice, false); specifications specification status comment web animationsthe definition of 'play()' in that specification.
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
the default is false.
AudioBufferSourceNode - Web APIs
its default value is false.
AudioContext.createMediaStreamDestination() - Web APIs
<!doctype html> <html> <head> <title>createmediastreamdestination() demo</title> </head> <body> <h1>createmediastreamdestination() demo</h1> <p>encoding a pure sine wave to an opus file </p> <button>make sine wave</button> <audio controls></audio> <script> var b = document.queryselector("button"); var clicked = false; var chunks = []; 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 reco...
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.value = 20; ...
AudioParam.value - Web APIs
WebAPIAudioParamvalue
consider this example: const source = new audiobuffersourcenode(...); const rate = 5.3; source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); the log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863.
AudioScheduledSourceNode: ended event - Web APIs
examples in this simple example, an event listener for the ended event is set up to enable a "start" button in the user interface when the node stops playing: node.addeventlistener('ended', () => { document.getelementbyid("startbutton").disabled = false; }) you can also set up the event handler using the audioscheduledsourcenode.onended property: node.onended = function() { document.getelementbyid("startbutton").disabled = false; } for an example of the ended event in use, see our audio-buffer example on github.
AudioScheduledSourceNode.onended - Web APIs
node.onended = function(event) { document.getelementbyid("startbutton").disabled = false; } specifications specification status comment web audio apithe definition of 'onended' in that specification.
BaseAudioContext.createDynamicsCompressor() - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
BaseAudioContext.createPeriodicWave() - Web APIs
the default is false.
BatteryManager.charging - Web APIs
otherwise, the value is false.
Using the Beacon API - Web APIs
if the browser successfully queues the request for delivery, the method returns true and returns false otherwise.
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.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).
BluetoothRemoteGATTServer.connected - Web APIs
it can be false while the user agent is physically connected.
BluetoothRemoteGATTServer - Web APIs
it can be false while the user agent is physically connected.
Body.bodyUsed - Web APIs
WebAPIBodybodyUsed
this returns false before and true afterwards, as at that point the body has been read.
CSSNumericValue.equals() - Web APIs
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.
CSSNumericValue - Web APIs
otherwise, false.
CSSPseudoElement.element - Web APIs
low 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 false specifications specification status comment css ...
CSSStyleValue.parse() - Web APIs
const css = cssstylevalue.parse( 'transform', 'translate3d(10px,10px,0) scale(0.5)'); csstransformvalue {0: csstranslate, 1: cssscale, length: 2, is2d: false} specifications specification status comment css typed om level 1the definition of 'parse()' in that specification.
Using the CSS Painting API - Web APIs
if set to false, all colours used on the canvas will be fully opaque */ static get contextoptions() { return { alpha: true }; } /* ctx is the 2d drawing context a subset of the html5 canvas api.
CSS Properties and Values API - Web APIs
examples the following uses css.registerproperty in javascript to type a css custom properties, --my-color, as a color, give it a default value, and not allow it to inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); the same registration can take place in css using the following @property: @property --my-color { syntax: '<color>'; inherits: false; initial-value: #c0ffee; } specifications specification status comment css properties and values api level 1 working draft initial definition.
Using the CSS Typed Object Model - Web APIs
for example, had we included transform: translate3d(1px, 1px, 3px), the .get('transform') would have returned a csstranslate with cssunitvalues for x, y, and z, and the readonly .is2d property would have been false.
CSS Typed Object Model API - Web APIs
otherwise, false cssnumericvalue.to - converts value into another one with the specified unit.
Cache - Web APIs
WebAPICache
if no cache entry is found, the promise resolves to false.
CacheStorage.has() - Web APIs
WebAPICacheStoragehas
return value a promise that resolves to true if the cache exists or false if not.
CanvasRenderingContext2D.addHitRegion() - Web APIs
ady; you might need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <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" style="height:250px"> ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi, false); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.arc(130, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi, false); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.ge...
CanvasRenderingContext2D.arc() - Web APIs
the default is false (clockwise).
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
> <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; // focus button1, if appropriate drawbutton(button1, 20, 20); if (ctx.ispointinpath(x, y)) { b...
CanvasRenderingContext2D.ellipse() - Web APIs
the default value is false (clockwise).
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
byid('video'); this.c1 = document.getelementbyid('c1'); this.ctx1 = this.c1.getcontext('2d'); this.c2 = document.getelementbyid('c2'); this.ctx2 = this.c2.getcontext('2d'); let self = this; this.video.addeventlistener('play', function() { self.width = self.video.videowidth / 2; self.height = self.video.videoheight / 2; self.timercallback(); }, false); }, this code grabs references to the elements in the xhtml document that are of particular interest, namely the video element and the two canvas elements.
Applying styles and colors - Web APIs
25 : -25; ctx.lineto(math.pow(i, 1.5) * 2, 75 + dy); } ctx.stroke(); return false; } <table> <tr> <td><canvas id="canvas" width="150" height="150"></canvas></td> <td>change the <code>miterlimit</code> by entering a new value below and clicking the redraw button.<br><br> <form onsubmit="return draw();"> <label>miter limit</label> <input type="number" size="3" id="miterlimit"/> <input type="submit" value="redraw"/> </form> </t...
Basic animations - Web APIs
seconds()); ctx.translate(105, 0); ctx.fillrect(0, -12, 40, 24); // shadow ctx.drawimage(earth, -12, -12); // moon ctx.save(); ctx.rotate(((2 * math.pi) / 6) * time.getseconds() + ((2 * math.pi) / 6000) * time.getmilliseconds()); ctx.translate(0, 28.5); ctx.drawimage(moon, -3.5, -3.5); ctx.restore(); ctx.restore(); ctx.beginpath(); ctx.arc(150, 150, 105, 0, math.pi * 2, false); // earth orbit ctx.stroke(); ctx.drawimage(sun, 0, 0, 300, 300); window.requestanimationframe(draw); } init(); <canvas id="canvas" width="300" height="300"></canvas> screenshotlive sample an animated clock this example draws an animated clock, showing your current time.
Compositing example - Web APIs
var lightmix = function() { var ctx = canvas2.getcontext("2d"); ctx.save(); ctx.globalcompositeoperation = "lighter"; ctx.beginpath(); ctx.fillstyle = "rgba(255,0,0,1)"; ctx.arc(100, 200, 100, math.pi*2, 0, false); ctx.fill() ctx.beginpath(); ctx.fillstyle = "rgba(0,0,255,1)"; ctx.arc(220, 200, 100, math.pi*2, 0, false); ctx.fill() ctx.beginpath(); ctx.fillstyle = "rgba(0,255,0,1)"; ctx.arc(160, 100, 100, math.pi*2, 0, false); ctx.fill(); ctx.restore(); ctx.beginpath(); ctx.fillstyle = "#f00"; ctx.fillrect(0,0,30,30) ctx.fill(); }; var colorsphere ...
Clients.matchAll() - Web APIs
WebAPIClientsmatchAll
the default is false.
Clients.openWindow() - Web APIs
(windowclient.focus(), true) : false); // otherwise, open a new tab to the applicable url and focus it.
CloseEvent() - Web APIs
closeeventinit optional is a closeeventinit dictionary, having the following fields: "wasclean", optional and defaulting to false, of type long, indicates if the connection has been closed cleanly or not.
console - Web APIs
WebAPIConsole
methods console.assert() log a message and stack trace to console if the first argument is false.
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() - Web APIs
the default is 'false'.
CryptoKey - Web APIs
WebAPICryptoKey
false the key may not be extracted.
DOMMatrixReadOnly.scale() - Web APIs
we test if the browser supports a six parameter scale() method by creating a new matrix using three parameters and observing it's is2d property — if this is false then the third parameter has been accepted by the browser as a scalez parameter, making this a 3d matrix.
DOMTokenList.supports() - Web APIs
syntax let trueorfalse = element.supports(token) parameters token a domstring containing the token to query for.
DOMTokenList - Web APIs
domtokenlist.contains(token) returns true if the list contains the given token, otherwise false.
DataTransfer.clearData() - Web APIs
color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript window.addeventlistener('domcontentloaded', function () { // select html elements var draggable = document.getelementbyid('source'); var dropable = document.getelementbyid('target'); var status = document.getelementbyid('status'); var data = document.getelementbyid('data'); var dropped = false; // register event handlers draggable.addeventlistener('dragstart', dragstarthandler); draggable.addeventlistener('dragend', dragendhandler); dropable.addeventlistener('dragover', dragoverhandler); dropable.addeventlistener('dragleave', dragleavehandler); dropable.addeventlistener('drop', drophandler); function dragstarthandler (event) { status.innerhtml = 'drag in process'; ...
DataTransfer - Web APIs
it will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location.
DataTransferItem.webkitGetAsEntry() - Web APIs
first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.addeventlistener("dragover", function(event) { event.preventdefault(); }, false); the event handler that kicks everything off, of course, is the handler for the drop event: dropzone.addeventlistener("drop", function(event) { let items = event.datatransfer.items; event.preventdefault(); listing.innerhtml = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitgetasentry(); if (item) { scanfiles(item, listing); } } }, false); t...
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.caretRangeFromPoint() - Web APIs
toffset; } // only split text_nodes if (textnode && textnode.nodetype == 3) { let replacement = textnode.splittext(offset); let br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } let paragraphs = document.getelementsbytagname("p"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].addeventlistener('click', insertbreakatpoint, false); } result ...
Document.createEvent() - Web APIs
elem.addeventlistener('build', function (e) { // e.target matches elem }, false); // target can be any element or other eventtarget.
Document.createTreeWalker() - Web APIs
var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var nodelist = []; var currentnode = treewalker.currentnode; while(currentnode) { nodelist.push(currentnode); currentnode = treewalker.nextnode(); } specifications specification status comment domthe definition of 'document.createtreewalker' in that specification.
Document.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.
Document.fullscreenEnabled - Web APIs
if full-screen mode isn't available, this value is false.
Document.hasFocus() - Web APIs
WebAPIDocumenthasFocus
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.mozSyntheticDocument - Web APIs
syntax var issynthetic = document.mozsyntheticdocument; on return, issynthetic is true if the document is a synthetic one; otherwise it's false.
Document.onoffline - Web APIs
the document.onoffline event handler is called when an offline is fired on the <body> element and bubbles up, when navigator.online property changes and becomes false.
Document.ononline - Web APIs
WebAPIDocumentononline
window.navigator.online returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network).
Document.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: alert("the state of the 'bold' command is indeterminable."); break; } document.execcommand('bold'); } result specifications specification status comment execcommand ...
Document.requestStorageAccess() - Web APIs
to make testing easier, we have added two preferences in about:config that control prompting upon requeststorageaccess() calls: dom.storage_access.auto_grants can be set to false to disable the automatic granting of ephemeral storage access grants.
Document: scroll event - Web APIs
// reference: http://www.html5rocks.com/en/tutorials/speed/animations/ 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 p...
Document - Web APIs
WebAPIDocument
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.
DocumentOrShadowRoot.activeElement - Web APIs
ctionend ); const outputelement = document.getelementbyid('output-element'); const outputtext = document.getelementbyid('output-text'); outputelement.innerhtml = activetextarea.id; outputtext.innerhtml = selection; } const textarea1 = document.getelementbyid('ta-example-one'); const textarea2 = document.getelementbyid('ta-example-two'); textarea1.addeventlistener('mouseup', onmouseup, false); textarea2.addeventlistener('mouseup', onmouseup, false); result specifications specification status comment html living standardthe definition of 'activeelement' in that specification.
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
only split text_nodes if (textnode.nodetype == 3) { var replacement = textnode.splittext(offset); var br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } window.onload = function (){ var paragraphs = document.getelementsbytagname("p"); for (i=0 ; i < paragraphs.length; i++) { paragraphs[i].addeventlistener("click", insertbreakatpoint, false); } }; specifications specification status comment css object model (cssom) view modulethe definition of 'caretpositionfrompoint()' in that specification.
DocumentOrShadowRoot.fullscreenElement - Web APIs
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.
Events and the DOM - Web APIs
eventtarget.addeventlistener // assuming mybutton is a button element mybutton.addeventlistener('click', greet, false) function greet(event){ // print and have a look at the event object // always print arguments in case of overlooking any other arguments console.log('greet:', arguments) alert('hello world') } this is the method you should use in modern web pages.
Examples of web and XML development using the DOM - Web APIs
ev.stoppropagation(); alert("event propagation halted."); } function load() { elem = document.getelementbyid("tbl1"); elem.addeventlistener("click", stopevent, false); } </script> </head> <body onload="load();"> <table id="t-daddy" onclick="alert('hi');"> <tr id="tbl1"> <td id="c1">one</td> </tr> <tr> <td id="c2">two</td> </tr> </table> </body> </html> example 6: getcomputedstyle this example demonstrates how the window.getcomputedstyle method can be used to get the styles of an element that are not set using the style attribute or with ...
DragEvent.dataTransfer - Web APIs
} dragtarget.addeventlistener("dragend", function(ev) { // call the drag and drop data processor if (ev.datatransfer !== null) processdata(ev.datatransfer); }, false); specifications specification status comment html living standardthe definition of 'dragevent.datatransfer' in that specification.
DynamicsCompressorNode.attack - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
DynamicsCompressorNode.knee - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
DynamicsCompressorNode.ratio - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
DynamicsCompressorNode.release - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
DynamicsCompressorNode.threshold - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
DynamicsCompressorNode - Web APIs
0, audioctx.currenttime); compressor.ratio.setvalueattime(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.disc...
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
return value a glboolean indicating whether the given object is a webglquery object (true) or not (false).
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
document.getelementbyid("animatebutton").addeventlistener("click", event => { document.getelementbyid("box").animate( boxrotationkeyframes, boxrotationtiming ); }, false); the rest of the code is pretty simple: it adds an event listener to the "animate" button so that when it's clicked by the user, the box is animated by calling element.animate() on it, providing the boxrotationkeyframes and boxrotationtiming objects to describe the animation that should occur.
Element.getAnimations() - Web APIs
defaults to false.
Element.hasAttribute() - Web APIs
syntax var result = element.hasattribute(name); result holds the return value true or false.
Element.hasAttributeNS() - Web APIs
syntax result = element.hasattributens(namespace,localname) result is the boolean value true or false.
Element.hasAttributes() - Web APIs
syntax var result = element.hasattributes(); return value result holds the return value true or false.
Element.hasPointerCapture() - Web APIs
return value a boolean value — true if the element does have pointer capture, false if it doesn't.
Element: mouseout event - Web APIs
3</li> </ul> javascript let test = document.getelementbyid("test"); // briefly make the list purple when the mouse moves off the // <ul> element test.addeventlistener("mouseleave", function( event ) { // highlight the mouseleave target event.target.style.color = "purple"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 1000); }, false); // briefly make an <li> orange when the mouse moves off of it test.addeventlistener("mouseout", function( event ) { // highlight the mouseout target event.target.style.color = "orange"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 500); }, false); result specifications specification status ui event...
Element: mouseover event - Web APIs
javascript let test = document.getelementbyid("test"); // this handler will be executed only once when the cursor // moves over the unordered list test.addeventlistener("mouseenter", function( event ) { // highlight the mouseenter target event.target.style.color = "purple"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 500); }, false); // this handler will be executed every time the cursor // is moved over a different list item test.addeventlistener("mouseover", function( event ) { // highlight the mouseover target event.target.style.color = "orange"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 500); }, false); result specifications specificati...
Element: overflow event - Web APIs
ding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getelementbyid("wrapper"), child = document.getelementbyid("child"), toggle = document.getelementbyid("toggle"); wrapper.addeventlistener("overflow", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underflow", function( event ) { console.log( event ); }, false); toggle.addeventlistener("change", function( event ) { if ( event.target.checked ) { child.style.width = "40px"; child.style.height = "40px"; } else { child.style.width = "10px"; child.style.height = "10px"; } }, false); </script> ...
Element: paste event - Web APIs
gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const target = document.queryselector('div.target'); target.addeventlistener('paste', (event) => { let paste = (event.clipboarddata || window.clipboarddata).getdata('text'); paste = paste.touppercase(); const selection = window.getselection(); if (!selection.rangecount) return false; selection.deletefromdocument(); selection.getrangeat(0).insertnode(document.createtextnode(paste)); event.preventdefault(); }); result specifications specification status clipboard api and events working draft ...
Element.scrollIntoViewIfNeeded() - Web APIs
if false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor.
Element: scroll event - Web APIs
// reference: http://www.html5rocks.com/en/tutorials/speed/animations/ 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 ...
Element.setAttribute() - Web APIs
the absence of the attribute means its value is false.
Element: show event - Web APIs
cancelable no interface event event handler property onshow examples <div contextmenu="test"></div> <menu type="context" id="test"> <menuitem label="alert" onclick="alert('the alert label has been clicked')" /> </menu> <script> document.getelementbyid("test").addeventlistener("show", function(e){ alert("the context menu will be displayed"); }, false); </script> specifications specification status html5the definition of 'show event' in that specification.
Element.tabStop - Web APIs
WebAPIElementtabStop
syntax var istabstop = element.tabstop; element.tabstop = (true|false); example // tbd ...
Element: underflow event - Web APIs
ding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getelementbyid("wrapper"), child = document.getelementbyid("child"), toggle = document.getelementbyid("toggle"); wrapper.addeventlistener("overflow", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underflow", function( event ) { console.log( event ); }, false); toggle.addeventlistener("change", function( event ) { if ( event.target.checked ) { child.style.width = "40px"; child.style.height = "40px"; } else { child.style.width = "10px"; child.style.height = "10px"; } }, false); </script> ...
Comparison of Event Targets - Web APIs
telementbyid('explicitoriginaltarget').innerhtml = e.explicitoriginaltarget; document.getelementbyid('originaltarget').innerhtml = e.originaltarget; } function handlemouseover(e) { document.getelementbyid('target').innerhtml = e.target; document.getelementbyid('relatedtarget').innerhtml = e.relatedtarget; } document.addeventlistener('click', handleclicks, false); document.addeventlistener('mouseover', handlemouseover, false); </script> </body> </html> use of target and relatedtarget the relatedtarget property for the mouseover event holds the node that the mouse was previously over.
Event.cancelBubble - Web APIs
in later implementations, setting this to false does nothing.
Event.cancelable - Web APIs
WebAPIEventcancelable
if the event is not cancelable, then its cancelable property will be false and the event listener cannot stop the event from occurring.
Event.currentTarget - Web APIs
function hide(e){ e.currenttarget.style.visibility = 'hidden'; console.log(e.currenttarget); // when this function is used as an event handler: this === e.currenttarget } var ps = document.getelementsbytagname('p'); for(var i = 0; i < ps.length; i++){ // console: print the clicked <p> element ps[i].addeventlistener('click', hide, false); } // console: print <body> document.body.addeventlistener('click', hide, false); // click around and make paragraphs disappear note: the value of event.currenttarget is only available while the event is being handled.
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.isTrusted - Web APIs
WebAPIEventisTrusted
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.msConvertURL() - Web APIs
example var bloblist = []; document.getelementbyid("pastezone").addeventlistener('paste', handlepaste, false); function handlepaste(evt) { var filelist = window.clipboarddata.files; // note that window.datatransfer.files is not applicable.
Event.target - Web APIs
WebAPIEventtarget
= document.createelement('li'); ul.appendchild(li1); ul.appendchild(li2); function hide(evt) { // e.target refers to the clicked <li> element // this is different than e.currenttarget, which would refer to the parent <ul> in this context evt.target.style.visibility = 'hidden'; } // attach the listener to the list // it will fire when each <li> is clicked ul.addeventlistener('click', hide, false); specifications specification status comment domthe definition of 'event.target' in that specification.
Event.type - Web APIs
WebAPIEventtype
html <p>press any key or click the mouse to get the event type.</p> <p id="log"></p> javascript function geteventtype(event) { const log = document.getelementbyid('log'); log.innertext = event.type + '\n' + log.innertext; } // keyboard events document.addeventlistener('keydown', geteventtype, false); // first document.addeventlistener('keypress', geteventtype, false); // second document.addeventlistener('keyup', geteventtype, false); // third // mouse events document.addeventlistener('mousedown', geteventtype, false); // first document.addeventlistener('mouseup', geteventtype, false); // second document.addeventlistener('click', geteventtype, false); // third result specifica...
EventSource() - Web APIs
the possible entries are: withcredentials, defaulting to false, indicating if cors should be set to include credentials.
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.dispatchEvent() - Web APIs
return value the return value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault().
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.
Fetch API - Web APIs
WebAPIFetch API
instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
File.webkitRelativePath - Web APIs
ry multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications specification status comment file and directory entries apithe definition of 'webkitrelativepath' in that specification.
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, but inherits properties from its parent interface, filesystementry.
FileSystemDirectoryReader.readEntries() - Web APIs
first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.addeventlistener("dragover", function(event) { event.preventdefault(); }, false); the event handler that kicks everything off, of course, is the handler for the drop event: dropzone.addeventlistener("drop", function(event) { let items = event.datatransfer.items; event.preventdefault(); listing.innerhtml = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitgetasentry(); if (item) { scanfiles(item, listing); } } }, false); t...
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.
Using FormData Objects - Web APIs
d("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 the method specified in the open() call.
FormData.has() - Web APIs
WebAPIFormDatahas
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.
Guide to the Fullscreen API - Web APIs
document.addeventlistener("keydown", function(e) { if (e.keycode == 13) { togglefullscreen(); } }, false); toggling fullscreen mode this code is called when the user hits the enter key, as seen above.
Gamepad.buttons - Web APIs
WebAPIGamepadbuttons
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).
Gamepad.connected - Web APIs
WebAPIGamepadconnected
if the gamepad is connected, the value is true; if not, it is false.
GamepadButton.pressed - Web APIs
the gamepadbutton.pressed property of the gamepadbutton interface returns a boolean indicating whether the button is currently pressed (true) or unpressed (false).
GamepadButton - Web APIs
gamepadbutton.pressed read only a boolean value indicating whether the button is currently pressed (true) or unpressed (false).
Geolocation.clearWatch() - Web APIs
unction success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulation, you reach the target'); navigator.geolocation.clearwatch(id); } }; function error(err) { console.warn('error(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success, error, options); specifications specification status comment geolocation api recommendation initial specification.
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.cod...
Geolocation.watchPosition() - Web APIs
nction success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulations, you reached the target'); navigator.geolocation.clearwatch(id); } } function error(err) { console.warn('error(' + err.code + '): ' + err.message); } target = { latitude : 0, longitude: 0 }; options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success, error, options); specifications specification status comment geolocation apithe definition of 'watchposition()' in that specification.
GlobalEventHandlers.onanimationend - Web APIs
= function(event) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onanimationiteration - Web APIs
finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { box.style.animationplaystate = "running"; iterationcounter++; }, false); this sets the box element's animation-play-state to "running" and increments the iteration counter.
GlobalEventHandlers.onanimationstart - Web APIs
= function(event) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onerror - Web APIs
{ var string = msg.tolowercase(); var substring = "script error"; if (string.indexof(substring) > -1){ alert('script error: see browser console for detail'); } else { var message = [ 'message: ' + msg, 'url: ' + url, 'line: ' + lineno, 'column: ' + columnno, 'error object: ' + json.stringify(error) ].join(' - '); alert(message); } return false; }; when using the inline html markup (<body onerror="alert('an error occurred')">), the html specification requires arguments passed to onerror to be named event, source, lineno, colno, error.
GlobalEventHandlers.onkeypress - Web APIs
html <label>enter numbers only: <input> </label> javascript function numbersonly(event) { return event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.queryselector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exit" in any point of a page.
HTMLAreaElement - Web APIs
htmlareaelement.nohref is a boolean flag indicating if the area is inactive (true) or active (false).
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example var canvas = document.getelementbyid('canvas'); canvas.addeventlistener('webglcontextcreationerror', function(e) { console.log(e.statusmessage || 'unknown error'); }, false); var gl = canvas.getcontext('webgl'); // logs statusmessage or "unknown error" if unable to create webgl context specifications specification status comment webgl 1.0the definition of 'webglcontextcreationerror' in that specification.
HTMLCanvasElement: webglcontextrestored event - Web APIs
yes cancelable yes interface webglcontextevent event handler property none example with the help of the webgl_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); // "webglcontextrestored" event is logged.
HTMLCanvasElement - Web APIs
this is only supported in mozilla-based browsers; use the standardized canvas.getcontext('2d', { alpha: false }) instead.
HTMLDialogElement.open - Web APIs
false means it not set, and therefore the dialog is not shown.
HTMLElement.contentEditable - Web APIs
'false' indicates that the element cannot be edited.
HTMLElement.isContentEditable - Web APIs
the htmlelement.iscontenteditable read-only property returns a boolean that is true if the contents of the element are editable; otherwise it returns false.
HTMLElement - Web APIs
htmlelement.contenteditable is a domstring, where a value of true means the element is editable and a value of false means it isn't.
HTMLIFrameElement.setNfcFocus() - Web APIs
default is false; set to true to allow it to receive nfc events.
HTMLImageElement.isMap - Web APIs
syntax htmlimageelement.ismap = true|false; let ismap = htmlimageelement.ismap; value a boolean value which is true if the image is being used for a server-side image map; otherwise, the value is false.
HTMLMediaElement.audioTracks - Web APIs
var video = document.getelementbyid("video"); for (var i = 0; i < video.audiotracks.length; i += 1) { video.audiotracks[i].enabled = false; } specifications specification status comment html living standardthe definition of 'htmlmediaelement.audiotracks' in that specification.
HTMLMediaElement.disableRemotePlayback - Web APIs
(false means "not disabled", which means "enabled") example var obj = document.createelement('audio'); obj.disableremoteplayback = true; specifications specification status comment remote playback apithe definition of 'disableremoteplayback' in that specification.
HTMLMediaElement.paused - Web APIs
true is paused and false is not paused.
HTMLMediaElement.play() - Web APIs
example this example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback: let videoelem = document.getelementbyid("video"); let playbutton = document.getelementbyid("playbutton"); playbutton.addeventlistener("click", handleplaybutton, false); playvideo(); async function playvideo() { try { await videoelem.play(); playbutton.classlist.add("playing"); } catch(err) { playbutton.classlist.remove("playing"); } } function handleplaybutton() { if (videoelem.paused) { playvideo(); } else { videoelem.pause(); playbutton.classlist.remove("playing"); } } in this example, playback of video is toggled off a...
HTMLMediaElement: seeked event - Web APIs
the seeked event is fired when a seek operation completed, the current playback position has changed, and the boolean seeking attribute is changed to false.
HTMLOListElement - Web APIs
htmlolistelement.reversed is a boolean value reflecting the reversed and defining if the numbering is descending, that is its value is true, or ascending (false).
HTMLObjectElement.validationMessage - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints.
HTMLObjectElement.willValidate - Web APIs
always false for htmlobjectelement objects.
HTMLOptGroupElement - Web APIs
htmloptgroupelement.disabled is a boolean representing whether or not the whole list of children <option> is disabled (true) or not (false).
HTMLOrForeignElement.dataset - Web APIs
> const el = document.queryselector('#user'); // el.id === 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'johndoe' // el.dataset.dateofbirth === '' // set the data attribute el.dataset.dateofbirth = '1960-10-03'; // result: el.dataset.dateofbirth === 1960-10-03 delete el.dataset.dateofbirth; // result: el.dataset.dateofbirth === undefined // 'somedataattr' in el.dataset === false el.dataset.somedataattr = 'mydata'; // result: 'somedataattr' in el.dataset === true specifications specification status comment html living standardthe definition of 'htmlelement.dataset' in that specification.
HTMLSelectElement.checkValidity() - Web APIs
if the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
HTMLSelectElement.disabled - Web APIs
ue="1">water</option> <option value="2">beer</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.
HTMLSelectElement.selectedOptions - Web APIs
: "; } output += collection[i].label; if (i === (collection.length - 2) && (collection.length < 3)) { output += " and "; } else if (i < (collection.length - 2)) { output += ", "; } else if (i === (collection.length - 2)) { output += ", and "; } } if (output === "") { output = "you didn't order anything!"; } outputbox.innerhtml = output; }, false); this script sets up a click event listener on the "order now" button.
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).
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.
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
if false, improvements can be made to optimize performance.
HTMLVideoElement.msZoom - Web APIs
set to false the video frame uses letter box or pillarbox to display video.
HTMLVideoElement.videoHeight - Web APIs
let v = document.getelementbyid("myvideo"); v.addeventlistener("resize", ev => { let w = v.videowidth; let h = v.videoheight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); note that this only applies the change if both the videowidth and the videoheight are non-zero.
HTMLVideoElement.videoWidth - Web APIs
let v = document.getelementbyid("myvideo"); v.addeventlistener("resize", ev => { let w = v.videowidth; let h = v.videoheight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); note that this only applies the change if both the videowidth and the videoheight are non-zero.
The HTML DOM API - Web APIs
button = 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.disabled = 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.
Recommended Drag Types - Web APIs
ondrop="dodrop(event)"/> <script> function checkdrag(event) { return event.datatransfer.types.contains("application/x-moz-file"); } function dodrop(event) { var file = event.datatransfer.mozgetdataat("application/x-moz-file", 0); if (file instanceof components.interfaces.nsifile) { event.currenttarget.appenditem(file.leafname); } } </script> in this example, the event returns false only if the data transfer contains the application/x-moz-file type.
HashChangeEvent - Web APIs
examples syntax options for a hash change you can listen for the hashchange event using any of the following options: window.onhashchange = funcref; or <body onhashchange="funcref();"> or window.addeventlistener("hashchange", funcref, false); basic example function locationhashchanged() { if (location.hash === '#somecoolfeature') { somecoolfeature(); } } window.addeventlistener('hashchange', locationhashchanged); polyfill there are several fallback scripts listed on the modernizr github page.
Headers.has() - Web APIs
WebAPIHeadershas
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.
IDBCursor.source - Web APIs
WebAPIIDBCursorsource
within each iteration we log the source of the cursor, which will log our idbobjectstore object to the console, something like this: idbobjectstore {autoincrement: false, transaction: idbtransaction, indexnames: domstringlist, keypath: "albumtitle", name: "rushalbumlist"…} the cursor does not require us to select the data based on a key; we can just grab all of it.
IDBCursorSync - Web APIs
returns false if the cursor has reached the end of its range; otherwise returns true.
IDBDatabase.onabort - Web APIs
{ note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function() { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; specificati...
IDBDatabase.onerror - Web APIs
note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; specificati...
IDBDatabase.onversionchange - Web APIs
note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; db.onversion...
IDBDatabase - Web APIs
event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database using // idbdatabase.createobjectstore var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; this next l...
IDBDatabaseSync - Web APIs
autoincrement if true, the object store uses a key generator; if false, it does not use one.
IDBIndex.objectStore - Web APIs
the current object store is logged to the console: it should be returned something like this: idbobjectstore { name: "contactslist", keypath: "id", indexnames: domstringlist[7], transaction: idbtransaction, autoincrement: false } finally, we iterate through each record, and insert the data into an html table.
IDBIndex - Web APIs
WebAPIIDBIndex
if false, then there is one record for each key that is an array.
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.lowerOpen - Web APIs
false the lower-bound value is included in the key range.
IDBKeyRange.upperOpen - Web APIs
false the upper-bound value is included in the key range.
IDBObjectStore.autoIncrement - Web APIs
false the object store does not auto increment.
IDBObjectStore.deleteIndex() - Web APIs
onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); objectstore.deleteindex("seconds"); objectstore.deleteindex("conta...
IDBObjectStore - Web APIs
radeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; // create a...
IDBObjectStoreSync - Web APIs
unique if true, keys in the index must be unique; if false, duplicate keys are allowed.
IDBOpenDBRequest - Web APIs
onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); }; specifications specification status comment ...
IDBTransactionSync - Web APIs
static boolean if true, this transaction is static; if false, this transaction is dynamic.
IdleDeadline.didTimeout - Web APIs
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.
ImageCapture - Web APIs
img.width * ratio) / 2; let y = (canvas.height - img.height * ratio) / 2; canvas.getcontext('2d').clearrect(0, 0, canvas.width, canvas.height); canvas.getcontext('2d').drawimage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio); } document.queryselector('video').addeventlistener('play', function() { document.queryselector('#grabframebutton').disabled = false; document.queryselector('#takephotobutton').disabled = false; }); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in that specification.
InputEvent() - Web APIs
the default is false.
InputEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var inputevent = new inputevent('syntheticinput', false); console.log(inputevent.iscomposing); // return false specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'inputevent.iscomposing' in that specification.
enabled - Web APIs
method of installtrigger object syntax boolean enabled (); parameters none returns true if software installation is enabled for this client machine; otherwise, false.
install - Web APIs
returns install returns true if the function succeeded and false if it did not, but these values are not always reliable as a determinant of the success of the operation.
installChrome - Web APIs
returns a boolean value indicating false if the software install feature has been turned off, and true if it's on.
IntersectionObserverEntry - Web APIs
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.
Timing element visibility with the Intersection Observer API - Web APIs
setting up to set things up, we run the startup() function below when the page loads: window.addeventlistener("load", startup, false); function startup() { contentbox = document.queryselector("main"); document.addeventlistener("visibilitychange", handlevisibilitychange, false); let observeroptions = { root: null, rootmargin: "0px", threshold: [0.0, 0.75] }; adobserver = new intersectionobserver(intersectioncallback, observeroptions); buildcontents(); refreshintervalid = window...
Intersection Observer API - Web APIs
const numsteps = 20.0; let boxelement; let prevratio = 0.0; let increasingcolor = "rgba(40, 40, 190, ratio)"; let decreasingcolor = "rgba(190, 40, 40, ratio)"; // set things up window.addeventlistener("load", (event) => { boxelement = document.queryselector("#box"); createobserver(); }, false); the constants and variables we set up here are: numsteps a constant which indicates how many thresholds we want to have between a visibility ratio of 0.0 and 1.0.
KeyboardEvent.altKey - Web APIs
the keyboardevent.altkey read-only property is a boolean that indicates if the alt key (option or ⌥ on os x) was pressed (true) or not (false) when the event occured.
KeyboardEvent.ctrlKey - Web APIs
the keyboardevent.ctrlkey read-only property returns a boolean that indicates if the control key was pressed (true) or not (false) when the event occured.
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.
KeyboardEvent.initKeyEvent() - Web APIs
false, // ctrlkeyarg, false, // altkeyarg, false, // shiftkeyarg, false, // metakeyarg, 9, // keycodearg, 0); // charcodearg); document.getelementbyid('blah').dispatchevent(event); specification this implementation of keyboard events...
KeyboardEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var kbdevent = new keyboardevent("synthetickey", false); console.log(kbdevent.iscomposing); // return false specifications specification status comment ui eventsthe definition of 'keyboardevent.prototype.iscomposing' in that specification.
KeyboardEvent.keyCode - Web APIs
example window.addeventlistener("keydown", function (event) { if (event.defaultprevented) { return; // should do nothing if the default action has been cancelled } var handled = false; if (event.key !== undefined) { // handle the event with keyboardevent.key and set handled true.
KeyboardEvent.shiftKey - Web APIs
the keyboardevent.shiftkey read-only property is a boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred.
LockedFile.abort() - Web APIs
WebAPILockedFileabort
summary the abort method is used to release the lock on the lockedfile object, making it inactive: its active property is set to false and all ongoing operations are canceled.
LockedFile.active - Web APIs
WebAPILockedFileactive
the active property allows to know if the lockedfile object is still usable (true) or not (false).
LockedFile.getMetadata() - Web APIs
each key is a boolean where true means the metadata is expected and where false means it is not expected.
LockedFile - Web APIs
lockedfile.active read only a flag indicating if the file can be accessed (true) or not (false).
MSCandidateWindowHide - Web APIs
the handler of this event will see that the iscandidatewindowvisible method returns false, and no clientrect object is returned from getcandidatewindowclientrect.
MediaDevices.ondevicechange - Web APIs
tton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 30 }, audio: { samplerate: 44100, samplesize: 16, volume: 0.25 } }).then(stream => { videoelement.srcobject = stream; updatedevicelist(); }) .catch(err => log(err.name + ": " + err.message)); }, false); we set up global variables that contain references to the <ul> elements that are used to list the audio and video devices: let audiolist = document.getelementbyid("audiolist"); let videolist = document.getelementbyid("videolist"); getting and drawing the device list now let's take a look at updatedevicelist() itself.
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'); }; windo...
msExtendedCode - Web APIs
}, false); video.addeventlistener('canplay', function () { video1.play(); }, false); ...
MediaQueryList - Web APIs
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.
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.isTypeSupported - Web APIs
if the value is false, the user agent is incapable of recording the specified format.
MediaSessionActionDetails.seekTime - Web APIs
if the value of fastseek is false, or fastseek is missing, the action should be treated as the final action of the operation, and you should finalize any details that need to be handled.
MediaStream.ended - Web APIs
WebAPIMediaStreamended
the ended read-only property of the mediastream interface returns a boolean value which is true if the stream has been completely read, or false if the end of the stream has not been reached.
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 - Web APIs
mediastream.active read only a boolean value that returns true if the mediastream is active, or false otherwise.
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 on your browser!'); } ...
MediaStreamTrack: mute event - Web APIs
musictrack.addeventlistener("mute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track musictrack enters its muted state, the element with the id timeline-widget gets its background color changed to #aaa.
MediaStreamTrack.onunmute - Web APIs
when the onunmute event handler is called, the track's muted flag is false.
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.
MediaStreamTrack: unmute event - Web APIs
musictrack.addeventlistener("mute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track musictrack enters its muted state, the element with the id timeline-widget gets its background color changed to #aaa.
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 supported on your br...
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 supported on your br...
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.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.
MediaTrackConstraints.displaySurface - Web APIs
for example, if your app needs to know that the surface being shared is a monitor or application—meaning that there's possibly a non-content backdrop—it can use code similar to this: let mayhavebackdropflag = false; let displaysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || 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.autoGainControl - Web APIs
syntax var autogaincontrol = mediatracksettings.autogaincontrol; value a boolean value which is true if the track has automatic gain control enabled or false if agc is disabled.
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.
MediaTrackSettings.noiseSuppression - Web APIs
syntax var noisesuppression = mediatracksettings.noisesuppression; value a boolean value which is true if the input track has noise suppression enabled or false if agc is disabled.
MediaTrackSupportedConstraints.aspectRatio - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.autoGainControl - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.channelCount - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.cursor - Web APIs
async function capturewithcursor() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { displaysurface: "browser" }, audio: false; }; if (supportedconstraints.cursor) { displaymediaoptions.video.cursor = "always"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { /* handle the error */ } } specifications specification status comment screen capturethe definition of 'mediatracksupportedconstraints.cursor' in that...
MediaTrackSupportedConstraints.deviceId - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.displaySurface - Web APIs
async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.displaysurface) { displaymediaoptions.video.displaysurface = "monitor"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { /* handle the error */ } } specifications specification status comment screen capturethe definition of 'mediatracksupportedconstraint...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.facingMode - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.frameRate - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.groupId - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.height - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.latency - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.logicalSurface - Web APIs
async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.logicalsurface) { displaymediaoptions.video.logicalsurface = "monitor"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { /* handle the error */ } } specifications specification status comment screen capturethe definition of 'mediatracksupportedconstraint...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.sampleRate - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.sampleSize - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.volume - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
MediaTrackSupportedConstraints.width - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false.
Transcoding assets for Media Source Extensions - Web APIs
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.
MessageChannel() - Web APIs
var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessageChannel.port1 - Web APIs
var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } specifications specification status comment html living standardthe definition of 'port1' in that specification.
MessageChannel.port2 - Web APIs
var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessagePort.close() - Web APIs
WebAPIMessagePortclose
channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); you could stop messages being sent at any time using channel.port1.close(); specifications specification status comment html living standardthe definition of 'close()' in that specification.
MessagePort.onmessage - Web APIs
var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessagePort.postMessage() - Web APIs
var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessagePort.start() - Web APIs
WebAPIMessagePortstart
e is sent back to this document using onmessage: channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } another option would be to do this using eventtarget.addeventlistener, however, when this method is used, you need to explicitly call start() to begin the flow of messages to this document: channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); specifications specification status comment html living standardthe definition of 'start()' in that specification.
MouseEvent.altKey - Web APIs
WebAPIMouseEventaltKey
syntax var altkeypressed = instanceofmouseevent.altkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed.
MouseEvent.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
80px; 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.pageX - Web APIs
WebAPIMouseEventpageX
javascript var box = document.queryselector(".box"); var pagex = document.getelementbyid("x"); var pagey = document.getelementbyid("y"); function updatedisplay(event) { pagex.innertext = event.pagex; pagey.innertext = event.pagey; } box.addeventlistener("mousemove", updatedisplay, false); box.addeventlistener("mouseenter", updatedisplay, false); box.addeventlistener("mouseleave", updatedisplay, false); the javascript code uses addeventlistener() to register the function updatedisplay() as the event handler for the mousemove, mouseenter, and mouseleave events.
MouseEvent.region - Web APIs
WebAPIMouseEventregion
<canvas id="canvas"></canvas> <script> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "circle"}); canvas.addeventlistener("mousemove", function(event){ if(event.region) { console.log("hit region: " + event.region); } }); </script> ...
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.
msIsBoxed - Web APIs
WebAPIMsIsBoxed
boolean value set to false means the video player is zoomed to fill the screen.
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.
MutationEvent - Web APIs
}, false); the event object is passed to the listener in a mutationevent (see its definition in the specification) for most events, and mutationnameevent for domattributenamechanged and domelementnamechanged.
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.
MutationObserverInit.characterDataOldValue - Web APIs
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.
Navigator.getBattery() - Web APIs
let batteryischarging = false; navigator.getbattery().then(function(battery) { batteryischarging = battery.charging; battery.addeventlistener('chargingchange', function() { batteryischarging = battery.charging; }); }); for more examples and details, see battery status api.
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.vibrate() - Web APIs
WebAPINavigatorvibrate
if the method was unable to vibrate because of invalid parameters, it will return false, else it returns true.
navigator.hardwareConcurrency - Web APIs
let workerlist = []; for (let i = 0; i < window.navigator.hardwareconcurrency; i++) { let newworker = { worker: new worker('cpuworker.js'), inuse: false }; workerlist.push(newworker); } specification specification status comment html living standardthe definition of 'navigator.hardwareconcurrency' in that specification.
NavigatorID.taintEnabled() - Web APIs
the navigatorid.taintenabled() method always returns false.
NavigatorID - Web APIs
navigatorid.taintenabled() always returns false.
Node.hasChildNodes() - Web APIs
syntax bool = node.haschildnodes(); return value a boolean that is true if the node has child nodes, and false otherwise.
NodeFilter.acceptNode() - Web APIs
/^\s*$/.test(node.data) ) { return nodefilter.filter_accept; } } }, false ); // show the content of every non-empty text node that is a child of root var node; while ((node = iterator.nextnode())) { alert(node.data); } specifications specification status comment domthe definition of 'nodefilter.acceptnode()' in that specification.
NodeFilter - Web APIs
/^\s*$/.test(node.data) ) { return nodefilter.filter_accept } } }, false ); // show the content of every non-empty text node that is a child of root let node; while ((node = nodeiterator.nextnode())) { alert(node.data) } specifications specification status comment domthe definition of 'nodefilter' in that specification.
NodeIterator.detach() - Web APIs
syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodeiterator.detach(); // detaches the iterator nodeiterator.nextnode(); // throws an invalid_state_err exception specifications specification status comment domthe definition of 'nodeiterator.detach' in that specification.
NodeIterator.filter - Web APIs
syntax nodefilter = nodeiterator.filter; example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = nodeiterator.filter; specifications specification status comment domthe definition of 'nodeiterator.filter' in that specification.
NodeIterator.nextNode() - Web APIs
syntax node = nodeiterator.nextnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node specifications specification status comment domthe definition of 'nodeiterator.nextnode' in that specification.
NodeIterator.previousNode() - Web APIs
syntax node = nodeiterator.previousnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node previousnode = nodeiterator.previousnode(); // same result, since we backtracked to the previous node specifications specification status comment domthe definition of 'nodeiterator.previousnode' in that specification.
NodeIterator.referenceNode - Web APIs
syntax node = nodeiterator.referencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); node = nodeiterator.referencenode; specifications specification status comment domthe definition of 'nodeiterator.referencenode' in that specification.
NodeIterator.root - Web APIs
WebAPINodeIteratorroot
syntax root = nodeiterator.root; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = nodeiterator.root; // document.body in this case specifications specification status comment domthe definition of 'nodeiterator.root' in that specification.
NodeIterator.whatToShow - Web APIs
example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); if( (nodeiterator.whattoshow == nodefilter.show_all) || (nodeiterator.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // nodeiterator will show comments } specifications specification status comment domthe definition of 'nodeiterator.whattoshow' in that specification.
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.
Notification.renotify - Web APIs
false is the default; true makes the notification renotify the user.
Notification.silent - Web APIs
false is the default; true makes the notification silent.
NotificationAction - Web APIs
ownotification("new mail from alice", { actions: [ { action: 'archive', title: 'archive' } ] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'archive') { // archive action was clicked archiveemail(); } else { // main body of notification was clicked clients.openwindow('/inbox'); } }, false); specifications specification status comment notifications api living standard living standard ...
NotificationEvent.action - Web APIs
example self.registration.shownotification("new articles available", { actions: [{action: "get", title: "get now."}] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'get') { synchronizereader(); } else { clients.openwindow("/reader"); } }, false); specifications specification status comment notifications apithe definition of 'action' in that specification.
OES_vertex_array_object.isVertexArrayOES() - Web APIs
return value a glboolean indicating whether the given object is a webglvertexarrayobject object (true) or not (false).
OfflineAudioContext: complete event - Web APIs
amples when processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.addeventlistener('complete', () => { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; }) you can also set up the event handler using the offlineaudiocontext.oncomplete property: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.oncomplete = function() { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; } specifications specification status comment w...
OfflineAudioContext.oncomplete - Web APIs
offlineaudioctx.oncomplete = function() { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; } specifications specification status comment web audio apithe definition of 'oncomplete' in that specification.
PaymentCurrencyAmount.value - Web APIs
ng 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.
PaymentRequest.canMakePayment() - Web APIs
if the payment can't be processed, the promise receives a value of false.
PaymentRequest: merchantvalidation event - Web APIs
request.addeventlistener("merchantvalidation", event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation and payment method documentation.
PaymentRequest.shippingOption - Web APIs
if requestshipping was false (or missing), shippingoption returns null, even the developer provides a selected a shipping option.
PaymentRequest: shippingaddresschange event - Web APIs
const paymentrequest = new paymentrequest(methoddata, details, options); paymentrequest.addeventlistener("shippingaddresschange", event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupate); }, false); const checkaddress = theaddress => { let detailsupdate = {}; // check the address, return a paymentdetailsupdate object // with any changes or errors.
PaymentRequest: shippingoptionchange event - Web APIs
paymentrequest.addeventlistener("shippingoptionchange", event => { const value = calculatenewtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }, false); after caling a custom function, calculatenewtotal(), to compute the updated total based on the newly-selected shipping option as specified by the shippingoption.
PaymentRequest.show() - Web APIs
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.shippingOption - Web APIs
ils.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.
Using the Payment Request API - Web APIs
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.
PeriodicWave.PeriodicWave() - Web APIs
example var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var options = { real : real, imag : imag, disablenormalization : false } var wave = new periodicwave(ac, options); specifications specification status comment web audio apithe definition of 'periodicwave' in that specification.
Using the Permissions API - Web APIs
for example, the pushpermissiondescriptor should also contain a boolean that specifies if uservisibleonly is true or false.
PointerEvent.PointerEvent() - Web APIs
isprimary — optional and defaulting to false, of type boolean, that sets the value of the instance's pointerevent.isprimary.
PointerEvent.pointerId - Web APIs
let id; // let's assume that this is a previously saved pointerid target.addeventlistener('pointerdown', function(event) { // compare previous event's id that was cached // to current event's id and handle accordingly if (id === event.pointerid) process_event(event); }, false); specifications specification status comment pointer events – level 2the definition of 'pointerid' in that specification.
PointerEvent.pointerType - Web APIs
('pointerdown', function(event) { // call the appropriate pointer type handler switch (event.pointertype) { case 'mouse': process_pointer_mouse(event); break; case 'pen': process_pointer_pen(event); break; case 'touch': process_pointer_touch(event); break; default: console.log(`pointertype ${event.pointertype} is not suported`); } }, false); specifications specification status comment pointer eventsthe definition of 'pointertype' in that specification.
PointerEvent.pressure - Web APIs
someelement.addeventlistener('pointerdown', function(event) { if (event.pressure == 0) { // no pressure process_no_pressure(event); } else if (event.pressure == 1) { // maximum pressure process_max_pressure(event); } else { // default process_pressure(event); } }, false); specifications specification status comment pointer events – level 2the definition of 'pressure' in that specification.
PointerEvent.tangentialPressure - Web APIs
someelement.addeventlistener('pointerdown', function(event) { if (event.tangentialpressure == 0) { // no pressure process_no_tanpressure(event); } else if (event.tangentialpressure == 1) { // maximum pressure process_max_tanpressure(event); } else { // default process_tanpressure(event); } }, false); specifications specification status comment pointer events – level 2the definition of 'tangentialpressure' in that specification.
PointerEvent.tiltX - Web APIs
someelement.addeventlistener("pointerdown", function(event) { process_tilt(event.tiltx, event.tilty); }, false); specifications specification status comment pointer events – level 2the definition of 'tiltx' in that specification.
PointerEvent.tiltY - Web APIs
someelement.addeventlistener("pointerdown", function(event) { process_tilt(event.tiltx, event.tilty); }, false); specifications specification status comment pointer events – level 2the definition of 'tilty' in that specification.
PointerEvent.twist - Web APIs
someelement.addeventlistener('pointerdown', function(event) { if (event.twist == 0) { // no twist process_no_twist(event); } else { // default process_twist(event); } }, false); specifications specification status comment pointer events – level 2the definition of 'twist' in that specification.
PointerEvent.width - Web APIs
target.addeventlistener("pointerdown", function(ev) { // calculate the contact area var area = ev.width * ev.height; }, false); specifications specification status comment pointer events – level 2the definition of 'width' in that specification.
PositionOptions.enableHighAccuracy - Web APIs
on the other hand, if false (the default value), the device can take the liberty to save resources by responding more quickly and/or using less power.
ProgressEvent() - Web APIs
it defaults to false.
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
the default value is false.
PublicKeyCredentialRequestOptions.extensions - Web APIs
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); }); specificati...
PublicKeyCredentialRequestOptions - Web APIs
// 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); }); specifications specification status comment web...
PushManager.getSubscription() - Web APIs
var pushbutton = document.queryselector('.js-push-button'); pushbutton.disabled = false; if (!subscription) { // we aren’t subscribed to push, so set ui // to allow the user to enable push return; } // keep your server in sync with the latest subscriptionid sendsubscriptiontoserver(subscription); showcurlcommand(subscription); // set your ui to show they have subscribed for // push messages ...
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 subscribe...
RTCDTMFSender: tonechange event - Web APIs
this can be done using addeventlistener(): dtmfsender.addeventlistener("tonechange", ev => { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;"; } document.getelementbyid("playingtone").innertext = tone; }, false); you can also just set the ontonechange event handler property directly: dtmfsender.ontonechange = function( ev ) { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;" } document.getelementbyid("playingtone").innertext = tone; }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'to...
RTCDTMFToneChangeEvent - Web APIs
dtmfsender.addeventlistener("change", function(event) { if (event.tone !== "") { dialstringbox.innertext += event.tone; } else { senddtmfbutton.disabled = false; } }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmftonechangeevent' in that specification.
RTCDataChannel: bufferedamountlow event - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("sendfile"); let source = /* source data object */ dc.bufferedamountlowthreshold = 65536; pc.addeventlistener("bufferedamountlow", ev => { if (source.position <= source.length) { dc.send(source.readfile(65536)); } }, false); after creating the rtcpeerconnection, this calls rtcpeerconnection.createdatachannel() to create the data channel.
RTCDataChannel: error event - Web APIs
t) { console.error(" received dlts failure alert: ", err.receivedalert); } if (err.sentalert) { console.error(" sent dlts failure alert: ", err.receivedalert); } break; } // add source file name and line information console.error(" error in file ", err.filename, " at line ", err.linenumber, ", column ", err.columnnumber); }, false); the received event provides details in an rtcerror object called error; rtcerror is an extension of the domexception interface.
RTCDataChannel.id - Web APIs
WebAPIRTCDataChannelid
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: message event - Web APIs
dc.addeventlistener("message", ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); }, false); lines 2-4 create the new paragraph element and add the message data to it as a new text node.
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.onopen - Web APIs
let dc = mypeerconnection.createdatachannel("message channel"); dc.onopen = function(event) { let messagebox = document.getelementbyid("messagebox"); let sendbutton = document.getelementbyid("sendbutton"); messagebox.disabled = false; messagebox.focus(); sendbutton.disabled = false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.onopen' in that specification.
RTCDataChannel.ordered - Web APIs
syntax var ordered = adatachannel.ordered; a boolean value which is true if in-order delivery is guaranteed and is otherwise false.
RTCDataChannel.reliable - Web APIs
syntax var reliable = adatachannel.reliable; value true if the rtcdatachannel's connection is reliable; false if it isn't.
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
l 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.
RTCIceTransport: gatheringstatechange event - Web APIs
the addeventlistener() method is called to add a listener for gatheringstatechange events: pc.getsenders().foreach(sender => { sender.transport.icetransport.addeventlistener("gatheringstatechange", ev => { let transport = ev.target; if (transport.gatheringstate === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }, false); likewise, you can use the ongatheringstatechange event handler property: pc.getsenders().foreach(sender => { sender.transport.icetransport.ongatheringstatechange = ev => { let transport = ev.target; if (transport.gatheringstate === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }; }); specification...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
cetransport; let localprotoelem = document.getelementbyid("local-protocol"); let remoteprotoelem = document.getelementbyid("remote-protocol"); icetransport.addeventlistener("selectedcandidatepairchange", ev => { let pair = icetransport.getselectedcandidatepair(); localprotoelem.innertext = pair.local.protocol.touppercase(); remoteprotoelem.innertext = pair.remote.protocol.touppercase(); }, false) this can also be done by setting the onselectedcandidatepairchange event handler property directly.
RTCIceTransport: statechange event - Web APIs
let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.addeventlistener("statechange", ev => { if (icetransport.state === "failed") { handlefailure(pc); } }, false); the same code, using the onstatechange event handler property, looks like this: let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.onstatechange = ev => { if (icetransport.state === "failed") { handlefailure(pc); } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of...
RTCOfferOptions.iceRestart - Web APIs
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.
RTCPeerConnection.addTrack() - Web APIs
the rtcrtptransceiver's stopped property is false.
RTCPeerConnection: addstream event - Web APIs
you can also use the addeventlistener() method to set an event listener: pc.addeventlistener("addstream", ev => doaddstream(ev.stream), false); ...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
syntax var cantrickle = rtcpeerconnection.cantrickleicecandidates; value a boolean that is true if the remote peer can accept trickled ice candidates and false if it cannot.
RTCPeerConnection: connectionstatechange event - Web APIs
*/ } }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'connectionstatechange' in that specification.
RTCPeerConnection: datachannel event - Web APIs
pc.addeventlistener("datachannel", ev => { receivechannel = ev.channel; receivechannel.onmessage = myhandlemessage; receivechannel.onopen = myhandleopen; receivechannel.onclose = myhandleclose; }, false); receivechannel is set to the value of the event's channel property, which specifies the rtcdatachannel object representing the data channel linking the remote peer to the local one.
RTCPeerConnection: icegatheringstatechange event - Web APIs
} likewise, you can use addeventlistener() to add a listener for icegatheringstatechange events: pc.addeventlistener("icegatheringstatechange", ev => { let connection = ev.target; switch(connection.icegatheringstate) { case "gathering": /* collection of candidates has begun */ break; case "complete": /* collection of candidates is finished */ break; } }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'icecandidatestatechange' in that specification.
RTCPeerConnection: icecandidate event - Web APIs
first, an example using addeventlistener(): pc.addeventlistener("icecandidate", ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }, false); you can also set the onicecandidate event handler property directly: pc.onicecandidate = ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'icecandidate' in that specificatio...
RTCPeerConnection: negotiationneeded event - Web APIs
pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }, false); after creating the offer, the local end is configured by calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer.
RTCPeerConnection.onaddstream - Web APIs
pc.onaddstream = function(event) { document.getelementbyid("received_video").srcobject = event.stream; document.getelementbyid("hangup-button").disabled = false; }; you can also use addeventlistener() to add a handler for addstream events to an rtcpeerconnection.
RTCPeerConnection.ontrack - Web APIs
pc.ontrack = function(event) { document.getelementbyid("received_video").srcobject = event.streams[0]; document.getelementbyid("hangup-button").disabled = false; }; the first line of our ontrack event handler takes the first stream in the incoming track and sets the srcobject attribute to that.
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 browsersthe definition of 'rtcpeerconnection.removetrack()' in that specification.
RTCPeerConnection: signalingstatechange event - Web APIs
pc.addeventlistener("signalingstatechange", ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }, false); using onsignalingstatechange, it looks like this: pc.onsignalingstatechange = ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'signalingstatechange' in that specification.
RTCRtcpParameters - Web APIs
if false, compund rtcp is in use, as found in rfc 3550.
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.stopped - Web APIs
if either or both are still at work, the result is false.
RTCSessionDescription - Web APIs
example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var message = json.parse(evt.data); if (message.sdp) pc.setremotedescription(new rtcsessiondescription(message), function () { // if we received an offer, we need to answer if (pc.remotedescription.type == "offer") pc.createanswer(localdesccreated, logerror); }, logerror); else pc.addicecandidate(new rtcicecandidate(me...
RTCTrackEvent - Web APIs
peerconnection.addeventlistener("track", e => { let videoelement = document.getelementbyid("videobox"); videoelement.srcobject = e.streams[0]; }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtctrackevent' in that specification.
Range.collapsed - Web APIs
WebAPIRangecollapsed
it returns true if the start and end boundary points of the range are the same point in the dom, false if not.
ReadableStreamBYOBReader.read() - Web APIs
the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }.
ReadableStreamDefaultReader.read() - Web APIs
the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }.
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).
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).
SVGSVGElement - Web APIs
if the initial view is the "standard" view, then this attribute is false.
Screen.lockOrientation() - Web APIs
return value returns true if the orientation was authorized to be locked or false if the orientation locking was denied.
Screen.mozEnabled - Web APIs
WebAPIScreenmozEnabled
setting it to false will turn off the screen.
Screen.unlockOrientation() - Web APIs
syntax var unlocked = window.screen.unlockorientation(); return value returns true if the orientation was successfully unlocked or false if the orientation couldn't be unlocked.
Screen - Web APIs
WebAPIScreen
setting to false will turn off the device's screen.
Using the Screen Capture API - Web APIs
const videoelem = document.getelementbyid("video"); const logelem = document.getelementbyid("log"); const startelem = document.getelementbyid("start"); const stopelem = document.getelementbyid("stop"); // options for getdisplaymedia() var displaymediaoptions = { video: { cursor: "always" }, audio: false }; // set event listeners for the start and stop buttons startelem.addeventlistener("click", function(evt) { startcapture(); }, false); stopelem.addeventlistener("click", function(evt) { stopcapture(); }, false); logging content to make logging of errors and other issues easy, this example overrides certain console methods to output their messages to the <pre> block whose id is log.
ServiceWorkerGlobalScope: push event - Web APIs
self.addeventlistener("push", event => { let message = event.data.json(); switch(message.type) { case "init": doinit(); break; case "shutdown": doshutdown(); break; } }, false); specifications specification status comment push apithe definition of 'push' in that specification.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
istener("pushsubscriptionchange", event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { return fetch("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method.
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.
ShadowRoot.delegatesFocus - Web APIs
syntax var df = shadowroot.delegatesfocus value a boolean value — true if the shadow root does delegate focus, false if it doesn't.
SourceBuffer.removeAsync() - Web APIs
this method can only be called when updating is false.
SpeechRecognition() - Web APIs
casin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition.grammars - Web APIs
casin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition.lang - Web APIs
casin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition.maxAlternatives - Web APIs
casin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
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.
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.
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.
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.
Using the Storage Access API - Web APIs
if that call returns false, we can then call document.requeststorageaccess(), returning the result so that then we can chain it onto the previous promise call.
Using readable streams - Web APIs
n the pump() function seen above we first invoke read(), which returns a promise containing a results object — this has the results of our read in it, in the form { done, value }: return reader.read().then(({ done, value }) => { the results can be one of three different types: if a chunk is available to read, the promise will be fulfilled with an object of the form { value: thechunk, done: false }.
StyleSheet.disabled - Web APIs
note that disabled == false does not guarantee the style sheet is applied (it could be removed from the document, for instance).
SubtleCrypto.encrypt() - Web APIs
}, key, encoded ); } let iv = new uint8array(16); let key = new uint8array(16); let data = new uint8array(12345); //crypto functions are wrapped in promises so we have to use await and make sure the function that //contains this code is an async function //encrypt function wants a cryptokey object const key_encoded = await crypto.subtle.importkey( "raw", key.buffer, 'aes-ctr' , false, ["encrypt", "decrypt"]); const encrypted_content = await window.crypto.subtle.encrypt( { name: "aes-ctr", counter: iv, length: 128 }, key_encoded, data ); //uint8array console.log(encrypted_content); aes-cbc this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in cbc mode.
SubtleCrypto.verify() - Web APIs
return value result is a promise that fulfills with a boolean: true if the signature is valid, false otherwise.
SyncManager.register() - Web APIs
the default is false.
TextDecoder() - Web APIs
it defaults to false.
Touch.force - Web APIs
WebAPITouchforce
console.log("targettouches[" + i + "].force = " + e.targettouches[i].force); } }, false); specifications specification status comment touch events – level 2 draft initial definition.
Touch.identifier - Web APIs
WebAPITouchidentifier
for (var i=0; i < e.changedtouches.length; i++) { console.log("changedtouches[" + i + "].identifier = " + e.changedtouches[i].identifier); } }, false); specifications specification status comment touch events – level 2 draft no change.
Touch.pageX - Web APIs
WebAPITouchpageX
var i; for (i=0; i < e.changedtouches.length; i++) { console.log("touchpoint[" + i + "].pagex = " + e.changedtouches[i].pagex); console.log("touchpoint[" + i + "].pagey = " + e.changedtouches[i].pagey); } }, false); specifications specification status comment touch events – level 2 draft no change from the previous version.
Touch.pageY - Web APIs
WebAPITouchpageY
var i; for (i=0; i < e.changedtouches.length; i++) { console.log("touchpoint[" + i + "].pagex = " + e.changedtouches[i].pagex); console.log("touchpoint[" + i + "].pagey = " + e.changedtouches[i].pagey); } }, false); specifications specification status comment touch events – level 2 draft no change from last version.
Touch.screenX - Web APIs
WebAPITouchscreenX
var i; for (i=0; i < e.touches.length; i++) { console.log("touchpoint[" + i + "].screenx = " + e.touches[i].screenx); console.log("touchpoint[" + i + "].screeny = " + e.touches[i].screeny); } }, false); specifications specification status comment touch events – level 2 draft non-stable version.
Touch.target - Web APIs
WebAPITouchtarget
for (var i=0; i < e.targettouches.length; i++) { console.log("touchpoint[" + i + "].target = " + e.targettouches[i].target); } }, false); specifications specification status comment touch events – level 2 draft non-stable version.
TouchEvent.changedTouches - Web APIs
for (var i=0; i < e.changedtouches.length; i++) { console.log("changedtouches[" + i + "].identifier = " + e.changedtouches[i].identifier); } }, false); specifications specification status comment touch events – level 2 draft non-stable version.
TouchEvent.touches - Web APIs
switch (e.touches.length) { case 1: handle_one_touch(e); break; case 2: handle_two_touches(e); break; case 3: handle_three_touches(e); break; default: console.log("not supported"); break; } }, false); specifications specification status comment touch events – level 2 draft non-stable version.
TouchEvent - Web APIs
to override this behavior, you need to set the passive option to false, after which calling preventdefault() will work as specified.
TouchList.item() - Web APIs
WebAPITouchListitem
cument.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.targettouches.length >= 1) touch = ev.targettouches.item(0); else touch = ev.touches.item(0); }, false); specifications specification status comment touch events – level 2 draft non-stable version.
TouchList.length - Web APIs
WebAPITouchListlength
cument.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.targettouches.length >= 1) touch = ev.targettouches.item(0); else touch = ev.touches.item(0); }, false); specifications specification status comment touch events – level 2 draft non-stable version.
TrackEvent - Web APIs
var videoelem = document.queryselector("video"); videoelem.videotracks.addeventlistener("addtrack", handletrackevent, false); videoelem.videotracks.addeventlistener("removetrack", handletrackevent, false); videoelem.audiotracks.addeventlistener("addtrack", handletrackevent, false); videoelem.audiotracks.addeventlistener("removetrack", handletrackevent, false); videoelem.texttracks.addeventlistener("addtrack", handletrackevent, false); videoelem.texttracks.addeventlistener("removetrack", handletrackevent, false); func...
TreeWalker.currentNode - Web APIs
syntax node = treewalker.currentnode; treewalker.currentnode = node; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.currentnode; // the root element as it is the first element!
TreeWalker.filter - Web APIs
WebAPITreeWalkerfilter
syntax nodefilter = treewalker.filter; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = treewalker.filter; // document.body in this case specifications specification status comment domthe definition of 'treewalker.filter' in that specification.
TreeWalker.firstChild() - Web APIs
syntax node = treewalker.firstchild; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.firstchild(); // returns the first child of the root element, or null if none specifications specification status comment domthe definition of 'treewalker.firstchild' in that specification.
TreeWalker.lastChild() - Web APIs
syntax node = treewalker.lastchild(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.lastchild(); // returns the last visible child of the root element specifications specification status comment domthe definition of 'treewalker.lastchild' in that specification.
TreeWalker.nextNode() - Web APIs
syntax node = treewalker.nextnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.nextnode(); // returns the first child of root, as it is the next node in document order specifications specification status comment domthe definition of 'treewalker.nextnode' in that specification.
TreeWalker.nextSibling() - Web APIs
syntax node = treewalker.nextsibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); treewalker.firstchild(); var node = treewalker.nextsibling(); // returns null if the first child of the root element has no sibling specifications specification status comment domthe definition of 'treewalker.nextsibling' in that specification.
TreeWalker.parentNode() - Web APIs
syntax node = treewalker.parentnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.parentnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.parentnode' in that specification.
TreeWalker.previousNode() - Web APIs
syntax node = treewalker.previousnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previousnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.previousnode' in that specification.
TreeWalker.previousSibling() - Web APIs
syntax node = treewalker.previoussibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previoussibling(); // returns null as there is no previous sibiling specifications specification status comment domthe definition of 'treewalker.previoussibling' in that specification.
TreeWalker.root - Web APIs
WebAPITreeWalkerroot
syntax root = treewalker.root; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.root; // document.body in this case specifications specification status comment domthe definition of 'treewalker.root' in that specification.
TreeWalker.whatToShow - Web APIs
syntax nodetypes = treewalker.whattoshow; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); if( (treewalker.whattoshow == nodefilter.show_all) || (treewalker.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // treewalker will show comments } specifications specification status comment domthe definition of 'treewalker.whattoshow' in that specification.
UIEvent.cancelBubble - Web APIs
it is set to false by default, allowing the event to bubble up the dom, if it is a bubbleable event.
URLSearchParams.set() - Web APIs
'use strict' function genurl(rexp, atext, bdebug=false){ let theurl theurl= new url('https://regexr.com') theurl.searchparams.set( 'expression', rexp.tostring() ) theurl.searchparams.set( 'tool', 'replace' ) theurl.searchparams.set( 'input', '\u2911\u20dc' )// ⤑⃜ theurl.searchparams.set( 'text', atext.join('\n') ) if( bdebug ){ // display the key/value pairs for(var pair of theurl.searchparams.entries()) { console.debug(pair[0] + '...
URLSearchParams - Web APIs
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 searc...
UserProximityEvent.near - Web APIs
the near property tell if there is an object close to the device (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.
Visual Viewport API - Web APIs
let pendingupdate = false; function viewporthandler(event) { if (pendingupdate) return; pendingupdate = true; requestanimationframe(() => { pendingupdate = false; var layoutviewport = document.getelementbyid('layoutviewport'); // since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin.
WEBGL_lose_context.loseContext() - Web APIs
syntax gl.getextension('webgl_lose_context').losecontext(); examples with this method, you can simulate the webglcontextlost event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').losecontext(); // webglcontextevent event with type "webglcontextlost" is logged.
WEBGL_lose_context.restoreContext() - Web APIs
examples with this method, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); specifications specification status comment webgl_lose_contextthe definition of 'webgl_lose_context.losecontext' in that specification.
WebGL2RenderingContext.isQuery() - Web APIs
return value a glboolean indicating whether the given object is a valid webglquery object (true) or not (false).
WebGL2RenderingContext.isSampler() - Web APIs
return value a glboolean indicating whether the given object is a valid webglsampler object (true) or not (false).
WebGL2RenderingContext.isSync() - Web APIs
return value a glboolean indicating whether the given object is a valid webglsync object (true) or not (false).
WebGL2RenderingContext.isTransformFeedback() - Web APIs
return value a glboolean indicating whether the given object is a valid webgltransformfeedback object (true) or not (false).
WebGL2RenderingContext.isVertexArray() - Web APIs
return value a glboolean indicating whether the given object is a valid webglvertexarrayobject object (true) or not (false).
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
position gl.vertexattribpointer(0, 3, gl.float, false, 20, 0); gl.enablevertexattribarray(0); //2.
WebGLContextEvent.statusMessage - Web APIs
var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextcreationerror', function(e) { console.log('webgl context creation failed:' + e.statusmessage || 'unknown error'); }, false); specifications specification status comment webgl 1.0the definition of 'webglcontextevent.statusmessage' in that specification.
WebGLContextEvent - Web APIs
examples with the help of the webgl_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').losecontext(); // webglcontextevent event with type "webglcontextlost" is logged.
WebGLProgram - Web APIs
// use the program gl.useprogram(program); // bind existing attribute data gl.bindbuffer(gl.array_buffer, buffer); gl.enablevertexattribarray(attributelocation); gl.vertexattribpointer(attributelocation, 3, gl.float, false, 0, 0); // draw a single triangle gl.drawarrays(gl.triangles, 0, 3); deleting the program if there is an error linking the program or you wish to delete an existing program, then it is as simple as running webglrenderingcontext.deleteprogram().
WebGLRenderingContext.disable() - Web APIs
examples gl.disable(gl.dither); to check if a capability is disabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // false specifications specification status comment webgl 1.0the definition of 'disable' in that specification.
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
gl.bindbuffer(gl.array_buffer, vertexbuffer); avertexposition = gl.getattriblocation(shaderprogram, "avertexposition"); gl.enablevertexattribarray(avertexposition); gl.vertexattribpointer(avertexposition, vertexnumcomponents, gl.float, false, 0, 0); gl.drawarrays(gl.triangles, 0, vertexcount); this code snippet is taken from the function animatescene() in "a basic 2d webgl animation example." see that article for the full sample and to see the resulting animation in action.
WebGLRenderingContext.getContextAttributes() - Web APIs
en this <canvas> element <canvas id="canvas"></canvas> and given this webgl context var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getcontextattributes(); the getcontextattributes method returns an object that describes the attributes set on this context, for example: { alpha: true, antialias: true, depth: true, failifmajorperformancecaveat: false, powerpreference: "default", premultipliedalpha: true, preservedrawingbuffer: false, stencil: false, desynchronized: false } the context attributes can be set when creating the context using the htmlcanvaselement.getcontext() method: canvas.getcontext('webgl', { antialias: false, depth: false }); see getcontext() for more information about the indi...
WebGLRenderingContext.getTexParameter() - Web APIs
gl.texture_immutable_format glboolean immutability of the texture format and size true or false.
WebGLRenderingContext.getVertexAttrib() - Web APIs
otherwise false.
WebGLRenderingContext.isBuffer() - Web APIs
the webglrenderingcontext.isbuffer() method of the webgl api returns true if the passed webglbuffer is valid and false otherwise.
WebGLRenderingContext.isContextLost() - Web APIs
syntax let islost = gl.iscontextlost(); return value a boolean which is true if the context is lost, or false if not.
WebGLRenderingContext.isFramebuffer() - Web APIs
the webglrenderingcontext.isframebuffer() method of the webgl api returns true if the passed webglframebuffer is valid and false otherwise.
WebGLRenderingContext.isProgram() - Web APIs
the webglrenderingcontext.isprogram() method of the webgl api returns true if the passed webglprogram is valid, false otherwise.
WebGLRenderingContext.isRenderbuffer() - Web APIs
the webglrenderingcontext.isrenderbuffer() method of the webgl api returns true if the passed webglrenderbuffer is valid and false otherwise.
WebGLRenderingContext.isShader() - Web APIs
the webglrenderingcontext.isshader() method of the webgl api returns true if the passed webglshader is valid, false otherwise.
WebGLRenderingContext.isTexture() - Web APIs
the webglrenderingcontext.istexture() method of the webgl api returns true if the passed webgltexture is valid and false otherwise.
WebGLRenderingContext.pixelStorei() - Web APIs
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.
Canvas size and WebGL - Web APIs
" + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this example is also available on github.
Raining rectangles - Web APIs
does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } ;(function(){ "use strict" window.addeventlistener("load", setupanimation, false); var gl, timer, rainingrect, scoredisplay, missesdisplay; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) return; gl.enable(gl.scissor_test); rainingrect = new rectangle(); timer = settimeout(drawanimation, 17); document.queryselector("canvas") .addeventlistener("click", playerclick, fa...
Data in WebGL - Web APIs
WebAPIWebGL APIData
1.0, 0.0, 1.0 ), // green ]; var cbuffer = gl.createbuffer(); //continued //create buffer to store colors and reference it to "vcolor" which is in glsl gl.bindbuffer( gl.array_buffer, cbuffer ); gl.bufferdata( gl.array_buffer, flatten(vertexcolors), gl.static_draw ); var vcolor = gl.getattriblocation( program, "vcolor" ); gl.vertexattribpointer( vcolor, 4, gl.float, false, 0, 0 ); gl.enablevertexattribarray( vcolor ); //glsl attribute vec4 vcolor; void main() { fcolor = vcolor; } varyings varyings are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader.
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('...
Using shaders to apply color in WebGL - Web APIs
{ const numcomponents = 4; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.color); gl.vertexattribpointer( programinfo.attriblocations.vertexcolor, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexcolor); } view the complete code | open this demo on a ne...
Using textures in WebGL - Web APIs
first, the code to specify the colors buffer is gone, replaced with this: // tell webgl how to pull out the texture coordinates from buffer { const num = 2; // every coordinate composed of 2 values const type = gl.float; // the data in the buffer is 32 bit float const normalize = false; // don't normalize const stride = 0; // how many bytes to get from one set to the next const offset = 0; // how many bytes inside the buffer to start from gl.bindbuffer(gl.array_buffer, buffers.texturecoord); gl.vertexattribpointer(programinfo.attriblocations.texturecoord, num, type, normalize, stride, offset); gl.enablevertexattribarray(programinfo.attriblocations.texturecoo...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
async function enablehold(audiostream) { try { await audiotransceiver.sender.replacetrack(audiostream.getaudiotracks()[0]); audiotransceiver.receiver.track.enabled = false; audiotransceiver.direction = "sendonly"; } catch(err) { /* handle the error */ } } the three lines of code within the try block perform the following steps: replace their outgoing audio track with a mediastreamtrack containing hold music.
Using WebRTC data channels - Web APIs
to do this, simply call createdatachannel() without specifying a value for the negotiated property, or specifying the property with a value of false.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
<<<--- 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.
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.
Web audio spatialization basics - Web APIs
se is released: // for each of our controls, move the boombox and change the position values movecontrols.foreach(function(el) { let moving; el.addeventlistener('mousedown', function() { let direction = this.dataset.control; if (moving && moving.frameid) { window.cancelanimationframe(moving.frameid); } moving = moveboombox(direction); }, false); window.addeventlistener('mouseup', function() { if (moving && moving.frameid) { window.cancelanimationframe(moving.frameid); } }, false) }) summary hopefully, this article has given you an insight into how web audio spatialization works, and what each of the pannernode properties do (there are quite a few of them).
Window.closed - Web APIs
WebAPIWindowclosed
false: the window is open.
Window.find() - Web APIs
WebAPIWindowfind
returns true if the string is found; otherwise, false.
Window.fullScreen - Web APIs
WebAPIWindowfullScreen
false: the window is not in full screen mode.
Window: hashchange event - Web APIs
bubbles yes cancelable no interface hashchangeevent event handler onhashchange examples you can use the hashchange event in an addeventlistener method: window.addeventlistener('hashchange', function() { console.log('the hash has changed!') }, false); or use the onhashchange event handler property: function locationhashchanged() { if (location.hash === '#cool-feature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; specifications specification status comment html living standardthe definition of 'hashchange' in that specification.
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
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.
Window.navigator - Web APIs
WebAPIWindownavigator
syntax navigatorobject = window.navigator examples example #1: browser detect and return a string var sbrowser, susrag = navigator.useragent; // the order matters here, and this may report false positives for unlisted browsers.
Window: offline event - Web APIs
the offline event of the window interface is fired when the browser has lost access to the network and the value of navigator.online switches to false.
Window.onbeforeinstallprompt - Web APIs
tener("beforeinstallprompt", function(beforeinstallpromptevent) { beforeinstallpromptevent.preventdefault(); // prevents immediate prompt display // shows prompt after a user clicks an "install" button installbutton.addeventlistener("click", function(mouseevent) { // you should not use the mouseevent here, obviously beforeinstallpromptevent.prompt(); }); installbutton.hidden = false; // make button operable }); ...
Window.ondragdrop - Web APIs
WebAPIWindowondragdrop
<html> <head><title>dragdroptest</title> <script type="text/javascript"> window.addeventlistener("dragdrop", testfunc, false); function testfunc(event) { alert("dragdrop!"); event.stoppropagation(); } </script> </head> <body> i am bodytext </body> </html> specification not part of specification.
Window: pagehide event - Web APIs
window.addeventlistener("pagehide", event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }, false); this can also be written using the onpagehide event handler property on the window: window.onpagehide = event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } } specifications specification status comment html living standardthe definition of 'pagehide' in that specification.
Window: rejectionhandled event - Web APIs
no cancelable no interface promiserejectionevent event handler property onrejectionhandled example you can use the rejectionhandled event to log promises that get rejected to the console, along with the reasons why they were rejected: window.addeventlistener("rejectionhandled", event => { console.log("promise rejected; reason: " + event.reason); }, false); specifications specification status comment html living standardthe definition of 'rejectionhandled' in that specification.
Window.screenLeft - Web APIs
WebAPIWindowscreenLeft
dow.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenTop - Web APIs
WebAPIWindowscreenTop
dow.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenX - Web APIs
WebAPIWindowscreenX
dow.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); these work in exactly the same way as screenx/screeny.
Window.screenY - Web APIs
WebAPIWindowscreenY
dow.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); these work in exactly the same way as screenx/screeny.
WindowOrWorkerGlobalScope.isSecureContext - Web APIs
the issecurecontext read-only property of the windoworworkerglobalscope interface returns a boolean indicating whether the current context is secure (true) or not (false).
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false).
XMLDocument.async - Web APIs
WebAPIXMLDocumentasync
(it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
XMLDocument.load() - Web APIs
WebAPIXMLDocumentload
examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
eforegmt + "\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 state: secure common name (cn) = addons.mozilla.org organisation = mozilla corporation issuer = verisign, inc.
XMLHttpRequest.open() - Web APIs
if this value is false, the send() method does not return until the response is received.
XMLHttpRequest.overrideMimeType() - Web APIs
// interpret the received data as plain text req = new xmlhttprequest(); req.overridemimetype("text/plain"); req.addeventlistener("load", callback, false); req.open("get", url); req.send(); specifications specification status comment xmlhttprequestthe definition of 'overridemimetype()' in that specification.
XMLHttpRequest.responseType - Web APIs
xmlhttprequests are asynchronous by default; they are only placed in synchronous mode by passing false as the value of the optional async parameter when calling open().
XMLHttpRequest.withCredentials - Web APIs
the default is false.
XRPose - Web APIs
WebAPIXRPose
xrpose.emulatedposition read only a boolean value which is false if the position and orientation given by transform is obtained directly from a full six degree of freedom (6dof) xr device (that is, a device which tracks not only the pitch, yaw, and roll of the head but also the forward, backward, and side-to-side motion of the viewer).
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.
XRRigidTransform.inverse - Web APIs
*/ mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, objectmatrix); gl.uniformmatrix4fv(programinfo.uniformlocations.modelviewmatrix, false, modelviewmatrix); /* ...
XRSession: visibilitychange event - Web APIs
ibilitychange 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
if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.addeventlistener('click', onbuttonclicked); immersivebutton.innerhtml = 'enter xr'; immersivebutton.disabled = false; } else { console.log("webxr doesn't support immersive-vr mode!"); } }); } else { console.log("webxr is not available!"); } function onbuttonclicked() { if (!xrsession) { navigator.xr.requestsession('immersive-vr') .then((session) => { xrsession = session; // onsessionstarted() not shown for reasons of brevity and clarity.
XRWebGLLayer.framebuffer - Web APIs
opaque framebuffers initialized with the depth property set to false will not have a depth buffer and will rely on the coordinates alone to determine distance.
XRWebGLLayerInit.alpha - Web APIs
xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { alpha: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.alpha' in that specification.
msGetPropertyEnabled - Web APIs
return value type: boolean if false, the property is not enabled.
msPutPropertyEnabled - Web APIs
false = disable the property.
msthumbnailclick - Web APIs
example 2 // adds an overlay icon on your app pinned to the taskbar window.external.mssitemodeseticonoverlay(iconuri, tooltip); // removes an overlay icon window.external.mssitemodecleariconoverlay(); // pinned icons on your taskbar can be instructed to trigger specific events on your site from the taskbar // add an event handlerdocument.addeventlistener('msthumbnailclick', onbuttonclicked, false); // add the buttons var btnplay = window.external.mssitemodeaddthumbbarbutton(iconuri, tooltip); // refresh the taskbar window.external.mssitemodeshowthumbbar(); // call a javascript function when the button is pressed function onbuttonclicked(e) { switch (e.buttonid) { case btnplay: play(); break;} } see also microsoft api extensions ...
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.
Using the group role - Accessibility
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" tabindex="-1" src="images/treecontracted.gif" /> <span role="treeitem" tabindex="0">cats</span> </div> <div id="catgroup" role="group"> <div id="siamese" role="treeitem"> <span tabindex="-1">siamese</span> </div> <div id="tabby" role="treeitem"> <span tabindex="-1">tabby</span> </div> </div> </div> </div>...
Using the log role - Accessibility
<div id="chatarea" role="log"> <ul id="chatregion" aria-live="polite" aria-atomic="false"> <li>please choose a user name to begin using ajax chat.</li> </ul> <ul id="userlistregion" aria-live="off" aria-relevant="additions removals text"> </ul> </div> working examples: http://websiteaccessibility.donaldevans.com/2011/07/12/aria-log/ notes using the log role on an element implies that element has aria-live="polite".
Using the radio role - Accessibility
<h3 id="rg1_label">lunch options</h3> <ul 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 ...
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: form role - Accessibility
examples <div role="form" id="send-comment" aria-label="add a comment"> <label for="username">username</label> <input id="username" name="username" autocomplete="nickname" autocorrect="off" type="text"> <label for="email">email</label> <input id="email" name="email" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" type="text"> <label for="comment">comment</label> <textarea id="comment" name="comment"></textarea> <input value="comment" type="submit"> </div> it is recommended to use <form> instead.
ARIA: search role - Accessibility
examples <form id="search" role="search"> <label for="search-input">search this site</label> <input type="search" id="search-input" name="search" spellcheck="false"> <input value="submit" type="submit"> </form> accessibility concerns landmark roles are intended to be used sparingly, to identify larger overall sections of the document.
::before (:before) - CSS: Cascading Style Sheets
WebCSS::before
; position: absolute; border-color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; } javascript var list = document.queryselector('ul'); list.addeventlistener('click', function(ev) { if (ev.target.tagname === 'li') { ev.target.classlist.toggle('done'); } }, false); here is the above code example running live.
:disabled - CSS: Cascading Style Sheets
WebCSS:disabled
holder="address" disabled> <input type="text" placeholder="zip code" disabled> </fieldset> </form> css input[type="text"]:disabled { background: #ccc; } javascript // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').onchange = togglebilling; }, false); function togglebilling() { // select the billing text fields var billingitems = document.queryselectorall('#billing input[type="text"]'); // toggle the billing text fields for (var i = 0; i < billingitems.length; i++) { billingitems[i].disabled = !billingitems[i].disabled; } } result specifications specification status comment html living standa...
-webkit-animation - CSS: Cascading Style Sheets
false the browser doesn't support these prefixed css animations.
-webkit-transform-2d - CSS: Cascading Style Sheets
false the 2d css transforms prefixed with -webkit are not supported by the browser.
-webkit-transform-3d - CSS: Cascading Style Sheets
false the 3d css transforms prefixed with -webkit are not supported by the browser.
color-index - CSS: Cascading Style Sheets
candidate recommendation the value can now be negative, in which case it computes to false.
color - CSS: Cascading Style Sheets
WebCSS@mediacolor
candidate recommendation the value can now be negative, in which case it computes to false.
height - CSS: Cascading Style Sheets
WebCSS@mediaheight
candidate recommendation the value can now be negative, in which case it computes to false.
monochrome - CSS: Cascading Style Sheets
WebCSS@mediamonochrome
candidate recommendation the value can now be negative, in which case it computes to false.
prefers-contrast - CSS: Cascading Style Sheets
this keyword value evaluates as false in a boolean context.
prefers-reduced-data - CSS: Cascading Style Sheets
this keyword value evaluates as false in the boolean context.
prefers-reduced-motion - CSS: Cascading Style Sheets
alternatively, add gtk-enable-animations = false to the [settings] block of the gtk 3 configuration file.
prefers-reduced-transparency - CSS: Cascading Style Sheets
this keyword value evaluates as false in the boolean context.
width - CSS: Cascading Style Sheets
WebCSS@mediawidth
candidate recommendation the value can now be negative, in which case it computes to false.
At-rules - CSS: Cascading Style Sheets
WebCSSAt-rule
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.
Coordinate systems - CSS: Cascading Style Sheets
function update(e) { setcoords(e, "offset"); setcoords(e, "client"); setcoords(e, "page"); setcoords(e, "screen"); } inner.addeventlistener("mouseenter", update, false); inner.addeventlistener("mousemove", update, false); inner.addeventlistener("mouseleave", update, false); the event handler is in the update() method.
Using CSS animations - CSS: Cascading Style Sheets
var element = document.getelementbyid("watchme"); element.addeventlistener("animationstart", listener, false); element.addeventlistener("animationend", listener, false); element.addeventlistener("animationiteration", listener, false); element.classname = "slidein"; this is pretty standard code; you can get details on how it works in the documentation for eventtarget.addeventlistener().
Using CSS transitions - CSS: Cascading Style Sheets
<p>click anywhere to move the ball</p> <div id="foo"></div> using javascript you can make the effect of moving the ball to a certain position happen: var f = document.getelementbyid('foo'); document.addeventlistener('click', function(ev){ f.style.transform = 'translatey('+(ev.clienty-25)+'px)'; f.style.transform += 'translatex('+(ev.clientx-25)+'px)'; },false); with css you can make it smooth without any extra effort.
Testing media queries programmatically - CSS: Cascading Style Sheets
to do this, call the addlistener() method on the mediaquerylist object, with a callback function to invoke when the media query status changes (e.g., the media query test goes from true to false): // create the query list.
<color> - CSS: Cascading Style Sheets
html <div></div> <hr> <label for="color">enter a valid color value:</label> <input type="text" id="color"> css div { width: 100%; height: 200px; } javascript const inputelem = document.queryselector('input'); const divelem = document.queryselector('div'); function validtextcolor(stringtotest) { if (stringtotest === "") { return false; } if (stringtotest === "inherit") { return false; } if (stringtotest === "transparent") { return false; } const image = document.createelement("img"); image.style.color = "rgb(0, 0, 0)"; image.style.color = stringtotest; if (image.style.color !== "rgb(0, 0, 0)") { return true; } image.style.color = "rgb(255, 255, 255)"; image.style.color = stringtotest; return image.style.colo...
Guide to scroll anchoring - CSS: Cascading Style Sheets
you can check whether disabling scroll anchoring fixes the issue in firefox by changing layout.css.scroll-anchoring.enabled to false in about:config.
set:has-same-node() - EXSLT
returns true if the two node-sets have any nodes in common; otherwise false.
Getting Started - Developer guides
<button id="ajaxbutton" type="button">make a request</button> <script> (function() { var httprequest; document.getelementbyid("ajaxbutton").addeventlistener('click', makerequest); function makerequest() { httprequest = new xmlhttprequest(); if (!httprequest) { alert('giving up :( cannot create an xmlhttp instance'); return false; } httprequest.onreadystatechange = alertcontents; httprequest.open('get', 'test.html'); httprequest.send(); } function alertcontents() { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(httprequest.responsetext); } else { alert('there was a problem with the request.'); } } } })(); </scri...
Web Audio playbackRate explained - Developer guides
min="0.5" max="4" step="0.1" > <p>playback rate <span id="currentpbr">1</span></p> </form> and apply some javascript to it: window.onload = function () { var v = document.getelementbyid("myvideo"); var p = document.getelementbyid("pbr"); var c = document.getelementbyid("currentpbr"); p.addeventlistener('input',function(){ c.innerhtml = p.value; v.playbackrate = p.value; },false); }; finally, we listen for the input event firing on the <input> element, allowing us to react to the playback rate control being changed.
Audio and video manipulation - Developer guides
16); // roughly 60 frames per second }, doload: function() { this.video = document.getelementbyid("my-video"); this.c1 = document.getelementbyid("my-canvas"); this.ctx1 = this.c1.getcontext("2d"); var self = this; this.video.addeventlistener("play", function() { self.width = self.video.width; self.height = self.video.height; self.timercallback(); }, false); }, computeframe: function() { this.ctx1.drawimage(this.video, 0, 0, this.width, this.height); var frame = this.ctx1.getimagedata(0, 0, this.width, this.height); var l = frame.data.length / 4; for (var i = 0; i < l; i++) { var grey = (frame.data[i * 4 + 0] + frame.data[i * 4 + 1] + frame.data[i * 4 + 2]) / 3; frame.data[i * 4 + 0] = grey; frame.data[i * 4...
Mutation events - Developer guides
}, false); the event object is passed to the listener in a mutationevent (see its definition in the specification) for most events, and mutationnameevent for domattributenamechanged and domelementnamechanged.
Constraint validation - Developer guides
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).
Separate sites for mobile and desktop - Developer guides
and false positives are particularly scary — it could be embarrassing to serve desktop users your mobile site accidentally.
User input and controls - Developer guides
if you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired: element.addeventlistener("touchstart", handlestart, false);
 element.addeventlistener("touchcancel", handlecancel, false);
 element.addeventlistener("touchend", handleend, false);
 element.addeventlistener("touchmove", handlemove, false); where element is the dom element you want to register the touch events on.
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
let colorpicker = document.getelementbyid("colorpicker"); let box = document.getelementbyid("box"); let output = document.getelementbyid("output"); box.style.bordercolor = colorpicker.value; colorpicker.addeventlistener("input", function(event) { box.style.bordercolor = event.target.value; }, false); colorpicker.addeventlistener("change", function(event) { output.innertext = "color set to " + colorpicker.value + "."; }, false); the input event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker.
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
starting the download the code that starts the download (say, when the user clicks a "download" button), looks like this: function startdownload() { let imageurl = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2fmdn_logo-only_color.svg?1535749917189"; downloadedimg = new image; downloadedimg.crossorigin = "anonymous"; downloadedimg.addeventlistener("load", imagereceived, false); downloadedimg.src = imageurl; } we're using a hard-coded url here (imageurl), but that could easily come from anywhere.
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
s'), c = canvas.getcontext('2d'); c.fillstyle = 'hotpink'; function draw(x, y) { if (isdrawing) { c.beginpath(); c.arc(x, y, 10, 0, math.pi*2); c.closepath(); c.fill(); } } canvas.addeventlistener('mousemove', event => draw(event.offsetx, event.offsety) ); canvas.addeventlistener('mousedown', () => isdrawing = true); canvas.addeventlistener('mouseup', () => isdrawing = false); document.queryselector('a').addeventlistener('click', event => event.target.href = canvas.todataurl() ); result security and privacy <a> elements can have consequences for users’ security and privacy.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
its default value is false.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
this is only supported by mozilla-based browsers; use the standardized canvas.getcontext('2d', { alpha: false }) instead.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
the default, false, means the details are not visible.
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
if no match is found, it returns false.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
t event, which is sent when the user clicks the "submit" button: var form = document.queryselector("form"); var log = document.queryselector("#log"); form.addeventlistener("submit", function(event) { var data = new formdata(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\r"; }; log.innertext = output; event.preventdefault(); }, false); try this example out and see how there's never more than one result for the contact group.
<input type="reset"> - HTML: Hypertext Markup Language
WebHTMLElementinputreset
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.
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
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.
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
the permitted values for spellcheck are: false disable spell checking for this element.
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
var starttime = document.getelementbyid("starttime"); var valuespan = document.getelementbyid("value"); starttime.addeventlistener("input", function() { valuespan.innertext = starttime.value; }, false); when a form including a time input is submitted, the value is encoded before being included in the form's data.
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
the permitted values for spellcheck are: false disable spell checking for this element.
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
reportvalidity() returns true if the element's value passes validity checks; otherwise, returns false.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
instead, the stylesheet will be loaded on-demand, if and when the disabled attribute is changed to false or removed.
<picture>: The Picture element - HTML: Hypertext Markup Language
WebHTMLElementpicture
if the <source>'s media condition evaluates to false, the browser skips it and evaluates the next element inside <picture>.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
this is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
false : indicates that the element should not be spell checked.
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
if using server-sent events, make sure eventsource.withcredentials is false (it's the default value).
Feature Policy - HTTP
return false or error from an existing javascript api that provides access to feature.
Access-Control-Allow-Credentials - HTTP
if you don't need credentials, omit this header entirely (rather than setting its value to false).
NEL - HTTP
WebHTTPHeadersNEL
header type response header forbidden header name no syntax nel: { "report_to": "name_of_reporting_group", "max_age": 12345, "include_subdomains": false, "success_fraction": 0.0, "failure_fraction": 1.0 } specifications specification network error logging ...
X-DNS-Prefetch-Control - HTTP
on firefox, this can be changed by setting the network.dns.disableprefetchfromhttps preference to false.
HTTP headers - HTTP
WebHTTPHeaders
it is a structured header whose value is a boolean so possible values are ?0 for false and ?1 for true.
Link prefetching FAQ - HTTP
add this line to your prefs.js file located in your profile directory (or make the appropriate change via about:config): user_pref("network.prefetch-next", false); however, the theory is that if link prefetching needs to be disabled then there must be something wrong with the implementation.
Keyed collections - JavaScript
let sayings = new map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings) { console.log(key + ' goes ' + value); } // "cat goes meow" // "elephant goes toot" sayings.clear(); sayings.size; // 0 object and map compared traditionally, objects have been used to map strings to values.
Using Promises - JavaScript
capture these for analysis and handling by your code—or just to avoid having them cluttering up your output—by adding a handler for the unhandledrejection event, like this: window.addeventlistener("unhandledrejection", event => { /* you might start here by adding code to examine the promise specified by event.promise and the reason in event.reason */ event.preventdefault(); }, false); by calling the event's preventdefault() method, you tell the javascript runtime not to do its default action when rejected promises go unhandled.
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.
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
in non-strict code, the operation just returns false.
TypeError: "x" is not a non-null object - JavaScript
providing no object (like just a number), will throw an error: object.defineproperty({}, 'key', 1); // typeerror: 1 is not a non-null object object.defineproperty({}, 'key', null); // typeerror: null is not a non-null object a valid property descriptor object might look like this: object.defineproperty({}, 'key', { value: 'foo', writable: false }); weakmap and weakset objects require object keys weakmap and weakset objects store object keys.
TypeError: "x" is not a constructor - JavaScript
r 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); ...
TypeError: "x" is read-only - JavaScript
'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); obj.score = 0; // typeerror 'use strict'; object.defineproperty(this, 'lung_count', {value: 2, writable: false}); lung_count = 3; // typeerror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray[0]++; // typeerror there are also a few read-only properties built into javascript.
Arrow function expressions - JavaScript
correction: start note: the previous statement seems false.
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.
Functions - JavaScript
for example: if (shoulddefinezero) { function zero() { // danger: compatibility risk console.log("this is zero."); } } es2015 says that if shoulddefinezero is false, then zero should never be defined, since the block never executes.
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 obj...
ArrayBuffer - JavaScript
returns false otherwise.
Atomics.isLockFree() - JavaScript
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.
Atomics - JavaScript
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 int32array(sab); a reading thread is sleeping and waiting on location ...
BigInt64Array - JavaScript
bigint64array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
BigUint64Array - JavaScript
biguint64array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
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 btrue = new boolean(true); var btruestring = new boolean('true'); var bfalsestring = new boolean('false'); var bsulin = new boolean('su lin'); var barrayproto = new boolean([]); ...
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.
Boolean.prototype.valueOf() - JavaScript
examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification.
DataView.prototype.getBigInt64() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getBigUint64() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getFloat32() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getFloat64() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getInt16() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getInt32() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getUint16() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.getUint32() - JavaScript
if false or undefined, a big-endian value is read.
DataView.prototype.setBigInt64() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setBigUint64() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setFloat32() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setFloat64() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setInt16() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setInt32() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setUint16() - JavaScript
if false or undefined, a big-endian value is written.
DataView.prototype.setUint32() - JavaScript
if false or undefined, a big-endian value is written.
DataView - JavaScript
return new int16array(buffer)[0] === 256; })(); console.log(littleendian); // true or false 64-bit integer values because javascript does not currently include standard support for 64-bit integer values, dataview does not offer native 64-bit operations.
Date.prototype.toLocaleDateString() - JavaScript
to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats.
Error - JavaScript
{ var instance = new error(message, filename, linenumber); instance.name = 'customerror'; instance.foo = foo; object.setprototypeof(instance, object.getprototypeof(this)); if (error.capturestacktrace) { error.capturestacktrace(instance, customerror); } return instance; } customerror.prototype = object.create(error.prototype, { constructor: { value: error, enumerable: false, writable: true, configurable: true } }); if (object.setprototypeof){ object.setprototypeof(customerror, error); } else { customerror.__proto__ = error; } try { throw new customerror('baz', 'bazmessage'); } catch(e){ console.error(e.name); //customerror console.error(e.foo); //baz console.error(e.message); //bazmessage } specifications specification ...
Float32Array - JavaScript
float32array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Float64Array - JavaScript
float64array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Function.prototype.apply() - JavaScript
function.prototype.construct = function (aargs) { let fnewconstr = new function(""); fnewconstr.prototype = this.prototype; let onew = new fnewconstr(); this.apply(onew, aargs); return 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.length - JavaScript
the property attributes are: writable: false, enumerable: false, configurable: true.
Function.name - JavaScript
property attributes of function.name writable no enumerable no configurable yes note that in non-standard, pre-es2015 implementations the configurable attribute was false as well.
Int16Array - JavaScript
int16array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Int32Array - JavaScript
int32array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Int8Array - JavaScript
int8array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Intl.Collator.prototype.resolvedOptions() - JavaScript
examples using the resolvedoptions method var de = new intl.collator('de', { sensitivity: 'base' }) var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de" usedoptions.usage; // "sort" usedoptions.sensitivity; // "base" usedoptions.ignorepunctuation; // false usedoptions.collation; // "default" usedoptions.numeric; // false specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator.prototype.resolvedoptions' in that specification.
Intl.DateTimeFormat() constructor - JavaScript
possible values are true and false; the default is locale dependent.
Intl.DateTimeFormat.prototype.format() - JavaScript
s 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 - JavaScript
ions).format(date)); // → "2:00:00 pm aedt" // sometimes you want to be very precise options.fractionalseconddigits = 3; console.log(new intl.datetimeformat('en-au', options).format(date)); // → "2:00:00.200 pm aedt" // sometimes even the us needs 24-hour time options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, timezone: 'america/los_angeles' }; console.log(new intl.datetimeformat('en-us', options).format(date)); // → "12/19/2012, 19:00:00" // to specify options but use the browser's default locale, use 'default' console.log(new intl.datetimeformat('default', options).format(date)); // → "12/19/2012, 19:00:00" // sometimes it's helpful to include the period of the day options = {hour: "numeric...
Intl.Locale.prototype.caseFirst - JavaScript
false no special case ordering.
Intl.NumberFormat() constructor - JavaScript
possible values are true and false; the default is true.
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.clz32() - JavaScript
var asuint = x >>> 0; if (asuint === 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.
Math.fround() - JavaScript
es 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, or it is not-a-number (nan), math.fround() will return nan: math.fround('abc'); // nan math.fround(nan); // nan specifications specification ecmascript (ecma-262)the definition of 'math.f...
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.isFinite() - JavaScript
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 ...
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 specification ecmascript (ecma-262)the defi...
Number.prototype.toFixed() - JavaScript
this can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false .
Number.prototype.toLocaleString() - JavaScript
to check for support in es5.1 and later implementations, the requirement that illegal language tags are rejected with a rangeerror exception can be used: function tolocalestringsupportslocales() { var number = 0; try { number.tolocalestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } prior to es5.1, implementations were not required to throw a range error exception if tolocalestring is called with arguments.
Object.freeze() - JavaScript
for data properties of a frozen object, values cannot be changed, the writable and configurable attributes are set to false.
Object.preventExtensions() - JavaScript
object.preventextensions(empty); object.isextensible(empty); // === false // object.defineproperty throws when adding // a new property to a non-extensible object.
Object.prototype.__proto__ - JavaScript
() { 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...
Object.prototype.valueOf() - JavaScript
lus +"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
when console = {} */ }) .finally(function() { isloading = false; }); please do not add polyfills on mdn pages.
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
in strict mode, a false return value from the defineproperty() handler will throw a typeerror exception.
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 ecmascript (ecma-262)the definition of '[[delete]]' in that specification.
handler.get() - JavaScript
const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false }); const p = new proxy(obj, { get: function(target, property) { return 20; } }); p.a; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[get]]' in that specification.
handler.has() - JavaScript
const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { has: function(target, prop) { return false; } }); 'a' in p; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[hasproperty]]' in that specification.
handler.isExtensible() - JavaScript
const p = new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification.
handler.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 definit...
RangeError() constructor - JavaScript
ic values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "carrot"].includes(value) === false) { throw new rangeerror('the argument must be an "apple", "banana", or "carrot".') } } try { check("cabbage") } catch(error) { if(error instanceof rangeerror) { // handle the error } } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructors' in that specification.
RangeError - JavaScript
ic values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "carrot"].includes(value) === false) { throw new rangeerror('the argument must be an "apple", "banana", or "carrot".') } } try { check("cabbage") } catch(error) { if(error instanceof rangeerror) { // handle the error } } specifications specification ecmascript (ecma-262)the definition of 'rangeerror' in that specification.
Reflect.construct() - JavaScript
function oneclass() { this.name = 'one' } function otherclass() { this.name = 'other' } // 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 ...
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 specification ecmascript (ecma-262)the definition of 'reflect.deleteproperty' 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} ...
Reflect.preventExtensions() - JavaScript
reflect.preventextensions(empty) reflect.isextensible(empty) // === false difference from object.preventextensions() if the target argument to this method is not an object (a primitive), then it will cause a typeerror.
Reflect - JavaScript
my name is ${this.name}`); } } reflect.has(duck, 'color'); // true reflect.has(duck, 'haircut'); // false returning the object's own keys reflect.ownkeys(duck); // [ "name", "color", "greeting" ] adding a new property to the object reflect.set(duck, 'eyes', 'black'); // returns "true" if successful // "duck" now contains the property "eyes: 'black'" specifications specification ecmascript (ecma-262)the definition of 'reflect' in that specification.
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.
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.
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.
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.
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; while (r = re.exec("123 456")) console.log(r, "and re...
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.localeCompare() - JavaScript
to check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a rangeerror exception: function localecomparesupportslocales() { try { 'foo'.localecompare('bar', 'i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales the results provided by localecompare() vary between languages.
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.toLocaleUpperCase() - JavaScript
the following can return false: x.tolocalelowercase() === x.tolocaleuppercase().tolocalelowercase() examples using tolocaleuppercase() 'alphabet'.tolocaleuppercase(); // 'alphabet' 'gesäß'.tolocaleuppercase(); // 'gesÄss' 'i\u0307'.tolocaleuppercase('lt-lt'); // 'i' let locales = ['lt', 'lt', 'lt-lt', 'lt-u-co-phonebk', 'lt-x-lietuva']; 'i\u0307'.tolocaleuppercase(locales); // 'i' specifications specificat...
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...
Symbol() constructor - JavaScript
it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
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 ecmascript (ecma-262)the definition of 'symbol.for...
Symbol.isConcatSpreadable - JavaScript
able no enumerable no configurable no examples arrays by default, array.prototype.concat() spreads (flattens) arrays into its result: let alpha = ['a', 'b', 'c'], let numeric = [1, 2, 3] let alphanumeric = alpha.concat(numeric) console.log(alphanumeric) // result: ['a', 'b', 'c', 1, 2, 3] when setting symbol.isconcatspreadable to false, you can disable the default behavior: let alpha = ['a', 'b', 'c'], let numeric = [1, 2, 3] numeric[symbol.isconcatspreadable] = false let alphanumeric = alpha.concat(numeric) console.log(alphanumeric) // result: ['a', 'b', 'c', [1, 2, 3] ] array-like objects for array-like objects, the default is to not spread.
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 - JavaScript
it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
TypedArray.prototype.filter() - JavaScript
return true to keep the element, false otherwise.
TypedArray.prototype.find() - JavaScript
function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 5, 8, 12]); console.log(uint8.find(isprime)); // 5 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.find' in that specification.
TypedArray.prototype.findIndex() - JavaScript
function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 6, 8, 12]); var uint16 = new uint16array([4, 6, 7, 12]); console.log(uint8.findindex(isprime)); // -1, not found console.log(uint16.findindex(isprime)); // 2 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.findindex' in that specification.
TypedArray - JavaScript
typedarray.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Uint16Array - JavaScript
uint16array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Uint32Array - JavaScript
uint32array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Uint8Array - JavaScript
uint8array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
Uint8ClampedArray - JavaScript
uint8clampedarray.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate.
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.
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.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.
WebAssembly.Global() constructor - JavaScript
by default, this is false.
WebAssembly.Memory() constructor - JavaScript
the default is false.
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).
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 specification.
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-262)the definition of 'assignment operators' in that specification.
Destructuring assignment - JavaScript
function parseprotocol(url) { const parsedurl = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); if (!parsedurl) { return false; } 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: ...
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.
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.
new operator - JavaScript
the object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole new expression.
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.
this - JavaScript
urrenttarget and target are the same object console.log(this === e.target); this.style.backgroundcolor = '#a5d9f3'; } // get a list of every element in the document var elements = document.getelementsbytagname('*'); // add bluify as a click listener so when the // element is clicked on, it turns blue for (var i = 0; i < elements.length; i++) { elements[i].addeventlistener('click', bluify, false); } in an inline event handler when the code is called from an inline on-event handler, its this is set to the dom element on which the listener is placed: <button onclick="alert(this.tagname.tolowercase());"> show this </button> the above alert shows button.
typeof - JavaScript
; // 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 !
void operator - JavaScript
it should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns undefined examples immediately invoked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.
Expressions and operators - JavaScript
iftrue : iffalse) the conditional operator returns one of two values based on the logical value of the condition.
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.
for...of - JavaScript
} 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.
for - JavaScript
if the expression evaluates to false, execution skips to the first expression following the for construct.
function declaration - JavaScript
typeof foo is ${typeof foo}`); if (false) { function foo(){ return 1; } } // in chrome: // 'foo' name is hoisted.
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).
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.
while - JavaScript
when condition evaluates to false, execution continues with the statement after the while loop.
JavaScript reference - JavaScript
iftrue : 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.
JavaScript typed arrays - JavaScript
however, typed arrays are not to be confused with normal arrays, as calling array.isarray() on a typed array returns false.
prefer_related_applications - Web app manifests
if omitted, prefer_related_applications defaults to false.
MathML attribute reference - MathML
displaystyle <mstyle>, <mtable> a boolean value specifying whether more vertical space is used for displayed equations or, if set to false, a more compact layout is used to display formulas.
<mfrac> - MathML
WebMathMLElementmfrac
otherwise, if set to false (which is the default value), numerator and denominator are on top of each other.
<mover> - MathML
WebMathMLElementmover
if false (default value) the over-script is a limit over the base expression.
<mstyle> - MathML
WebMathMLElementmstyle
displaystyle a boolean value specifying whether more vertical space is used for displayed equations or, if set to false, a more compact layout is used to display formulas.
<munder> - MathML
WebMathMLElementmunder
if false (default value), the element is a limit under the base expression.
Web video codec guide - Web media technologies
these occur along block borders, in the form of sharp edges that produce false ringing and other edge effects.
SVG Conditional Processing Attributes - SVG: Scalable Vector Graphics
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.
requiredExtensions - SVG: Scalable Vector Graphics
if a null string or empty string value is given, the attribute evaluates to "false".
textLength - SVG: Scalable Vector Graphics
("widthdisplay"); const textelement = document.getelementbyid("hello"); const baselength = math.floor(textelement.textlength.baseval.value); widthslider.value = baselength; widthslider.addeventlistener("input", function(event) { textelement.textlength.baseval.newvaluespecifiedunits( svglength.svg_lengthtype_px, widthslider.valueasnumber); widthdisplay.innertext = widthslider.value; }, false); widthslider.dispatchevent(new event("input")); after fetching the element references, an eventlistener is established by calling addeventlistener() on the slider control, to receive any input events which occur.
<switch> - SVG: Scalable Vector Graphics
WebSVGElementswitch
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
WebSVGIndex
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.
Example - SVG: Scalable Vector Graphics
</div> <form action="" onsubmit="return false;"> <p> <label>number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>max.
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
function myrect(x,y,w,h,message){ this.message=message this.rect=document.createelementns("http://www.w3.org/2000/svg","rect") this.rect.setattributens(null,"x",x) this.rect.setattributens(null,"y",y) this.rect.setattributens(null,"width",w) this.rect.setattributens(null,"height",h) document.documentelement.appendchild(this.rect) this.rect.addeventlistener("click",this,false) this.handleevent= function(evt){ switch (evt.type){ case "click": alert(this.message) break; } } } inter-document scripting: referencing embedded svg when using svg within html, adobe's svg viewer 3.0 automatically includes a window property called svgdocument that points to the svg document.
Web Components
event extensions extensions to the event interface related to shadow dom: event.composed: returns a boolean which indicates whether the event will propagate across the shadow dom boundary into the standard dom (true), or not (false).
not - XPath
WebXPathFunctionsnot
returns true for an expression that evaluates to false; false for an expression that evaluates to true.
number - XPath
false is converted to 0.
string - XPath
boolean false is converted to the string false.
Functions - XPath
boolean() ceiling() choose() concat() contains() count() current() xslt-specific document() xslt-specific element-available() false() floor() format-number() xslt-specific function-available() generate-id() xslt-specific id() (partially supported) key() xslt-specific lang() last() local-name() name() namespace-uri() normalize-space() not() number() position() round() starts-with() string() string-length() substring() substring-after() substring-before() sum() system-property() xslt-specific translate(...
Introduction to using XPath in JavaScript - XPath
var req = new xmlhttprequest(); req.open("get", "chrome://yourextension/content/peopledb.xml", false); req.send(null); var xmldoc = req.responsexml; var nsresolver = xmldoc.creatensresolver( xmldoc.ownerdocument == null ?
<xsl:when> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementwhen
if true, the contents of the element are processed; if false, they are ignored.
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
xes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-available() (supported) generate-id() (supported) id() (partially supported) key() (supported) lang() (supported) last() (supported) local-name() (supported) name() (supported) namespace-uri() (supported) normalize-space() (supported) not() (supported) number() (supported) position() (supported) ...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
ed) axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-available() (supported) generate-id() (supported) id() (partially supported) key() (supported) lang() (supported) last() (supported) local-name() (supported) name() (supported) namespace-uri() (supported) normalize-space() (supported) not() (supported) number() (supported) position() (supported) round() (suppor...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
var testtransform = document.implementation.createdocument("", "test", null); // just an example to get a transform into a script as a dom // xmldocument.load is asynchronous, so all processing happens in the // onload handler testtransform.addeventlistener("load", onload, false); testtransform.load("test-transform.xml"); function onload() { processor.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a dom node.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
figure 7: sorting based on div contentview example // xhtml fragment: <div id="example"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</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 ...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
figure 6 : example var xslstylesheet; var xsltprocessor = new xsltprocessor(); var mydom; var xmldoc; function init(){ // load the xslt file, example1.xsl var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xsl", false); myxmlhttprequest.send(null); xslstylesheet = myxmlhttprequest.responsexml; xsltprocessor.importstylesheet(xslstylesheet); // load the xml file, example1.xml myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xml", false); myxmlhttprequest.send(null); xmldoc = myxmlhttprequest.responsexml; var fragment = xsltprocessor.transformtofragment(xmldoc...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in conjunction with the imported xsl file to p...